@outbuild-company/schedule-core 1.2.0 → 1.4.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.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var ni=Object.defineProperty;var Ql=Object.getOwnPropertyDescriptor;var td=Object.getOwnPropertyNames;var ed=Object.prototype.hasOwnProperty;var rd=(e,t)=>{for(var r in t)ni(e,r,{get:t[r],enumerable:!0})},id=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of td(t))!ed.call(e,n)&&n!==r&&ni(e,n,{get:()=>t[n],enumerable:!(i=Ql(t,n))||i.enumerable});return e};var nd=e=>id(ni({},"__esModule",{value:!0}),e);var Oy={};rd(Oy,{ACTIVITY_TYPE:()=>ze,CALENDAR_UNIT:()=>nt,COLUMN:()=>_,CONSTRAINT_TYPE:()=>Y,CONSTRAINT_TYPE_TO_LABEL:()=>zl,CREATION_KIND:()=>Xl,DEFAULT_HOURS_PER_DAY:()=>ql,DISPATCH_ACTION_KIND:()=>G,DISPATCH_ACTION_KINDS:()=>Jl,DISPATCH_TRACK_EVENT:()=>yt,LINK_CODE_TO_TYPE:()=>qt,LINK_TYPE:()=>M,LINK_TYPE_CODE:()=>qa,NEW_ACTIVITY_DEFAULTS:()=>Rr,REJECTION_REASON:()=>P,ROOT_PARENT_ID:()=>H,ScheduleCore:()=>ei,WORK_TIME_DIRECTION:()=>q,checkNoUpdatedLinks:()=>Gl,computeExpectedProgress:()=>ki,expectedProgressFromBaseline:()=>ve,getActiveBaseline:()=>rt,getUnsavedActivities:()=>Kl,isRootParent:()=>b,normalizeParentKey:()=>zt,parseFromBackend:()=>Kr,willRunCriticalPath:()=>Xc,yieldToBrowser:()=>at});var ft=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var Ye=e=>String(e);function On(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Ye(t),l=new Set([...i].map(String)),d=new Set(l),u=ad(c,n).filter(s),f=u.filter(g=>!a(g)),h=r&&f.length<u.length;r&&!h?d.add(c):d.delete(c);for(let g of f)r?d.add(g):d.delete(g);return h||sd({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:od(l,d),parentBlocked:h}}function ad(e,t){let r=[],i=new ft;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let s of t.getChildrenIds(a)){let o=Ye(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function sd(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:s,next:o}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=Ye(c);if(a(l))return;let d=n.getChildrenIds(l).map(Ye).filter(s),u=d.some(a),f=d.filter(C=>!a(C)),g=f.length>0&&f.every(C=>o.has(C))&&!u;if(r){if(!i||!g||o.has(l))return;o.add(l)}else{if(g||!o.has(l))return;o.delete(l)}c=n.getParentId(l)}}function od(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function ne(e){return(e.pendingRequestIds?.length??0)>0}var P={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var xn=(e,t)=>{let r=e.getActivity(t);return r!=null&&ne(r)},Nn=(e,t,r)=>{let i=[],n=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&i.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)n(a,!0);for(let a of r.unchecked)n(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function Fn(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?o=>n.has(o):o=>xn(r,o),s=On({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:o=>r.getChildren(o),getParentId:o=>{let c=r.getParentId(o);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:o=>r.activityExists(o),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:Nn(e,r,s.changed)}}function Mn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!xn(r,s))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(s=>!n.has(s)),unchecked:[...n].filter(s=>!i.has(s))};return{ok:!0,changes:Nn(e,r,a)}}function Wn(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=[];return r.forEachActivity((s,o)=>{let c=String(o),l=i.has(c),d=r.isVisible(c);d!==l&&(r.setVisible(c,l),n.push({activityId:c,visible:{before:d,after:l}}))}),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Un="text";var Bn="description";var Hn="duration";var jn="progress";var Vn="cost";var Yn="used_cost";var $n="hhWorkTime";var Gn="start_date";var Kn="end_date";var zn="constraint_type";var qn="constraint_date";var Jn="calendar_id";var Xn="custom_id";var Zn="subcontractId";var Qn="responsables";var ta="tags";var ea="custom_predecessors";var ra="custom_sucessors";var ia="real_work";var na="real_cost";var aa="expected_progress";var sa="expected_progress_base";var oa="start_base";var ca="end_base";var la="duration_base";var da="cost_base";var ua="work_base";var fa="calendarDuration";var pa="is_critical",ha="earlyStart",ya="earlyFinish",ma="lateStart",ga="lateFinish",va="freeSlack",Aa="totalSlack";var Ca="correlative_id";var Ia="unique_correlative_id";var Sa="ponderator";var q={FUTURE:"future",PAST:"past"},nt={HOUR:"hour",DAY:"day"},Ot={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var $e="status";var ai="Baseline";function Ge(e){return e==="Actual"?"Actual":ai}var cd={TEXT:Un,DESCRIPTION:Bn,DURATION:Hn,PROGRESS:jn,COST:Vn,USED_COST:Yn,HH_WORK_TIME:$n,START_DATE:Gn,END_DATE:Kn,CONSTRAINT_TYPE:zn,CONSTRAINT_DATE:qn,CALENDAR_ID:Jn,CUSTOM_ID:Xn,SUBCONTRACT_ID:Zn,RESPONSABLES:Qn,TAGS:ta,CUSTOM_PREDECESSORS:ea,CUSTOM_SUCESSORS:ra},ld={REAL_WORK:ia,REAL_COST:na,EXPECTED_PROGRESS:aa,EXPECTED_PROGRESS_BASE:sa,START_BASE:oa,END_BASE:ca,DURATION_BASE:la,COST_BASE:da,WORK_BASE:ua,CALENDAR_DURATION:fa,IS_CRITICAL:pa,EARLY_START:ha,EARLY_FINISH:ya,LATE_START:ma,LATE_FINISH:ga,FREE_SLACK:va,TOTAL_SLACK:Aa,CORRELATIVE_ID:Ca,UNIQUE_CORRELATIVE_ID:Ia,PONDERATOR:Sa,STATUS:$e},_={...cd,...ld};function ka(e,t){throw new Error(t)}function Da(e,t){return()=>t()===e}var Y={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},dd={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function _a(e,t,r){if(!t)return{violated:!1};let i=dd[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var ud=new Set(["mso","snet","snlt"]);function _e(e,t,r){return ud.has(e)?t:r}function Pa(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var fd={snet:{startOfDay:!0,direction:q.FUTURE},snlt:{startOfDay:!0,direction:q.PAST},fnet:{startOfDay:!1,direction:q.FUTURE},fnlt:{startOfDay:!1,direction:q.PAST},mso:{startOfDay:!0,direction:q.FUTURE},mfo:{startOfDay:!1,direction:q.PAST}},Ke=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Ta=(e,t)=>new Date(e.getTime()+t*864e5),pd=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function si(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=fd[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Ke(i),dir:q.FUTURE,task:e});if(pd(n,i))return i.getTime()!==Ke(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Ta(Ke(i),1),dir:q.PAST,task:e});let a=Ke(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:q.FUTURE,task:e}):t.getClosestWorkTime({date:Ta(a,1),dir:q.PAST,task:e})}function Ea(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i==="asap"||i==="alap")return r;let n=si(e,t);if(!n)return r;let a=o=>t.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e}),s=o=>t.calculateEndDate({startDate:o,durationHours:-e.durationHours,task:e});switch(i){case"snet":return{earliestStart:n,latestStart:null,earliestEnd:a(n),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:a(n)};case"fnet":return{earliestStart:s(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(n),earliestEnd:null,latestEnd:n};case"mso":{let o=a(n);return{earliestStart:n,latestStart:n,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(n);return{earliestStart:o,latestStart:o,earliestEnd:n,latestEnd:n}}default:return r}}function Ra(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function oi(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var M={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var ze={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},La={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var qe=typeof window>"u",ci=!qe&&typeof MessageChannel<"u"?new MessageChannel:null;function at(){return qe||!ci?Promise.resolve():new Promise(e=>{ci.port1.onmessage=()=>e(),ci.port2.postMessage(null)})}async function Je(e,t){return performance.now()-e<La.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await at(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ae(e){return qe||await at(),e()?{aborted:!1}:{aborted:!0}}function Xe(e,t){let{inDegree:r,successors:i}=hd(e,t),n=yd(r),a=md(n,r,i),s=a.length<e.length,o=s?gd(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function hd(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let a=n.source,s=n.target;!r.has(a)||!r.has(s)||(i.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:i}}function yd(e){let t=new ft;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function md(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return i}function gd(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Ze=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Xe(t,r),this.cached)}};function ba(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var li={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function di(e){return e==="project"||e==="task"||e==="milestone"}function _t(e,t){return t||di(e)&&li[e].alwaysSummary}function Kt(e){return e==="milestone"}function xt(e){return di(e)&&li[e].promotesToProjectOnFirstChild}var ui="project",se="task";function Pe(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function wa(e,t){let r=t.getActivity(e);return r?_t(r.type,t.getChildren(e).length>0):!1}function Oa(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function Fa(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);if(a.length===0){String(n)!==String(e)&&r.push(n);continue}for(let s of a)i.push(s)}return r}function vd(e){let t=new Map;for(let r of e)xa(t,String(r.source),r),xa(t,String(r.target),r);return t}function xa(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function Ad(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let s of e)Cd(s,n,t,r,i)||a.push(s);return a.length>0?a:e}function Cd(e,t,r,i,n){let a=String(e),s=r.getActivity(e);if(!s||s.autoScheduling===!1)return!1;let o=i.get(a)??[];for(let c of o)if(Id(c,a,s,t,r,n))return!0;return!1}function Id(e,t,r,i,n,a){if(Sd(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=kd(e,t);if(!i.has(String(o)))return!1;let c=n.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Dd(e,r,c))}function Sd(e){return e.source===e.target}function kd(e,t){return String(e.source)===t?e.target:e.source}function Dd(e,t,r){let i=e.lag??0,n=Math.abs(i);return String(e.target)===String(r.id)&&n<=r.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function Ma(e,t){let r=[],i=vd(e),n=0;for(let a of e){let s=wa(a.source,t),o=wa(a.target,t);if(Td(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Na(a.source,s,t,i,!0),l=Na(a.target,o,t,i,!1);n=wd(r,c,l,a,t,n,i)}return r}function Td(e,t,r,i){return r&&Oa(e.source,e.target,i)||t&&Oa(e.target,e.source,i)}function Na(e,t,r,i,n){return t?Ad(Fa(e,r),r,i,n):[e]}function _d(e,t,r){let i=Fa(e,t);if(i.length===0)return null;let n=null,a=null;for(let s of i){let o=r(s);if(!o)continue;(n===null||o.startDate<n)&&(n=o.startDate),(a===null||o.endDate>a)&&(a=o.endDate)}return n===null||a===null?null:{startDate:n,endDate:a}}function Qe(e,t){return _d(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function Pd(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Ed(e,t,r,i){if(!t)return 0;let n=i.getActivity(e);return!r||!n?-t.durationHours:-i.calculateDuration({startDate:r.startDate,endDate:n.endDate,task:t})}function Rd(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function Ld(e,t,r,i,n){if(Rd(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function bd(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Qe(e.source,t),a=Qe(e.target,t),s=e.type===M.START_TO_START||e.type===M.START_TO_FINISH,o=e.type===M.FINISH_TO_FINISH||e.type===M.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:a?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-Pd(i,a,t):0,summarySourceId:e.type===M.START_TO_START&&n?e.source:void 0}}function wd(e,t,r,i,n,a,s){let o=bd(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:h,summarySourceId:g}=o,C=a;for(let A of t){let k=f?Ed(A,c,l,n):0;for(let S of r){if(String(A)===String(S))continue;let D=Ld(S,d,c,n,s);e.push(Od(i,A,S,C,k,h,u+D,g,D!==0&&h===0?i.target:void 0)),C+=1}}return C}function Od(e,t,r,i,n,a,s,o,c){return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,_sourceLag:n,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var tr=class{invalidate(){}get(t,r){return Ma(t,r)}};function xd(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function Nd(e,t,r){let i=new Set,n=new Map,a=new ft;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(i.has(o))continue;i.add(o);let c=r.neighbors.get(s);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===o?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function Wa(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=xd(t),n=Nd(e,r,i),a=new Set([String(e)]);for(let s of n)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:n}}function Ua(e,t,r){let i=r.type===M.FINISH_TO_START,n=r.type===M.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case M.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case M.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case M.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case M.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1}}}function Fd(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Qe(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function Md(e,t,r,i,n){let a=t.durationHours===0&&n;return{successorStart:i.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function Ba(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=Ua(e,t,r),l=Fd(r,e,i)??n,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Md(e,t,r,i,o||c);let h=o?t:e,g=i.getClosestWorkTime({date:e.endDate,dir:"future",task:h});if(l!==0&&(g=i.calculateEndDate({startDate:g,durationHours:l,task:e})),a!==0&&(g=i.calculateEndDate({startDate:g,durationHours:a,task:t})),s!==0&&(g=i.calculateEndDate({startDate:g,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:g,dir:"past",task:t}),link:r};let C=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:C,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}function Ha(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=Ua(t,e,r),o=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-a,task:e})),n!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-n,task:t})),o}function ja(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===Y.ASAP||a===Y.ALAP)continue;let s=Ea(n,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function er(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;n===null?a=oi(e.startDate,i):Ra(n,i)?a=n:a=oi(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Va(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case Y.MSO:case Y.MFO:return new Date(i);case Y.SNET:case Y.FNET:return i>t?new Date(i):t;case Y.SNLT:case Y.FNLT:return i<t?new Date(i):t;default:return t}}function Wd(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Ya(e,t,r){return fi(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function fi(e,t,r){return t.dragWithMultiple&&Wd(e,r)}async function Ga(e,t,r,i,n,a){let s=new Map;for(let u of t){let f=String(u.target);s.has(f)||s.set(f,[]),s.get(f).push(u)}let o=u=>{let f=a.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let h=r.getActivity(u);return h?{startDate:h.startDate,endDate:h.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await Je(d,n);if(f.aborted)return a;d=f.newSliceStart;let h=r.getActivity(u);if(!h||!h.autoScheduling||h.progress===100||Ud(h,r))continue;let g=s.get(String(u))??[],C=null,A=null,k=!1;for(let v of g){let E=r.getActivity(v.source);if(!E)continue;let T=o(v.source),R=T.startDate.getTime()!==E.startDate.getTime()||T.endDate.getTime()!==E.endDate.getTime(),O={...E,startDate:T.startDate,endDate:T.endDate},N=Ya(O,c,l),X={...O,startDate:N.startDate,endDate:N.endDate},z=fi(v.source,c,l)?{...v,lag:0}:v,gt=Ba(X,h,z,r);(!C||gt.successorStart>C)&&(C=gt.successorStart,A=String(v.id),k=v._summaryTargetId!==void 0&&!R)}C!==null&&k&&C<h.startDate&&(C=new Date(h.startDate));let D=a.get(u),p=D?{...D}:{activityId:u,startDate:h.startDate,endDate:h.endDate,drivingLinkId:null,kind:"asap",conflict:!1},y=p.earliestStart||p.latestStart||p.earliestEnd||p.latestEnd;if(!(!C&&!y)){if(C){let v=C;h.type===ze.MILESTONE&&(v=Va(h,C)),p.drivingLinkId=A,p.startDate=v,p.endDate=r.calculateEndDate({startDate:v,durationHours:h.durationHours,task:h}),p.earliestSchedulingStart=v,p.earliestSchedulingEnd=p.endDate}else h.constraintType===Y.MSO?p.earliestStart&&(p.startDate=p.earliestStart,p.endDate=p.earliestEnd??r.calculateEndDate({startDate:p.earliestStart,durationHours:h.durationHours,task:h})):h.constraintType===Y.MFO&&p.latestStart&&(p.startDate=p.latestStart,p.endDate=p.latestEnd??r.calculateEndDate({startDate:p.latestStart,durationHours:h.durationHours,task:h}));er(h,p,r),a.set(u,p)}}return a}function Ud(e,t){return _t(e.type,t.getChildren(e.id).length>0)}var H="0";function b(e){return e==null||e===0||e==="0"}function zt(e){return b(e)?"0":String(e)}async function Ka(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let A of o)A.constraintType===Y.ALAP&&l.push(A.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let A of t){let k=String(A.source);d.has(k)||d.set(k,[]),d.get(k).push(A);let S=String(A.target);u.has(S)||u.set(S,[]),u.get(S).push(A)}let f=A=>{let k=s.get(A);if(k)return{startDate:k.startDate,endDate:k.endDate};let S=i.getActivity(A);return S?{startDate:S.startDate,endDate:S.endDate}:{startDate:new Date,endDate:new Date}},h=A=>!A.parentId||b(A.parentId)?i.getProjectEnd():f(A.parentId).endDate,g=(A,k)=>{let S=A,D=0;for(;S&&!b(S)&&D++<c+1;){if(String(S)===String(k))return!0;let p=i.getActivity(S);if(!p||!p.parentId)break;S=p.parentId}return!1},C=performance.now();for(let A of e){let k=await Je(C,a);if(k.aborted)return s;C=k.newSliceStart;let S=i.getActivity(A);if(!S||S.constraintType!==Y.ALAP||!S.autoScheduling||S.progress===100||_t(S.type,i.getChildren(A).length>0))continue;let D=h(S);if(!D)continue;let p=D,y=null,v=!1,E=d.get(String(A))??[];for(let At of E){if((At.lag??0)<0)continue;let ie=i.getActivity(At.target);if(!ie||ie.autoScheduling===!1)continue;let wn=f(At.target),Zl={...ie,startDate:wn.startDate,endDate:wn.endDate},Ve=Ha(Zl,S,At,i);Ve<p&&(p=Ve),(y===null||Ve<y)&&(y=Ve,v=S.parentId&&!b(S.parentId)?g(At.target,S.parentId):!1)}if(y!==null)if(v)p=y;else{let At=f(A).endDate,ie=At.getTime()>D.getTime()?At:D;p=y<ie?y:ie}else p>D&&(p=D);let R=(u.get(String(A))??[]).some(At=>At.type===M.FINISH_TO_START||At.type===M.FINISH_TO_FINISH),O=new Date(Date.UTC(p.getUTCFullYear(),p.getUTCMonth(),p.getUTCDate())),N=()=>i.getClosestWorkTime({date:O,dir:"past",task:S}),X=i.getClosestWorkTime({date:p,dir:"future",task:S}).getTime()===p.getTime(),z;S.durationHours===0&&y===null?z=R&&X?N():i.getClosestWorkTime({date:p,dir:"past",task:S}):S.durationHours===0?R?z=N():z=i.getClosestWorkTime({date:p,dir:"future",task:S}):z=i.getClosestWorkTime({date:p,dir:"future",task:S});let gt=i.calculateEndDate({startDate:z,durationHours:-S.durationHours,task:S}),Te=s.get(A),vt=Te?{...Te}:{activityId:A,startDate:gt,endDate:z,drivingLinkId:null,kind:"alap",conflict:!1};vt.startDate=gt,vt.endDate=z,vt.drivingLinkId=null,vt.kind="alap";let ri=vt.earliestSchedulingStart??null;vt.earliestSchedulingStart=null,vt.earliestSchedulingEnd=null;let ii=ri!==null&&ri.getTime()>gt.getTime()?ri:gt;vt.latestSchedulingStart=ii,vt.latestSchedulingEnd=ii===gt?z:i.calculateEndDate({startDate:ii,durationHours:S.durationHours,task:S}),er(S,vt,i),s.set(A,vt)}return s}var oe={warn(){},error(){}};function Ee(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,e.updateActivity(r))}})}function za(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=n.get(s)??[];c.push(o),n.set(s,c)}return Bd(n,i,r)}function Bd(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new ft;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;i.has(o)||(i.add(o),n.enqueue(o))}}return!1}function Nt(e,t){switch(e.kind){case"create":return Hd(e,t);case"update":return jd(e,t);case"delete":return Vd(e,t)}}function Hd(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:"activity-missing"};let a=r.getAllLinks();for(let l of a)if(String(l.source)===String(e.source)&&String(l.target)===String(e.target)&&l.type===e.type)return{applied:!1,rejected:"duplicate",linkId:l.id};let s=a.map(l=>({source:l.source,target:l.target}));if(za(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Yd)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function jd(e,t){let{port:r}=t;return r.getLink(e.linkId)?(e.lag!==void 0&&r.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&r.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function Vd(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}var rr=null;function Yd(){return rr===null&&(rr=Date.now()),rr+=1,String(rr)}var qa={[M.FINISH_TO_START]:"fs",[M.START_TO_START]:"ss",[M.FINISH_TO_FINISH]:"ff",[M.START_TO_FINISH]:"sf"},qt={fs:M.FINISH_TO_START,ss:M.START_TO_START,ff:M.FINISH_TO_FINISH,sf:M.START_TO_FINISH},Ja="fs";function Xa(e){if(e in qt)return qt[e]}var Za=";",Qa=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function ir(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(Za)){if(n.length===0)continue;let a=$d(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function $d(e){let t=e.toLowerCase(),r=Qa.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?qt[n]:qt[Ja],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:o,lag:c}}function ar(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=nr(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.target)===String(t)&&s.set(nr(c.source,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function nr(e,t){return`${String(e)}::${t}`}function sr(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=nr(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.source)===String(t)&&s.set(nr(c.target,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function pt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var ts={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:q.FUTURE,date:e,unit:nt.HOUR}):t.isWorkTime(e,nt.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function pi(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var hi=ts;var or=class{adapter;reporter;currentCalculationId=0;topoCache=new Ze;expandedLinksCache=new tr;constructor(t,r=oe){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=Da(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{qd(this.adapter);let a=Ft("schedule.total"),s=Ft("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Pt(s);let l=c;if((await ae(i)).aborted)return{...n,cancelled:!0};let d=Ft("schedule.scoping"),u=this.adapter.getAllIds(),f=Jd(t,l,this.adapter),h=f.links,g=f.idSet;Pt(d);let C=Ft("schedule.topologicalSort"),A=Zd(this.topoCache,u,l,g);if(Pt(C),A.hasCycles)return Pt(a),{...n,cycles:[A.cycleNodes]};if((await ae(i)).aborted)return{...n,cancelled:!0};let k=Ft("schedule.processConstraints"),S=new Map;if(ja(A.ordered,this.adapter,S),Pt(k),(await ae(i)).aborted)return{...n,cancelled:!0};let D=Ft("schedule.asapPass"),p=await Ga(A.ordered,h,this.adapter,t,i,S);if(Pt(D),(await ae(i)).aborted)return{...n,cancelled:!0};let y=Ft("schedule.alapPass"),v=await Ka(A.reversed,h,p,this.adapter,t,i);if(Pt(y),(await ae(i)).aborted)return{...n,cancelled:!0};let E=Ft("schedule.diff"),T=[];for(let[R,O]of v){let N=this.adapter.getActivity(R);if(!N)continue;let X=N.startDate.getTime()!==O.startDate.getTime(),z=N.endDate.getTime()!==O.endDate.getTime();(X||z)&&T.push(R)}return Pt(E),Pt(a),{plans:v,updatedIds:T,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},Kd=!1;function zd(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Kd}function Ft(e){return{name:e,startedAt:performance.now()}}function qd(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Pt(e){if(!zd())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Jd(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=Wa(i,t);return Xd(n,t,r)}function Xd(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let s of r.getAllActivities()){let o=String(s.id);s.constraintType===Y.ALAP&&!i.has(o)&&(n.add(o),i.add(o))}if(n.size===0)return{idSet:i,links:e.links};let a=[...e.links];for(let s of t)(n.has(String(s.source))||n.has(String(s.target)))&&a.push(s);return{idSet:i,links:a}}function Zd(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let s=i?Array.from(i):t;return Xe(s,r)}if(!i)return n;let a=ba(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function es(e,t,r){let i=t.getActivity(e);if(!i)return;let n=r?{...i,endDate:r.endDate}:i,a=t.calendarReader.getCalendar(String(i.calendarId));for(let s of t.getIncomingLinkIds(e)){let o=t.getLink(s);if(!o)continue;let c=t.getActivity(o.source);if(!c||c.constraintType==="alap"||Kt(i.type)&&(o.type===M.START_TO_FINISH||o.type===M.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=pi(c,n,o.type),f=hi.computeLagBetweenTasks(d,u,a);f!==o.lag&&Nt({kind:"update",linkId:o.id,lag:f},{port:t})}}function rs(e,t){let r=t.getActivity(e);r&&Kt(r.type)&&(r.durationHours=0)}function ce(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function cr(e){return Number(e.toFixed(2))}function lt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function le(e,t,r=!0,i={}){let n=t?tu(e,t):nu(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await Qd(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function lr(e,t){is(e,t,"skip")}async function Qd(e,t,r,i={recomputeRealWork:!1}){let a=0;for(let s of e)is(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await at()}function tu(e,t){let r=new Set;for(let a of t)eu(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=ns(i,e);return as(i,n)}function eu(e,t,r){let i=t.getParentId(e);for(;i&&!b(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function ru(e,t,r){let i=null,n=null,a=0,s=[];for(let o of e){let c=t.getActivity(o);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(a+=iu(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:s}}function is(e,t,r="freeze-when-no-contribution",i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let s=ru(a,t,i);if(s.minStart===null||s.maxEnd===null)return;let o=String(n.calendarId??""),c=t.calendarReader.getCalendar(o),l=new Date(s.minStart),d=new Date(s.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u);let f=ce(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",cr(f??0)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function iu(e,t){return t?Number(e.realWorkHours)||0:lt(e.workHours,e.progress)}function nu(e){let t=au(e),r=ns(t,e);return as(t,r)}function au(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function ns(e,t){let r=new Map;for(let i of e)r.set(i,su(i,t));return r}function su(e,t){let r=0,i=e;for(;i&&!b(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function as(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var ss={updateActivityDuration:rs,updateTaskTiming:cu("updateTaskTiming"),adjustLinkLagOnTaskMove:es,recordLastStartDate:ou};function ou(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Mt(e,t,r,i){for(let n of t){let a=n in ss?ss[n]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${n} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,i??null)}}function cu(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function w(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function x(e){return{ok:!1,reason:e}}function W(){return{valid:!0}}function Q(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function U(){return{allowed:!0}}function K(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function F(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var os={targetField:"name",canEdit(){return U()},parseInput(e){return typeof e!="string"?x("not_a_string"):w(e)},validate(){return W()},transform(e,t){return F({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var cs={targetField:"description",canEdit(){return U()},parseInput(e){return typeof e!="string"?x("not_a_string"):w(e.trim())},validate(){return W()},transform(e,t){return F({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Ct(e){return e.constraintType??Y.ASAP}var dr=100;function de(e){return e.progress>=dr}function tt(e,t){return _t(e.type,t.hasChildren(e.id))}function ls(e){return e.progress>0}function ds(e){return e.hasLookaheadTasks}function Re(e,t){return Math.round(Math.ceil(e*t*60)/60)}var ue=e=>({endDate:e});function Jt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(a=>a.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Le(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(h=>h.type===f)?.value),n=i("year"),a=i("month"),s=i("day"),o=Date.UTC(n,a-1,s,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(o)),l=f=>Number(c.find(h=>h.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-o;return new Date(o-u)}function lu(e,t){let r=Jt(t);for(;!e.isWorkTime(r,nt.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Jt(r);return r}function yi(e,t){return e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:nt.HOUR})}function mi(e,t){let r=lu(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:q.PAST,date:i,unit:nt.HOUR})}var ur=new Set(["snet","snlt","mso"]),gi=new Set(["fnet","fnlt","mfo"]),Wt=new Set(["asap","alap"]),fr="snet";function Et(e,t,r){if(!ur.has(r)&&!gi.has(r))return e;let i=ur.has(r)?yi(t,e):mi(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var Rt=()=>({constraintType:fr});var Ut=e=>({constraintDate:e}),us=e=>({constraintDate:e});var fs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var ps={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id"};function fe(e,t,r){return _a(e,t,r)}function pe(e,t,r){return Pa(e,t,r)}var ys={targetField:"durationHours",canEdit(e,t){return de(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?x("not_a_number"):w(r.inputUnit==="hours"?i:Re(i,r.hoursPerDay))},validate(e,t,r){return hs(r)?Q(ps.NEGATIVE_DURATION):du(t,r)?Q("unchanged"):W()},transform(e,t,r){if(hs(t))return F({},{autoSchedule:!1,postProcessors:[]});let i=uu(e,t,r),n=fu(e,t,r,i.violated);return{...F(n,{autoSchedule:!0,postProcessors:[fs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:pe(i.constraintType,i.constraintDate,ms(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function hs(e){return Math.sign(e)===-1}function du(e,t){return e===t}function uu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!=="fnet"&&n!=="fnlt"&&n!=="mfo")return{violated:!1};let a=i.calculateEndDate(e.startDate,t);return fe(n,e.constraintDate,a)}function fu(e,t,r,i=!1){let n={};i&&Object.assign(n,Rt(),Ut(e.startDate));let a=Pe(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=ms(e,t,r);return s&&Object.assign(n,ue(s)),n}function ms(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var he=e=>({realWorkHours:e});var pu=0,hu=dr,gs=0,vs={targetField:"progress",canEdit(e,t){return ds(e)?K("has_lookahead_tasks","cant_edit_actvity_with_task"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?x("not_a_number"):w(t)},validate(e,t,r){return yu(r)?Q("out_of_range"):W()},transform(e,t,r){let i=mu(t),n=gu(t),a=Cu(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...he(a.get(e.id)??0)},o=n?vu(e,t,i,r.hierarchy,a):[],c=n?Su(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?Du(e,t):void 0;return F(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function yu(e){return e<pu||e>hu}function mu(e){return e===gs}function gu(e){return e===dr||e===gs}function vu(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:Au(t,r,n.get(s)??0)}))}function Au(e,t,r){return{progress:e,autoScheduling:t,...he(r)}}function Cu(e,t,r){let i=new Map,n=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?n(c.id):lt(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):lt(e.workHours,t);return i.set(e.id,a),i}function Iu(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=a=>t.getChildProgressInfo(a).some(s=>t.hasChildren(s.id)),n=a=>t.getAncestorIds(a).length;return r.filter(a=>i(String(a))).map(String).sort((a,s)=>n(s)-n(a))}function Su(e,t,r){let i=new Map;i.set(e.id,t);for(let s of r.getDescendantIds(e.id))i.set(s,t);let n=[...Iu(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of n){let o=ku(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function ku(e,t,r){let i=r.getChildProgressInfo(e).map(n=>({progress:t.has(n.id)?t.get(n.id):n.progress,ponderator:n.ponderator??0}));return Number((ce(i)??0).toFixed(2))}function Du(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var As={targetField:"cost",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?x("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=Tu(e,t,r.hierarchy);return F({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function Tu(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.cost;i.set(a,s),n.push({activityId:a,fields:{cost:s}})}return n}var Cs={targetField:"usedCost",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?x("not_a_number"):w(r)},validate(){return W()},transform(e,t,r){let i=_u(e,t,r.hierarchy);return F({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function _u(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.usedCost;i.set(a,s),n.push({activityId:a,fields:{usedCost:s}})}return n}var Is={targetField:"workHours",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?x("not_a_number"):w(t)},validate(){return W()},transform(e,t,r,i){let n=Ss(t,e.progress),a=String(i).trim()===""?[]:Pu(e,t,n,r.hierarchy);return F({workHours:t,...he(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Ss(e,t){return lt(e,t)}function Pu(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let s=[];for(let o of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(o)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??Ss(d.workHours,d.progress);c+=u,l+=f}n.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...he(l)}})}return s}function pr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function vi(e,t){return e.getTime()<t.getTime()}function ye(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var hr=e=>({durationHours:e});var ks={targetField:"startDate",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):ls(e)?K("has_progress","cant_edit_activity_with_progress"):U()},parseInput(e,t,r){return ye(e)?w(Jt(e,"UTC")):x("invalid_date")},validate(e,t,r,i){if(pr(t,r))return Q("unchanged");let n=Eu(e,r,i);return n||W()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return F({startDate:t,...Rt(),...Ut(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=yi(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...F({startDate:n,...ue(s),...a?hr(0):{},...Rt(),...Ut(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Ru(e,n,i)}},trackEvent:"activity_start_date_entry"};function Eu(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=Jt(i);return t.getTime()<n.getTime()?Q("before_parent_start"):null}function Ru(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=_e(Ct(e),t,i),a=fe(Ct(e),e.constraintDate,n);if(a.violated)return pe(a.constraintType,a.constraintDate,n)}var Lu=99.999,Ts={targetField:"endDate",canEdit(e,t){return tt(e,t)?K("summary","summary_column_value"):bu(e)?K("completed","cant_edit_completed_activity"):U()},parseInput(e,t,r){if(!ye(e))return x("invalid_date");let i=Jt(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,nt.DAY)?w(mi(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:nt.HOUR})):w(i)},validate(e,t,r,i){if(pr(e.endDate,r))return Q("unchanged");if(wu(r,e))return Q("before_date_origin");if(Ou(r,e))return Q("before_start_date");let n=xu(r,e,i);return n||W()},transform(e,t,r){let i=Nu(e,t),n=Fu(e,t,r,!!i);return{...F(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function bu(e){return e.progress>=Lu}function wu(e,t){return t.dateOrigin?vi(e,t.dateOrigin):!1}function Ou(e,t){return vi(e,t.startDate)}function xu(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,nt.DAY)?null:Q("not_working_day"):null}function Nu(e,t){if(Ct(e)===Y.MSO)return;let i=_e(Ct(e),e.startDate,t),n=fe(Ct(e),e.constraintDate,i);if(n.violated)return pe(n.constraintType,n.constraintDate,i)}function Fu(e,t,r,i=!1){let n={};Kt(e.type)&&!i&&Ds(e)?Object.assign(n,Ut(e.startDate)):(i||Ds(e))&&Object.assign(n,Rt(),Ut(e.startDate));let o=Mu(e,t,r),c=Pe(e.durationHours,o);return c&&(n.type=c),Object.assign(n,hr(o)),n.endDate=t,n}function Ds(e){return Wt.has(Ct(e))}function Mu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Wu=new Set(Object.values(Y)),_s={targetField:"constraintType",canEdit(e,t){return de(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return Uu(t)?w(t):x("invalid_constraint_type")},validate(){return W()},transform(e,t,r){let i=Bu(e,t,r);return F(i,{autoSchedule:!0})}};function Uu(e){return Wu.has(e)}function Bu(e,t,r){let i=ju(e,t);return{constraintType:t,...us(Hu(e,t,i,r))}}function Hu(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?Et(r,n,t):r}function ju(e,t){return Wt.has(t)?null:ur.has(t)?e.startDate:gi.has(t)?e.endDate:e.constraintDate}var Ps={targetField:"constraintDate",canEdit(e,t){return de(e)?K("completed","cant_edit_completed_activity"):tt(e,t)?K("summary","summary_column_value"):U()},parseInput(e){return ye(e)?w(e):x("invalid_date")},validate(){return W()},transform(e,t,r){let i=Es(e)?fr:Ct(e),n=r.calendars.getCalendar(e.calendarId),a=n?Et(t,n,i):t,s=Vu(e,a);return F(s,{autoSchedule:!0})}};function Vu(e,t){return{constraintDate:t,...Es(e)?Rt():{}}}function Es(e){return Wt.has(Ct(e))||!e.constraintType}var Rs={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return Yu(t)?x("empty_calendar"):w(t)},validate(e,t,r){return $u(e.calendarId,r)?Q("unchanged"):W()},transform(e,t,r){return F(Gu(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Yu(e){return e===""}function $u(e,t){return e===t}function Gu(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Ku(e.startDate):e.startDate,o=n.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=o),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,ue(n.calculateEndDate(c,e.durationHours)))}return i}function Ku(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Ls={targetField:"customId",canEdit(){return U()},parseInput(e){if(e==null)return x("empty_custom_id");if(typeof e!="string")return x("not_a_string");let t=e.trim();return t.length===0?x("empty_custom_id"):t.length>20?x("exceeds_max_length"):w(t)},validate(){return W()},transform(e,t){return F({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var bs={targetField:"subcontractId",canEdit(){return U()},parseInput(e){if(e==null)return w(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return w(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?x("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?x("not_an_integer"):w(e):x("not_an_integer")},validate(){return W()},transform(e,t){return F({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function be(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function yr(e){return e.some(t=>be(t)===null)}var ws={targetField:"responsableIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):x("not_an_array")},validate(e,t,r){return yr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(be).filter(i=>i!==null);return F({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Os={targetField:"tagIds",canEdit(){return U()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):x("not_an_array")},validate(e,t,r){return yr(r)?Q("missing_id"):W()},transform(e,t){let r=t.map(be).filter(i=>i!==null);return F({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var zu=new Map([[_.TEXT,os],[_.DESCRIPTION,cs],[_.DURATION,ys],[_.PROGRESS,vs],[_.COST,As],[_.USED_COST,Cs],[_.HH_WORK_TIME,Is],[_.START_DATE,ks],[_.END_DATE,Ts],[_.CONSTRAINT_TYPE,_s],[_.CONSTRAINT_DATE,Ps],[_.CALENDAR_ID,Rs],[_.CUSTOM_ID,Ls],[_.SUBCONTRACT_ID,bs],[_.RESPONSABLES,ws],[_.TAGS,Os]]);function Bt(e){return zu.get(e)}function me(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:"constraint_violation",activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var L={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Ai={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var qu=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],xs=new Set(qu);function Z(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Ns(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function ge(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Dt(e.constraintDate),dateOrigin:Dt(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Dt(t.startDate),endDate:Dt(t.endDate)})),baselineSnapshot:Ju(e.baselineSnapshot),criticalPath:Xu(e.criticalPath)}}function Dt(e){return e===null?null:new Date(e)}function Ju(e){return e===null?null:{...e,startDate:Dt(e.startDate),endDate:Dt(e.endDate)}}function Xu(e){return e===null?null:{...e,earlyStart:Dt(e.earlyStart),earlyFinish:Dt(e.earlyFinish),lateStart:Dt(e.lateStart),lateFinish:Dt(e.lateFinish)}}function Ht(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}function V(e,t){let r=new Map;for(let i of t){let n=e.getActivity(i);n&&r.set(i,J(n))}return r}function J(e){return ge(e)}function jt(e,t,r){Fs(e,t,r.patch);for(let i of r.cascadeMutations??[])Fs(e,i.activityId,i.fields)}function Fs(e,t,r){for(let[i,n]of Object.entries(r)){if(!xs.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Z(e,t,i,n)}}function Ms(e,t,r){let i=[];for(let n of r){let a=e.getActivity(n);if(!a){i.push({id:n,kind:"deleted",after:null});continue}let s=t.get(n),o=Ii(s,a);s&&Object.keys(o).length===0||(s?i.push({id:n,kind:"updated",fields:o,after:J(a)}):i.push({id:n,kind:"created",fields:o,after:J(a)}))}return i}function Ii(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);for(let s of a)(Object.hasOwn(i,s)!==Object.hasOwn(n,s)||!Ci(i[s],n[s]))&&(r[s]={before:i[s],after:n[s]});return r}function Ci(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,o)=>Ci(s,t[o]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,i=t,n=Object.keys(r),a=Object.keys(i);return n.length!==a.length?!1:n.every(s=>Object.hasOwn(i,s)&&Ci(r[s],i[s]))}function mr(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function Si(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function gr(e,t,r,i,n){for(let a of t){if(r.has(a.activityId)||(n.add(a.activityId),i.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=J(s);a.before!==void 0&&(o.correlativeId=a.before),i.set(a.activityId,o)}}var Zu=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Lt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(Zu);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,s]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(s)))}function ve(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),a=i.calculateDuration(e,t);return a===0?0:n*100/a}var Qu=e=>e.type==="project",tf=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=s=>s instanceof Date?s:Lt(String(s));return ve(a(e.startDate),a(e.endDate),t,n)};function ef(e,t,r){let i=[],n=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),i.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!Qu(o)){let d=tf(o,t,r);return n(s,d),d}let c=0;for(let d of r.getChildren(s)){let u=a(d),f=r.getActivity(d),h=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*h}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}function bt(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),ef(r,t,e)}function rt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var rf=e=>e.type==="project",nf=e=>rt(e),af=(e,t,r,i)=>{let n=nf(e);if(!n)return 0;let a=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!a||!n.startDate||!n.endDate?0:ve(n.startDate,n.endDate,t,a)};function ki(e,t,r,i=null){let n=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),n.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!rf(c)){let u=af(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),h=r.getActivity(u),g=typeof h?.ponderator=="number"?h.ponderator:0;l+=f*g}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function Vt(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>Z(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),ki(n,t,i,r)}var Ws=e=>Math.round(e*100)/100;function sf(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function of(e,t){let r=Ws(e),i=Ws(t);return r>99.99?Ot.DONE:i>r?Ot.OVERDUE:e>0&&r>i?Ot.ADVANCEMENT:e===0&&t===0?Ot.WAITING:e>0&&r<i?Ot.DOING:Ot.WAITING}function It(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=of(a,sf(i,t));i.status!==s&&(Z(e,n,$e,s),r.push(n))}),r}function Di(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,a)=>s=>s===void 0?t[n]():(t[a](s),i),i={__isMomentShim:!0,clone:()=>Di(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}Di.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var ht=Di;function cf(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function vr(e){return cf(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!vr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function dt(e){if(!vr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var lf=e=>e?e.$level===1:!1,df=e=>e.type==="project",uf=e=>e.$level!==0,ff=e=>e.type==="task",pf=e=>e.type==="task"||e.type==="milestone",st={byFirstLevel:lf,filterByParentType:df,avoidSubproject:uf,byTaskType:ff,byTaskTypeAndMilestone:pf};var m=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var B=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function Zt(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Us(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=hf({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=yf({gantt:t,subprojectsWithNoLinks:a}),o=mf({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:gf,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function hf(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(st.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function yf(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(o=>{let c=t.getTask(o),l=st.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function mf(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function gf(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[i]);n.push(o)}return n}function Bs({gantt:e,linkProperty:t,direction:r}){try{let i=vf(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Af(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function vf(e,t){return e.getTaskByTime().filter(st.avoidSubproject).filter(st.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Af(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?n.add(a.id):o.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function Hs({gantt:e,direction:t,linkProperty:r}){try{let i=Cf(e),n=new Set,a=new Set,s=new Set;t==="backward"&&kf(i).forEach(d=>{n.add(d.id)});let o=If(i,t,r),c=Sf(i,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(i){throw i}}function Cf(e){return e.getTaskByTime().filter(st.filterByParentType).filter(st.avoidSubproject)}function If(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,s=i.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function Sf(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function kf(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function js({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=Df(r),o=Tf(r),c=a[s];if(!Array.isArray(c))return;_f(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Df(e){return e==="forward"?"$source":"$target"}function Tf(e){return e==="forward"?"target":"source"}function _f(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var we={identifySecondLevelActivities:Us,identifyInitialActivities:Bs,identifyParentsWithAndWithoutLinks:Hs,identifyForbiddenActivities:js};function Ar(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Ti({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===B.FS&&t===0?dt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Oe(r,e,i,n)}function Vs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function Ys({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=I(r,n,e,i);return{es:n,ef:a}}function Oe(e,t,r,i){if(![B.FS,B.SS,B.FF].includes(t))return e;let a=[B.FS,B.SS].includes(t)?"future":"past";return dt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var _i=class{constructor(t,r,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Ar(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(r):i==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Zt(i),a=r.linkLag,s=r.es,o=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=Ys({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=Vs({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=Ti({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=Oe(n,"ss",this.activityCalendar,this.activity));let a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=Ti({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=Oe(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=dt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=I(this.activityCalendar,r,t,this.activity),n=I(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Oe(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},$s=_i;var Pi=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=Zt(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let n=r.linkLag,a=r.ls,s=r.lf;if(i==="ss"){let o={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(i==="ff"){let o={lag:n,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(i==="fs"){let o={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(i==="sf"){let o={lag:n,workTime:s,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(o);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:I(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null;if(t===0)return a=I(this.activityCalendar,r,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=I(this.activityCalendar,o,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=I(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=I(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=I(this.activityCalendar,c,n,this.activity),o=I(this.activityCalendar,s,i,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null,o=r;return s=I(this.activityCalendar,o,i,this.activity),a=I(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=I(this.activityCalendar,r,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=I(this.activityCalendar,c,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:I(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),dt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},Gs=Pi;function Ks(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=Pf(t),l=null;if(s==="forward"){let d=Ef(o,i,n,a);l=new $s(d,t,a),l=l.calculate()}else{let d=Rf(o,i,n,a);l=new Gs({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function Pf(e){return{duration:e.duration,calendarId:e.calendar_id}}function Ef(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);return o?{es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function Rf(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=i.getTask(s);return c?{ls:o.ls,lf:o.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function Js(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Lf(t.id,r))return null;let a=bf(t.id,i),s=wf(a,r);return s.length===0?null:Of(s,n)}function Lf(e,t){return t.has(e)}function bf(e,t){let r=t.get(e);return r?r.childrens:[]}function wf(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Of(e,t){if(t==="forward"){let r=zs(e,"es"),i=qs(e,"ef");return{es:r,ef:i}}else{let r=zs(e,"ls"),i=qs(e,"lf");return{ls:r,lf:i}}}function zs(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function qs(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Ei={parentWithLinks:Ks,parentWithNoLinks:Js};var Ri=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[m.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=Ei.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=Ei.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:n,maxEf:a}=i.reduce((s,{es:o,ef:c})=>({minEs:new Date(Math.min(s.minEs.getTime(),new Date(o).getTime())),maxEf:new Date(Math.max(s.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:a}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:n,maxLf:a}=i.reduce((s,{ls:o,lf:c})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(o).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}},Xs=Ri;var Li=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,a=this.getAllLevels(n),s=this.getDeepestLevel(a),o=this.createResult(r,i,s,a);this.structureOfParents.set(r.id,o)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(st.byFirstLevel).filter(st.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let a=Number(t.id),s=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,a=this.hasLink(t),s={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let a=r.get(i);a.has(n)||a.set(n,[]),a.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},Zs=Li;var bi=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let a=i.get(r);for(let[s,o]of a)if(o.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(s);this.calculateParentWithNoLinks(l,o);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(st.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=we.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=we.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new Zs({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((s,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),s({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=we.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=we.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(a=>{a&&n.set(a.id,a)}),n.forEach((a,s)=>{if(i.has(s))return;let o=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>n.has(l)||i.has(l)),r.set(s,o)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],s=o=>{if(n.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!i.has(o)&&!r.has(o)){n.add(o);let c=t.get(o)||[];for(let l of c)s(l);n.delete(o),i.add(o),a.push(o)}};for(let o of t.keys())!i.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let a=this.gantt.getCalendar(i.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)==="forward"){let o=i.start_date,c=i.end_date;return{es:o,ef:c}}else{if(n>=100)return{ls:ht(i.start_date).clone(),lf:ht(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,a);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=ht(t.start_date).clone(),n=ht(t.end_date).clone(),a=t.duration,s=[m.ASAP,m.ALAP,m.SNET,m.FNET],o=t.constraint_type||m.ASAP;if(s.includes(o))n=this.projectDates.end_date,i=I(r,n,-a,t);else{let c=[m.SNLT,m.MSO],l=[m.FNLT,m.MFO];c.includes(o)&&(i=t.constraint_date,n=I(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=I(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||m.ASAP,a=this.projectDates.end_date,s=[m.ASAP,m.ALAP,m.SNET,m.FNET],o=[m.SNLT,m.FNLT];if(s.includes(n))i=Math.max(t.end_date,a);else if(n===m.MSO)i=t.end_date;else if(n===m.MFO||o.includes(n)){let c=Math.min(a,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new Xs({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Yt=bi;function xf(e,t,r){let i={es:null,ef:null};if(!e)return i;if([m.SNET,m.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if([m.FNLT,m.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}else if(t===m.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if(t===m.MFO){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}return i}var Cr=xf;var wi=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let o=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===B.FS&&n===0?o=dt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[B.FF,B.SF].includes(a)?(l=I(s,o,i,this.referenceActivity),c=I(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=I(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=I(s,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,B.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,B.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,B.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,B.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![B.FS,B.SS,B.FF].includes(r))return t;let a=[B.FS,B.SS].includes(r)?"future":"past";return dt({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},Qs=wi;var xe=class extends Qs{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Yt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});return this.calculateLink(n)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,a=I(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return Ar(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Oi=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let a=this.gantt.getTask(n);a.type==="project"?this.handleProjectActivity(n,a,r,i):this.handleNonProjectActivity(n,a,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let a=this.pendingParentsWithNoLinks.has(t),s=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),s=this.pendingParentsWithLinks.has(a),o=this.calculationOfParentsFromLinks.has(a);if(s&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(r.$target.length===0&&r.$source.length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=n[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},Ir=Oi;var xi=(e,t)=>()=>t()===e;var Ni=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Nf=16,Ne=async e=>performance.now()-e>Nf?(await at(),performance.now()):e;var Fe=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await Ne(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await Ne(c),r([u])}for(let u of l){if(!s())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}o=d}};var Fi=class extends Yt{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new Ir({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Fe({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,a=i.constraint_type||m.ASAP,s=[m.SNET,m.SNLT,m.FNLT,m.FNET],o=[m.ASAP,m.ALAP,m.SNET,m.FNET,m.SNLT,m.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new xe({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===m.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new xe({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===m.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let h=Cr(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,h),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,h,{es:d,ef:u})),[m.MSO,m.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,h),i.progress===0)d=h.es,u=h.ef;else{let g=i.end_date;a===m.MFO&&(g=Math.max(h.ef,i.end_date)),d=i.start_date,u=g}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i="greater"){if(i==="greater")return r.ef>t.ef?r:t;if(i==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[m.SNET,m.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,a=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},to=Fi;var Mi=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===m.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=B.FS){let s=this.gantt.getCalendar(this.activity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let o=t,c=this.activity.type==="milestone";if(c&&n===0){let d=I(s,o,r,this.activity),u=I(s,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===B.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===B.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===B.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===B.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===m.ALAP?"ef":"lf",a=i[n],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,B.FF)}calculateFS(t,r){let i="ls";i=r===m.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,o,s,B.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,B.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=ht(r).clone();return I(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=ht(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),dt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),ht.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return o=I(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=I(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=I(i,l,a,this.activity),c=I(i,o,n,this.activity),s||(o=this.getLastWorkingHour(o,i,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=I(i,r,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=I(i,c,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=I(i,r,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=I(i,l,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=I(i,r,n),s=I(i,o,a,this.activity),{ls:o,lf:s}):(o=I(i,r,n,this.activity),s=I(i,o,a,this.activity),{ls:o,lf:s})}},eo=Mi;var Wi=class extends eo{constructor(t){super(t),this.constraint=t.constraint||m.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Yt(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(s=>{let o=this.gantt.getLink(s);if(!o)throw new Error("Link not found",{cause:{linkId:s}});if(!this.parentsWithFullProgress.has(Number(o.target)))return this.calculateLink(o)}).filter(s=>s);if(n.length!==0){let s=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(n),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=I(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);n.push({ls:c,lf:o});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:I(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===m.ALAP)return m.ALAP;if(this.constraint===m.FNET||this.constraint===m.SNET)return"snet-fnet";if(this.constraint===m.FNLT)return m.FNLT}getSpecialParamForSf(){return!![m.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![m.MFO,m.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===m.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===m.SNET||this.constraint===m.SNLT||this.constraint===m.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===m.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===m.ALAP||this.constraint===m.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,a=this.activity.constraint_date;if(r===m.ASAP)return new Date(Math.max(i,n));if(r===m.FNET||r===m.FNLT){let s=Math.min(i,a);return new Date(Math.max(i,s))}if(r===m.ALAP)return new Date(Math.min(i,n))}},ro=Wi;function Ff(e,t,r){let i={ls:null,lf:null};return r===m.MSO&&(i.ls=t.constraint_date,i.lf=I(e,i.ls,t.duration,t)),r===m.MFO&&(i.lf=t.constraint_date,i.ls=I(e,i.lf,-t.duration,t)),i}var io=Ff;var Ui=class extends Yt{constructor(t,r,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new Ir({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Fe({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=n.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,a=i.constraint_type||m.ASAP,s=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(s===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(s>0&&s<100&&(a===m.MSO||a===m.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===m.MSO||a===m.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===m.SNLT||a===m.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:o,lf:c},a)),this.setCalculations(i,o,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);n=Cr(a,i,s)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=this.gantt.getTask(n.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(n=new Date(Math.min(n,a.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===m.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===m.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,a){return new ro({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=io(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,a=0;if([m.ASAP,m.ALAP,m.SNET,m.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,i.lf)),n=t.start_date}else a=i.lf,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([m.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=I(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([m.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);n=new Date(Math.min(l.getTime(),d.lf.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[m.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[m.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:I(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t),lf:s});let c=this.getMinLfFromLinks(o);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},no=Ui;function ao(){return null}var so=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:a})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:a,gantt:n}});var Bi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=m.ASAP),t===m.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===m.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===m.SNET||t===m.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===m.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===m.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===m.MSO||t===m.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===m.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===m.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},oo=Bi;var Hi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===m.MSO||t===m.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=m.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),s=this.gantt.getTask(n.target);if(!s)return{linkId:n.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:o}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=m.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[m.SNLT,m.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=m.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===m.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===m.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===m.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Zt(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=({direction:s,constraint:o=m.ASAP})=>o===m.ALAP?this.backwardMap.get(n)[s]:this.forwardMap.get(n)[s];if(t===m.ASAP||t===m.SNET||t===m.FNET||t===m.MSO||t===m.MFO)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===m.ALAP)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:m.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:m.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:m.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:m.ALAP,direction:"ls"})}};if(t===m.SNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===m.FNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=t===m.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,n=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(n))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},co=Hi;var lo=e=>({totalFloat:new oo(e.totalFloat).getTotalFloat(),freeFloat:new co(e.freeFloat).getFreeFloat()});var ji=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let s=performance.now(),o=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:o,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=so({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:h}=lo(u);o.set(l,f),c.set(l,h),s=await Ne(s)}return{totalFloatMap:o,freeFloatMap:c}};var Vi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let i=++this.currentCalculationId,n=xi(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||ao(),Ni(this.gantt))return!1;let o=new to(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new no(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let{totalFloatMap:u,freeFloatMap:f}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=u,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(s){return this.forwardPathCalculations?.size,!1}}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await ji({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){return this.forwardPathCalculations?.size,{totalFloatMap:new Map,freeFloatMap:new Map}}}},uo=Vi;var Mf=e=>e==="fnet"||e==="fnlt"||e==="mfo",Wf=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Uf(e,t){let r=e.constraintDate;if(!r||!Mf(e.constraintType))return r;let i=Wf(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?si(e,t):r}function Bf(e){return{calculateEndDate:({start_date:t,duration:r})=>e.calculateEndDate(t,r),calculateDuration:({start_date:t,end_date:r})=>e.calculateDuration(t,r),getWorkHours:t=>e.getWorkHours(t),$gantt:{getClosestWorkTime:({date:t,dir:r,unit:i})=>e.getClosestWorkTime({date:t,direction:r,unit:i??"hour"})}}}function Hf(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let s=r.get(n);if(s!=null)return s;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!a.has(n)&&(a.add(n),l=i(String(c),a)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function jf(e){let t=Hf(e),r=new Map;return e.forEachActivity((i,n)=>{let a=String(n);r.set(a,{id:Number(n),parent:i.parentId===null?0:Number(i.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:Uf(i,e)})}),r}function Vf(e){let t=new Map;for(let s of e.values()){let o=t.get(s.parent);o?o.push(s):t.set(s.parent,[s])}let r=[],i=new Set,n=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)n.push(s[o])};for(a(t.get(0));n.length>0;){let s=n.pop();i.has(s)||(i.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())i.has(s)||r.push(s);return r}function Yf(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function fo(e,t){let r=new Map,i=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=Bf(u);return r.set(l,f),f},n=Yf(e);await at();let a=jf(e);await at();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await at();let o=Vf(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>a.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target),lag:l.lag}:null},getCalendar:i,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>n,refreshData:()=>{}}}var $f=1e3;function Gf(e,t,r){let i=o=>o==null?null:new Date(o),n=r.forward?.get(e),a=r.backward?.get(e),s=r.totalFloat.get(e)??null;return{criticalPath:{earlyStart:i(n?.es),earlyFinish:i(n?.ef),lateStart:i(a?.ls),lateFinish:i(a?.lf),totalSlackHours:s},isCritical:t<100&&s!=null&&s<=0,freeSlackHours:r.freeFloat.get(e)?.activityFreeFloat??null}}async function Yi(e,t,r=()=>!0){if(!r())return null;let i=await fo(e,t);if(!r())return null;let n=new uo(i);if(!await n.calculate(i,r)||!r())return null;let s={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},o=new Set([...s.forward?.keys()??[]]),c=new Map,l=0;for(let d of o){if(++l>=$f&&(l=0,await at(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,Gf(d,f,s))}return r()?c:null}async function Sr(e,t,r=()=>!0){let i=await Yi(e,t,r);if(!i||!r())return!1;for(let[n,a]of i){if(!r())return!1;e.setActivityFields(n,a)}return!0}function $t(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(String(n));if(!a)return 0;let s=[...e.getChildren(String(n))],o;if(s.length===0){let c=rt(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=i(String(l));o=c}return e.setActivityField(String(n),L.REAL_COST,o),r.push(String(n)),o};for(let n of t)i(n);return r}var po=new Set;var ho=new Set(["activity-outdent","activity-indent"]);var Me=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),Kf=new Set(["selection-toggle","selection-replace","visibility-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),zf=new Set;function qf(e){return e.kind==="inline-edit"?Me.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Me.has(t.column)):!1}function $i(e,t){return!(Kf.has(e.kind)||t.has(e.kind)||qf(e))}function mo(e){return $i(e,zf)}function We(e){return $i(e,po)}function go(e){return $i(e,ho)}function Gi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===_.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===_.PROGRESS):!1}function Jf(e){return go(e)&&Gi(e)}var yo=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function Xf(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?yo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>yo.has(t.column)):!1}var it={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function vo(e,t,r){let i=new Set;t.ran&&i.add(it.AUTOSCHEDULE),i.add(it.PARENT_BOUNDS),Xf(e)&&i.add(it.PARENT_PROGRESS),Gi(e)&&i.add(it.REAL_WORK);let n=!r.skipAutoSchedule;return n&&go(e)&&i.add(it.EXPECTED_PROGRESS),n&&Jf(e)&&i.add(it.REAL_COST),n&&We(e)&&!r.skipCriticalPath&&i.add(it.CRITICAL_PATH),i}async function $(e,t){let r=Zf(t);r.has(it.AUTOSCHEDULE)&&await rp(e.adapter,t);let i=r.has(it.AUTOSCHEDULE)?await Qf(e,t.autoscheduleFrom):ep();return await ip(e.adapter,t,i.scheduledIds,r),await np(e,r,t.now),i}function Zf(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,i=new Set(vo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&i.add(it.PARENT_PROGRESS),i}async function Qf(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=tp(e.adapter,i.updatedIds);return Ee(e.adapter,i),n}function tp(e,t){let r=[];for(let i of t){let n=String(i);r.push(n);let a=e.getActivity(n);a&&e.noteScheduledBefore(n,a)}return{scheduledIds:r}}function ep(){return{scheduledIds:[]}}async function rp(e,t){let r=t.collectDirty?t.collectDirty([]):Si(t.recomputeParentsFrom,[]);r.size!==0&&await le(e,r,!1)}async function ip(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Si(t.recomputeParentsFrom,r);await le(e,n,i.has(it.PARENT_PROGRESS),{recomputeRealWork:i.has(it.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function np(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(ap(e.adapter)&&Vt(e.adapter,r,e.defaultBaseCalendarId??null),bt(e.adapter,r),It(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&$t(e.adapter),t.has(it.CRITICAL_PATH)&&await Sr(e.adapter,e.sector.hoursPerDay)}function ap(e){let t=!1;return e.forEachActivity(r=>{rt(r)&&(t=!0)}),t}var sp=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),op=new Set(["mso","mfo"]);function kr(e){return sp.has(e)}function Dr(e){return e===_.CONSTRAINT_DATE}function Tr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||Wt.has(a)||op.has(a))return!1;let s=Ki(n.startDate),o=Ki(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=cp(t,a,String(n.calendarId??""),i),l=Ki(n.constraintDate);return lp(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function cp(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?Et(e,n,t):e}function Ki(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function lp(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function _r(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await $(e,Ao(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=i(s,o);a=a||c}if(a){let s=await $(e,Ao(t));n=up(n,s.scheduledIds)}return We(t.action)&&await $(e,dp(t)),{scheduledIds:n}}function Ao(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function dp(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function up(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function fp(e,t){let r=i=>i.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function zi(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let s=a.pendingRequestIds??[];if(!ne({pendingRequestIds:s}))continue;let o=t.getActivity(n),c=o==null;if(!c&&!fp(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)i.push({kind:"sir-auto-reject",activityId:n,sirId:d,reason:l});c||t.setActivityField(n,"pendingRequestIds",[])}return i}function j(e,t){let r=pp(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let l=yp(n);hp(e,n,l,i,r)}let a=t.sirDetection==="before-diff"?zi(i,e,r):[],s=Ms(e,i,r),o=t.sirDetection==="after-diff"?zi(i,e,r):a,c=t.warnings??[];return{source:t.source,activities:s,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...o.length>0?{effects:o}:{},...c.length>0?{warnings:c}:{}}}function pp(e,t){let r=new Set;for(let i of t.touchedIds)r.add(i);for(let i of t.scheduledIds)r.add(i);if(t.includeAllIds)for(let i of e.getAllIds())r.add(i);return r}function hp(e,t,r,i,n){for(let a of t.dirty){if(r.has(a)||i.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(Ii(s,o)).length!==0&&(i.set(a,s),n.add(a))}}function yp(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function St(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function Pr(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:St(d)});continue}if(n.kind==="delete"){let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let o=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};o&&o.type!==c.type&&(l.type={before:o.type,after:c.type}),o&&Number(o.lag)!==Number(c.lag)&&(l.lag={before:Number(o.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:St(c)})}return i}function Ae(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function Ce(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let a=t.getLink(n);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:St(a)})}return i}function Er(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Co(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=Bt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);mp(e.column)&&a.invalidateExpandedLinksCache(),e.column===L.PARENT&&a.invalidateAllCaches();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??P.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??P.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??P.INVALID,alertKey:f.notification?.messageKey};if(e.column===_.CUSTOM_ID&&d.value!==null){let T=i.getActivity(e.activityId),R=T?T.customId:null,O=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),O))return{ok:!1,reason:P.CUSTOM_ID_DUPLICATE}}let h=o.transform(c,d.value,n,d.raw),g=Ht(e.activityId,h),C=V(i,g),A=Ae(i,String(e.activityId)),k=c.constraintDate;jt(i,e.activityId,h),Mt(e.activityId,h.postProcessors??[],i,C.get(String(e.activityId))??null);let S=Ce(A,i,String(e.activityId));if(e.column===_.CUSTOM_ID){let T=C.get(String(e.activityId)),R=T?T.customId:null,O=typeof R=="string"?R:null,N=typeof d.value=="string"?d.value:null;O!==N&&r.customIdTracker.trackCustomIdChange(O,N)}let D=()=>({action:e,autoscheduleFrom:h.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:T=>mr(e.activityId,g,T),now:r.now,options:t}),p=kr(e.column),{scheduledIds:y}=await(p?_r({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:D(),revertTargets:Dr(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:k}],revert:(T,R)=>Tr(T,R,i,n.calendars)}):$({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},D())),v=(h.trackingEvents??[]).map(T=>({name:T.name,properties:T.properties??{}})),E=me(e.activityId,h.constraintWarning);return{ok:!0,changes:j(i,{source:e,beforeSnap:C,touchedIds:g,scheduledIds:y,sirDetection:"before-diff",links:S,trackingEvents:v,...E?{warnings:[E]}:{},hoursPerDay:s.hoursPerDay})}}function mp(e){return e===_.DURATION||e===L.AUTO_SCHEDULING}function gp(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind==="create"){r.add(String(n.source)),r.add(String(n.target));continue}let a=t.getLink(n.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),i.set(n.linkId,{...a}))}return{activityIds:r,links:i}}function vp(e,t,r,i){return e.map((n,a)=>{let s=n.kind==="create"?i?.get(a):void 0,o=Nt(n,{port:t,newLinkId:s?()=>s:r.next});return{op:n,finalLinkId:o.applied?o.linkId:null,rejected:o.applied?null:o.rejected??"link_op_rejected"}})}function Ap(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Io(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(M).some(a=>a===i))return{ok:!1,reason:P.INVALID_LINK_TYPE};let n=e.lag;if(n!==void 0&&!Number.isFinite(n))return{ok:!1,reason:P.INVALID_LINK_LAG}}return qi([Dp(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function So(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>Ip(s,i)),a=Cp(e.operations);return qi(n,e,t,r,a)}function Cp(e){let t=new Map;return e.forEach((r,i)=>{r.kind==="create"&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function Ip(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:pt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:pt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function qi(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let{activityIds:l,links:d}=gp(e,a),u=V(a,l),f=vp(e,a,c,n);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let h=Sp(f,d,a),{scheduledIds:g}=await $({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:h,recomputeParentsFrom:l,now:i.now,options:r}),C=Pr(f,d,a);return{ok:!0,linkVerdicts:f.map((A,k)=>A.rejected===null?{operationIndex:k,kind:A.op.kind,ok:!0,linkId:String(A.finalLinkId)}:{operationIndex:k,kind:A.op.kind,ok:!1,reason:A.rejected}),__beforeLinks:Ap(d),changes:j(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:g,links:C,hoursPerDay:o.hoursPerDay})}}function Sp(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=kp(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function kp(e,t,r){return e.kind==="create"?e.target:e.kind==="delete"?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function Dp(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:pt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:pt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function ko(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:P.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let s=e.column===_.CUSTOM_PREDECESSORS,{specs:o}=ir(e.newValue),c=o.map(g=>({...g,lag:pt(g.lag,n.hoursPerDay)})),l=new Map;i.forEachActivity(g=>{g.correlativeId!=null&&l.set(String(g.correlativeId),g.id)});let d=g=>l.get(g)??null,u=s?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let g of u){let C=i.getLink(g);C&&f.push(C)}let h=s?ar({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):sr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return qi(h.operations,e,t,r)}var yt={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};var Ji=Number.MAX_SAFE_INTEGER;function Qt(e,t){let r=Zi(e,t);return r.sort(Qi),r.map(i=>String(i.id))}function To(e){let t=[],r=n=>{t.push(n);let a=Qt(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=Qt("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function _o(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=Po(i),a=Qt(n,r),s=a.findIndex(o=>String(o)===String(e));if(s<=0)return null;for(let o=s-1;o>=0;o--){let c=a[o];if(c!==void 0&&!Tp(t,c))return c}return null}function Xi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=Po(r);return Qt(i,t).findIndex(a=>String(a)===String(e))}function Zi(e,t){if(String(e)==="0")return t.getAllActivities().filter(a=>a.parentId===null);let i=t.getChildren(e),n=[];for(let a of i){let s=t.getActivity(a);s&&n.push(s)}return n}function Qi(e,t){let r=Do(e),i=Do(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Do(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ji}function Po(e){let t=e.parentId;return t===null?"0":t}function Tp(e,t){return e.has(t)?!0:e.has(String(t))}function ct(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{b(a.parentId)&&t.push(a)}),t.sort(Lo);let r=[];Eo(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),_p(a,n)}n+=1;let s=Zi(String(a.id),e);s.sort(Lo),Eo(r,s)}return i}function Eo(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Ro(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Ji}var Lo=(e,t)=>Ro(e)-Ro(t);function _p(e,t){e.correlativeId=t}function en(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0,a=0;for(let c of i){let l=t.getActivity(c);if(!l)continue;let d=tn(l,L.WORK_HOURS),u=Pp(c,l,d,t);n+=d,a+=u}t.setActivityField(r,L.WORK_HOURS,n),t.setActivityField(r,L.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||b(o))break;r=o}}function bo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||b(i)||en(i,t)}function tn(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Pp(e,t,r,i){return i.hasChildren(e)?tn(t,L.REAL_WORK_HOURS):lt(r,tn(t,L.PROGRESS))}function rn(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Ep(c,L.USED_COST))}t.setActivityField(r,L.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||b(s))break;r=s}}function wo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||b(i)||rn(i,t)}function Ep(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function nn(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Rp(c,L.COST))}t.setActivityField(r,L.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||b(s))break;r=s}}function Oo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||b(i)||nn(i,t)}function Rp(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Rr=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),xo="New Master Plan",No="New Activity";var Lp=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Fo=new Set(Lp);function bp(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!Fo.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Mo(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=bp(e.activityOverrides??{}),n=e.numTasksInGantt===0?xo:No,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=wp(r,e.fallbackStartDate,i.startDate),l={...Rr,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:q.FUTURE,task:l}),u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function wp(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Op(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,i=e.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(i),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function Ie(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&xt(t.type):xp(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(s=>String(s)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=ui,(e.promotionSource??"create")==="create"&&(a.constraintType=Y.ASAP,a.constraintDate=null,a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a,promotionSnapshot:Op(t)}}function xp(e){return xt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Lr(e,t,r,i){let n=t,a=n==="0",s=an(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=ot(c),d=s.map(ot).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=s.find(l=>l.id===r);if(c){let l=ot(c),d=s.map(ot).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return s.length===0?0:Math.max(...s.map(ot))+1}var te=Number.MAX_SAFE_INTEGER,Wo=Number.MAX_SAFE_INTEGER-1;function ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:te}function an(e,t){let r=[];return e.forEachActivity(i=>{zt(i.parentId)===t&&r.push(i)}),r}function Uo(e,t,r){let i=e,n=Gt(e,r);for(;n!=null&&t.has(n);)i=n,n=Gt(n,r);return i}function Gt(e,t){let r=t.getActivity(e);if(!r)return null;let i=zt(r.parentId),n=Qt(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function Bo(e,t,r,i){let n=Qt(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let a=n.map(ot);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let s=a[r-1],o=a[r];return(s+o)/2}function sn(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=Np(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,h=Mp(e.activityId,i,o),g=c.next(),C={id:h,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Vp(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:g,activityOverrides:e.overrides??{}},k=Mo(C,{getActivity:v=>i.getActivity(v),calculateEndDate:v=>i.calculateEndDate(v),getClosestWorkTime:v=>i.getClosestWorkTime(v)}).newTask;k.realWorkHours=lt(k.workHours,k.progress),Up(k,e,t,u,d,r);let S=Lr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);k.correlativeId=S;let D=new Set([h]);d&&D.add(d.id);let p=d!==null&&i.getChildren(d.id).length===0,y=r.skipBeforeSnap?new Map:V(i,D);return i.addActivity(k),Bp(e,h,d,i,r.preserveParentCustomId??!1,p),bo(h,i),wo(h,i),Oo(h,i),Hp(i,h,y,D,r),{ok:!0,newId:h,parent:d,newActivity:k,beforeSnap:y,initialTouched:D}}function Np(e,t){let r=b(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:P.PARENT_NOT_FOUND};if(i!==null&&ne(i))return{ok:!1,reason:P.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:P.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Fp(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function Fp(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:P.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:P.ANCHOR_SIBLING_WRONG_PARENT}:null}function Mp(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function Wp(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Up(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=Wp(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=i??a.customIdReferenceId,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Bp(e,t,r,i,n,a){if(!r)return;let s=Ie({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:a,getParent:o=>i.getActivity(o)??null});if(s){for(let[o,c]of Object.entries(s.fields))o===L.CUSTOM_ID&&n||Z(i,s.parentId,o,c);s.promotionSnapshot&&i.setPromotionSnapshot(s.parentId,s.promotionSnapshot)}}function Hp(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=ct(e);n.skipBeforeSnap||gr(e,a,new Set([String(t)]),r,i)}function jp(e,t,r,i,n){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:yt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(l.properties.event_source=t.eventSource),j(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:i,trackingEvents:[l],hoursPerDay:n})}async function Ho(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=sn(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;i.setActivityField(o,"autoScheduling",!1);let l;try{l=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{i.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d}=l;return{ok:!0,changes:jp(i,e,s,d,a.hoursPerDay)}}function Vp(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function Yp(e,t){if("afterSiblingId"in e){let a=t.getActivity(e.afterSiblingId);return a?{ok:!0,parentId:a.parentId==null?"0":String(a.parentId),firstAfter:e.afterSiblingId}:{ok:!1,reason:P.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,n=an(t,r).sort((a,s)=>ot(a)-ot(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function $p(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function jo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=Yp(e.destination,i);if(!s.ok)return s;let o=V(i,new Set),c=new Set,l=new Map,d=[],u;for(let k of e.activities){let S=l.get(k.originalParentId),D,p,y;S!==void 0?D=S:(D=s.parentId,u===void 0?(p=s.firstAfter,y=s.firstBefore):p=u);let v=sn({kind:"activity-create",parentId:D,afterSiblingId:p,beforeSiblingId:y,...k.activityId?{activityId:k.activityId}:{},overrides:$p(k.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...S!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!v.ok)return v;if(k.baselineSnapshot!==void 0){let E=k.baselineSnapshot;i.setActivityField(v.newId,"baselineSnapshot",E?{...E,startDate:E.startDate?new Date(E.startDate):null,endDate:E.endDate?new Date(E.endDate):null}:null)}l.set(k.originalId,v.newId),d.push(v.newId),S===void 0&&(u=v.newId)}let f=ct(i),h=new Set(d.map(String));gr(i,f,h,o,c);for(let k of d)c.add(String(k));let g=[];for(let k of e.links){let S=l.get(k.source),D=l.get(k.target);if(S===void 0||D===void 0)continue;let p={kind:"create",source:S,target:D,type:k.type,lag:pt(k.lag,a.hoursPerDay)},y=Nt(p,{port:i,newLinkId:k.linkId?()=>k.linkId:r.linkIdGen.next});g.push({op:p,finalLinkId:y.applied?y.linkId:null,rejected:y.applied?null:y.rejected??"link_op_rejected"})}let{scheduledIds:C}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),A=Pr(g,new Map,i);return{ok:!0,changes:j(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:C,links:A,hoursPerDay:a.hoursPerDay})}}function Vo(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:i,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function Yo(e,t){let r=[...new Set(e.activityIds.map(String))],i=r.map(a=>t.adapter.getActivity(a));if(i.some(a=>!a))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let n=[];for(let[a,s]of r.entries()){let o=i[a];if(!o)continue;let c={};o.isLookahead!==e.isLookahead&&(c.isLookahead={before:o.isLookahead,after:e.isLookahead},t.adapter.setActivityField(s,"isLookahead",e.isLookahead)),o.hasLookaheadTasks!==e.hasLookaheadTasks&&(c.hasLookaheadTasks={before:o.hasLookaheadTasks,after:e.hasLookaheadTasks},t.adapter.setActivityField(s,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(c).length!==0&&n.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:n,links:[],calendars:[],trackingEvents:[]}}}function wt(e,t){en(e,t),rn(e,t),nn(e,t)}function $o(e,t){let r=new Set,i=[];for(let n of e){let a=String(n);r.has(a)||(r.add(a),i.push(a))}for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);for(let s of a){let o=String(s);r.has(o)||(r.add(o),i.push(o))}}return r}function Go(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function Gp(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function Kp(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function Se(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=Gp(e.promotionSnapshot)??(i?{type:se,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Kp(t,r,e.computeEndDate)}:{type:se});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(n.newActivityIds=s)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Ko(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}async function zo(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:s}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:P.ACTIVITY_IDS_EMPTY};for(let y of e.activityIds)if(!i.getActivity(y))return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let o=$o(e.activityIds,i),c=Go(o,i),l=new Set;for(let y of e.activityIds){let v=i.getActivity(y);if(!v)continue;let E=v.parentId;if(b(E))continue;let T=String(E);o.has(T)||l.add(T)}let d=new Set([...o,...l]),u=V(i,d),f=new Map;for(let y of c){let v=i.getLink(y);v&&f.set(y,{...v})}let h=new Set;for(let y of o){let v=i.getActivity(y);if(!v)continue;let E=b(v.parentId)?null:i.getActivity(String(v.parentId)),T=E?.hasNewActivities===!0&&E.newActivityIds.some(O=>String(O)===String(y));(v.isNewActivity===!0||T)&&h.add(y);let R=v.customId;typeof R=="string"&&R.length>0&&a.releaseCustomId(R)}for(let y of c)i.removeLink(y);let g=qp(i,o);for(let y of o)i.removeActivity(y);for(let y of l){let v=i.getActivity(y);if(!v)continue;zp(v,h,i);let E=i.getChildren(y),T=Se({parent:v,remainingChildIds:E.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(y),computeEndDate:(R,O)=>i.calculateEndDate({startDate:R,durationHours:O,task:v}),idsRemoved:o});if(!T){lr(y,i);continue}for(let[R,O]of Object.entries(T.fields))Z(i,y,R,O);if(v.customId==null||v.customId===""){let R=Gt(y,i),O=R?i.getActivity(R)?.customId:null,N=a.generateCustomIdForRestoredChild(typeof O=="string"&&O?O:null);i.setActivityField(y,L.CUSTOM_ID,N)}}for(let y of l)wt(y,i);let C=ct(i);for(let y of C){if(d.add(y.activityId),u.has(y.activityId))continue;let v=i.getActivity(y.activityId);if(!v)continue;let E=J(v);y.before!==void 0&&(E.correlativeId=y.before),u.set(y.activityId,E)}let{scheduledIds:A}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),k={name:yt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(k.properties.event_source=e.eventSource);let S=new Map;for(let[y,v]of f)S.set(y,v);let D=new Map;for(let y of o){let v=u.get(String(y));v&&D.set(String(y),v)}let p=j(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:A,sirDetection:"after-diff",links:Jp(f),trackingEvents:[k],hoursPerDay:s.hoursPerDay});return{ok:!0,changes:g.length>0?{...p,viewState:g}:p,__beforeSnap:D,__beforeLinks:S}}function zp(e,t,r){let i=Ko({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))Z(r,i.parentId,n,a)}function qp(e,t){let r=[];for(let i of t){let n=e.isChecked(i),a=e.isVisible(i);!n&&a||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function Jp(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}function br(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let a=String(n.source),s=String(n.target);!r.has(a)&&!r.has(s)||(qo(s,a,t)||qo(a,s,t))&&i.push(String(n.id))}return i}function qo(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let a=r.getActivity(i);if(!a)return!1;let s=a.parentId;if(s===null||b(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function Jo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let s=i.getActivity(e.activityId);if(!s)return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let o=b(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:P.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:P.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:P.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let y=i.getActivity(c);if(!y)return{ok:!1,reason:P.ANCHOR_SIBLING_NOT_FOUND};if((y.parentId===null?"0":String(y.parentId))!==e.parentId)return{ok:!1,reason:P.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=zt(l),u=String(e.parentId),f=d!==u,h=new Set([e.activityId]);f?(d!=="0"&&h.add(d),u!=="0"&&h.add(u)):d!=="0"&&h.add(d);let g=V(i,h);f&&i.setActivityField(e.activityId,L.PARENT,u);let C=Lr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,L.CORRELATIVE_ID,C),f){if(!o){let y=i.getActivity(e.parentId);if(y){let v=y.customId,E=xt(y.type)&&i.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,T=Ie({parentId:e.parentId,newChildId:e.activityId,getParent:R=>i.getActivity(R)??null,isCurrentlyLeaf:E,promotionSource:"reparent"});if(T){for(let[R,O]of Object.entries(T.fields))Z(i,T.parentId,R,O);T.promotionSnapshot&&i.setPromotionSnapshot(T.parentId,T.promotionSnapshot),T.fields.customId===null&&Er(v,r.customIdTracker)}}}if(d!=="0"){let y=i.getActivity(d);if(y){let v=i.getChildren(d),E=Se({parent:y,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(T,R)=>i.calculateEndDate({startDate:T,durationHours:R,task:y}),idsRemoved:new Set([e.activityId])});if(E){for(let[X,z]of Object.entries(E.fields))Z(i,d,X,z);let T=Gt(d,i),R=T?i.getActivity(T)?.customId:null,O=typeof R=="string"&&R?R:null,N=r.customIdTracker.generateCustomIdForRestoredChild(O);i.setActivityField(d,L.CUSTOM_ID,N)}}}}f&&(d!=="0"&&wt(d,i),o||wt(e.parentId,i));let A=ct(i);for(let y of A){if(h.add(y.activityId),g.has(y.activityId))continue;let v=i.getActivity(y.activityId);if(!v)continue;let E=J(v);y.before!==void 0&&(E.correlativeId=y.before),g.set(y.activityId,E)}let k=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:S}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:r.now,options:t,recomputeParentProgress:f}),D=f?br([e.activityId],i):[],p={name:yt.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:D.map(String)}};return e.eventSource!==void 0&&(p.properties.event_source=e.eventSource),{ok:!0,changes:j(i,{source:e,beforeSnap:g,touchedIds:h,scheduledIds:S,sirDetection:"before-diff",trackingEvents:[p],hoursPerDay:a.hoursPerDay})}}async function Xo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:P.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(s),f=[...e.activityIds].sort((p,y)=>{let v=i.getActivity(p),E=i.getActivity(y),T=v?ot(v):te,R=E?ot(E):te;return T-R});for(let p of f){if(!i.getActivity(p)){c.push({activityId:p,reason:P.ACTIVITY_NOT_FOUND}),u.delete(p);continue}let v=_o(p,u,i);if(v==null){c.push({activityId:p,reason:P.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(p);continue}let E=i.getActivity(p)?.parentId,T=b(E)?"0":String(E);d.push({activityId:p,newParentId:v,oldParentId:T}),o.add(p),o.add(v),T!=="0"&&o.add(T)}let h=V(i,o);for(let{activityId:p,newParentId:y}of d)i.setActivityField(p,L.PARENT,y),i.setActivityField(p,L.CORRELATIVE_ID,Wo),l.push(p);let g=new Set;for(let{activityId:p,newParentId:y}of d){if(g.has(y))continue;g.add(y);let v=i.getActivity(y);if(!v)continue;let E=v.customId,T=xt(v.type)&&i.getChildren(y).filter(N=>!l.includes(N)).length===0,R=v.hasNewActivities&&v.newActivityIds.some(N=>String(N)===String(p)),O=Ie({parentId:y,newChildId:p,getParent:N=>i.getActivity(N)??null,isCurrentlyLeaf:T,promotionSource:"reparent"});if(O){for(let[N,X]of Object.entries(O.fields))Z(i,O.parentId,N,X);O.promotionSnapshot&&i.setPromotionSnapshot(O.parentId,O.promotionSnapshot),R||(i.setActivityField(y,L.HAS_NEW_ACTIVITIES,!1),i.setActivityField(y,L.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(y,L.CONSTRAINT_TYPE,"asap"),i.setActivityField(y,L.CONSTRAINT_DATE,null),i.setActivityField(y,L.CUSTOM_ID,null),Er(E,r.customIdTracker)}let C=new Set;for(let p of d)p.oldParentId!=="0"&&C.add(p.oldParentId),C.add(p.newParentId);for(let p of C)wt(p,i);let A=ct(i);for(let p of A){if(o.add(p.activityId),h.has(p.activityId))continue;let y=i.getActivity(p.activityId);if(!y)continue;let v=J(y);p.before!==void 0&&(v.correlativeId=p.before),h.set(p.activityId,v)}let{scheduledIds:k}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),S=br(l,i),D={name:yt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(p=>({activity_id:p.activityId,reason:p.reason})),invalid_link_ids:S}};return e.eventSource!==void 0&&(D.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(p=>{let y=c.find(v=>String(v.activityId)===String(p));return y?{activityId:String(p),ok:!1,reason:y.reason}:{activityId:String(p),ok:!0}}),changes:j(i,{source:e,beforeSnap:h,touchedIds:o,scheduledIds:k,trackingEvents:[D],hoursPerDay:a.hoursPerDay})}}async function Zo(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:P.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let p of e.activityIds){let y=p;i.getActivity(y)&&(o.set(y,Xi(y,i)),c.set(y,Uo(y,s,i)))}let l=new Set,d=[],u=[],f=new Set,h=[],g=[...e.activityIds].sort((p,y)=>{let v=i.getActivity(p),E=i.getActivity(y),T=v?ot(v):te,R=E?ot(E):te;return T-R});for(let p of g){let y=p,v=i.getActivity(y);if(!v){d.push({activityId:y,reason:P.ACTIVITY_NOT_FOUND});continue}let E=v.parentId;if(b(E)){d.push({activityId:y,reason:P.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let T=String(E),R=i.getActivity(T);if(!R){d.push({activityId:y,reason:P.ACTIVITY_NOT_FOUND});continue}let O=R.parentId;if(b(O)){d.push({activityId:y,reason:P.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let N=String(O),X=Xi(T,i)+1,z=c.get(y);if(z!=null&&s.has(z)){let gt=o.get(z)??-1,Te=o.get(y)??-1;gt>=0&&Te>=0&&(X+=Te-gt)}h.push({activityId:y,grandparentKey:N,oldParentKey:T,targetIndexInGrandparent:X}),l.add(String(y)),l.add(String(T)),N!=="0"&&l.add(String(N)),f.add(T)}let C=V(i,l);for(let p of h){i.setActivityField(p.activityId,L.PARENT,p.grandparentKey);let y=Bo(i,p.grandparentKey,p.targetIndexInGrandparent,p.activityId);i.setActivityField(p.activityId,L.CORRELATIVE_ID,y),u.push(p.activityId)}for(let p of f){let y=i.getActivity(p);if(!y)continue;let v=i.getChildren(p),E=Se({parent:y,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(p),computeEndDate:(X,z)=>i.calculateEndDate({startDate:X,durationHours:z,task:y}),idsRemoved:new Set(h.filter(X=>X.oldParentKey===p).map(X=>X.activityId))});if(!E){lr(p,i);continue}for(let[X,z]of Object.entries(E.fields))Z(i,p,X,z);let T=Gt(p,i),R=T?i.getActivity(T)?.customId:null,O=typeof R=="string"&&R?R:null,N=r.customIdTracker.generateCustomIdForRestoredChild(O);i.setActivityField(p,L.CUSTOM_ID,N)}let A=new Set;for(let p of f)A.add(String(p));for(let p of h)p.grandparentKey!=="0"&&A.add(String(p.grandparentKey));for(let p of A)wt(p,i);let k=ct(i);for(let p of k){if(l.add(p.activityId),C.has(p.activityId))continue;let y=i.getActivity(p.activityId);if(!y)continue;let v=J(y);p.before!==void 0&&(v.correlativeId=p.before),C.set(p.activityId,v)}let{scheduledIds:S}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),D={name:yt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(p=>({activity_id:String(p.activityId),reason:p.reason}))}};return e.eventSource!==void 0&&(D.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(p=>{let y=d.find(v=>String(v.activityId)===String(p));return y?{activityId:String(p),ok:!1,reason:y.reason}:{activityId:String(p),ok:!0}}),changes:j(i,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:S,trackingEvents:[D],hoursPerDay:a.hoursPerDay})}}async function Qo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:P.INVALID_PROGRESS_VALUE};let o=n.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:P.ACTIVITY_NOT_FOUND};let c=Bt(_.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,n,e.newValue),d=Ht(e.activityId,l),u=V(i,d);jt(i,e.activityId,l),Mt(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await $({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:g=>mr(e.activityId,d,g),now:r.now,options:t}),h=(l.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:j(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function tc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let g of e.edits){let C=Xp(g,r);if(s.push(C.verdict),!C.verdict.ok||!C.changes)continue;let A=Ht(g.activityId,C.changes);Zp(o,A,r);for(let p of A)c.add(p);let k=Ae(i,g.activityId),S=V(i,new Set([String(g.activityId)])).get(String(g.activityId))??null;jt(i,g.activityId,C.changes),Mt(g.activityId,C.changes.postProcessors??[],i,S),d.push(...Ce(k,i,g.activityId)),f||=!!C.changes.needsAutoSchedule;for(let p of C.changes.trackingEvents??[])l.push({name:p.name,properties:p.properties??{}});let D=me(g.activityId,C.changes.constraintWarning);D&&u.push(D)}let{scheduledIds:h}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:s,changes:j(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:h,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Xp(e,t){let{ctx:r}=t,i=e.activityId,n=Bt(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let a=r.activityReader.getActivity(e.activityId);if(!a)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??P.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??P.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??P.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Zp(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of V(r.adapter,i))e.set(n,a)}var on=_.CUSTOM_ID;async function ec(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(D=>D.column===_.DURATION)&&n.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],h=[],g=[],C=!1;for(let D of e.edits){let p=Qp(D,r);if(o.push(p.verdict),!p.verdict.ok||!p.changes)continue;let y=me(D.activityId,p.changes.constraintWarning);y&&g.push(y);let v=Ht(D.activityId,p.changes);ih(c,v,r);for(let N of v)u.add(N);rh(l,D,c),Dr(D.column)&&d.add(String(D.activityId));let E=Ae(i,D.activityId),T=V(i,new Set([String(D.activityId)])).get(String(D.activityId))??null,R=th(D,r),O=p.changes;jt(i,D.activityId,O),Mt(D.activityId,p.changes.postProcessors??[],i,T),eh(D,R,r),h.push(...Ce(E,i,D.activityId)),C||=!!p.changes.needsAutoSchedule;for(let N of p.changes.trackingEvents??[])f.push({name:N.name,properties:N.properties??{}})}let A={action:e,autoscheduleFrom:C?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},k=l.size>0,{scheduledIds:S}=await(k?_r({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:A,revertTargets:[...l].filter(([D])=>!d.has(D)).map(([D,p])=>({activityId:D,priorConstraintDate:p})),revert:(D,p)=>Tr(D,p,i,r.ctx.calendars)}):$({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},A));return{ok:!0,verdicts:o,changes:j(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:S,sirDetection:"before-diff",links:h,trackingEvents:f,warnings:g,hoursPerDay:a.hoursPerDay})}}function Qp(e,t){let{ctx:r}=t,i=e.activityId,n=Bt(e.column);if(!n)return{verdict:{activityId:i,ok:!1,reason:P.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:i,ok:!1,reason:P.ACTIVITY_NOT_FOUND},changes:null};let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??P.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??P.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??P.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===on&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,h=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),h))return{verdict:{activityId:i,ok:!1,reason:P.CUSTOM_ID_DUPLICATE},changes:null}}let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function th(e,t){if(e.column!==on)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function eh(e,t,r){if(e.column!==on)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,a=typeof n=="string"?n:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function rh(e,t,r){if(!kr(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function ih(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let[n,a]of V(r.adapter,i))e.set(n,a)}function nh(e,t,r,i,n,a){let s=String(e.id);if(s.length===0||n.has(s))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${s}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let o=r(s);if(!o.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${s}"`);if(o.current!==null&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(s),a.add(e.proplannerId)}function rc(e,t,r,i){let n=new Set,a=new Set;for(let s of e)nh(s,t,r,i,n,a)}function ic(e,t){let r=e.activities??[],i=e.links??[],n=new Map;for(let c of t.adapter.getAllActivities())c.proplannerId!=null&&n.set(c.proplannerId,String(c.id));let a=new Map;for(let c of t.adapter.getAllLinks())c.proplannerId!=null&&a.set(c.proplannerId,String(c.id));rc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},n),rc(i,"link",c=>{let l=t.adapter.getLink(c);return{exists:l!==null,current:l?.proplannerId??null}},a);let s=[],o=[];return t.adapter.batchUpdate(()=>{for(let c of r){let l=t.adapter.getActivity(c.id);!l||l.proplannerId===c.proplannerId||(t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:l.proplannerId,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}}))}for(let c of i){let l=t.adapter.getLink(c.id);!l||l.proplannerId===c.proplannerId||(t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:l.proplannerId,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}}))}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function nc(e){return typeof e=="string"&&e.length>0?Lt(e):e instanceof Date?e:null}function cn(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function wr(e,t){let r=cn(e.duration),i=cn(e.cost),n=cn(e.hh_work);return r===null||i===null||n===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:nc(e.start_date),endDate:nc(e.end_date),durationDays:r,cost:i,workHours:n,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function ac(e,t,r){let i=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,o)});let n=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=i.get(o);if(c===void 0)continue;let l=n.get(c);l?l.push(s):n.set(c,[s])}let a=[];for(let[s,o]of n)e.setActivityField(s,"baselinePoints",o.map(c=>wr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(n.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function ah(e){let t=rt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function sc(e){let t=[];return e.forEachActivity((r,i)=>{let n=ah(r);if(!n){r.baselineSnapshot!==null&&(e.setActivityField(i,"baselineSnapshot",null),t.push(i));return}e.setActivityField(i,"baselineSnapshot",n),t.push(i)}),t}function Or(e,t,r,i,n=null){let a=new Set;for(let s of ac(e,t,i))a.add(s);if(r)for(let s of Vt(e,r,n))a.add(s);for(let s of sc(e))a.add(s);for(let s of $t(e))a.add(s);return[...a]}function oc(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,a=0;for(let o of i){let c=sh(String(o),t,r);n.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of i){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(rt(c)){let u=n.get(String(o))??0;r.setActivityField(o,_.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,_.PONDERATOR,0)}}function sh(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=rt(i);if(!n)return 0;if(t==="COST")return xr(n.cost);if(t==="HH")return xr(n.workHours);let a=i.type;return a==="project"?cc(e,r):a==="milestone"?0:xr(n.durationDays)}function cc(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=rt(n);if(!a)continue;let s=n.type;s==="project"?r+=cc(String(i),t):s!=="milestone"&&(r+=xr(a.durationDays))}return r}function xr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function lc(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,_.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&oc(String(i),e,t)})}function Nr(e){for(let t of oh(e))lh(t,e)}function oh(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,ch(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function ch(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function lh(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let a of r){let s=t.getActivity(a);s&&i.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let n=ce(i);n!==null&&t.setActivityField(e,_.PROGRESS,cr(n))}function Fr(e,t){lc(t,e.adapter),Nr(e.adapter),e.now&&(Vt(e.adapter,e.now,e.defaultBaseCalendarId??null),bt(e.adapter,e.now)),$t(e.adapter),e.now&&It(e.adapter,e.sector.statusCriteria)}function dc(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(i=>i.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}function uc(e,t){let r=V(t.adapter,new Set(t.adapter.getAllIds())),i=dc(t),n=Or(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return dc(t)!==i&&Fr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:j(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function dh(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}function fc(e,t){dh(e.criterion);let r=new Set(t.adapter.getAllIds()),i=V(t.adapter,r);return Fr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:j(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function pc(e,t){let r=Ge(e.criteria),i=new Set(t.adapter.getAllIds()),n=V(t.adapter,i),a=It(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:j(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function hc(e,t,r){return e.kind==="persistence-acknowledge"?ic(e,r):e.kind==="baseline-apply"?uc(e,r):e.kind==="ponderator-criterion-set"?fc(e,r):e.kind==="status-criteria-set"?pc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Io(e,t,r):e.kind==="links-batch"?So(e,t,r):e.kind==="activity-create"?Ho(e,t,r):e.kind==="activity-paste"?jo(e,t,r):e.kind==="activity-delete"?zo(e,t,r):e.kind==="activity-move"?Jo(e,t,r):e.kind==="activity-indent"?Xo(e,t,r):e.kind==="activity-outdent"?Zo(e,t,r):e.kind==="activity-set-progress"?Qo(e,t,r):e.kind==="dates-batch"?tc(e,t,r):e.kind==="bulk-edit"?ec(e,t,r):e.kind==="selection-toggle"?Fn(e,ln(r)):e.kind==="selection-replace"?Mn(e,ln(r)):e.kind==="visibility-set"?Wn(e,ln(r)):e.kind==="sir-sync"?Vo(e,r):e.kind==="activity-lookahead-sync"?Yo(e,r):e.kind==="inline-edit"&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?ko(e,t,r):e.kind!=="inline-edit"?ka(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Co(e,t,r)}function ln(e){return{adapter:e.adapter}}var uh=new Set(["startDate","endDate","constraintDate"]);function yc(e,t){return uh.has(e)&&typeof t=="string"?new Date(t):t}function mc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?fh(n,r):null}}}function fh(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function ph(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ee(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function re(e){return ee(e)&&!isNaN(e.getTime())}var hh={}.constructor.toString();function yh(e){var t=e.constructor.toString();return t!==hh}function mh(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function kt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ee(e):r=new Date(e);break;case ph(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=kt(e[t]);break;default:if(yh(e))r=Object.create(e);else{if(mh(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=kt(e[t]));break}return r||e}function ke(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function gc(e){return typeof e<"u"}var Mr;function dn(){return Mr||(Mr=new Date().valueOf()),Mr++,Mr}function ut(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var vh=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},Ah=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let o=0;o<n.length;o++)switch(n[o]){case"%j":case"%d":i+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${o}]||0;`;break;case"%i":i+=`set[4]=temp[${o}]||0;`;break;case"%Y":i+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${o}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let s=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return o=>s(o,r.locale)},vc={date_to_str:vh,str_to_date:Ah},Ch=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),Ih=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),s=e.match(/%[a-zA-Z]/g);for(let o=0;o<s.length;o++)switch(s[o]){case"%j":case"%d":n[2]=a[o]||1;break;case"%n":case"%m":n[1]=(a[o]||1)-1;break;case"%y":n[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[o]||0;break;case"%i":n[4]=a[o]||0;break;case"%Y":n[0]=a[o]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[o]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},Ac={date_to_str:Ch,str_to_date:Ih};function Cc(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var o=!1;return e.config.csp==="auto"?(i===null&&n(),o=i):o=e.config.csp,o}var s={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=vc;return a()&&(l=Ac),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=vc;return a()&&(l=Ac),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),h=1+Math.floor(f/7);return h},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=r(o);if(f)return s._isoDateDetected?u&&(s._isoDateOnly=!1):(s._isoDateDetected=!0,s._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return s}function un(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function fn(e,t,r,i,n,a){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=a,this}function pn(e,t,r,i,n,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=s,this}function Sh(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var Ic=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ee(t)?t={date:t}:t=ke({},t),!re(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof un)return t;var r;if(t.date?r=new un(t.date,t.unit,t.task,null,t.calendar):r=new un(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!re(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof fn)return r;var i;if(ee(r)?i=new fn(r):i=new fn(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!re(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=Sh,i;if(t instanceof r)return t;if(ee(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!re(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!re(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var a=arguments[0];if(a instanceof pn)return a;var s;if(ee(a)?s=new pn(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new pn(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(s.task=a,s.unit=null,s.step=null),s.unit=s.unit||e.config.duration_unit,s.step=s.step||e.config.duration_step,!re(s.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return s}}};function Sc(){}Sc.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(a){var s=String(a);return s.length<2&&(s="0"+s),s}function i(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<i.length;o++){var c=i[o];c.start<s.end&&c.end>s.start&&(n.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(i.splice(o,1),o--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=kt(e.getConfig()),i=kt(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let o=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(s.dates[u]=!1);for(let h in d.dates){let g=d.dates[h];if(h==u&&(s.dates[u]=!!(f&&g)),Array.isArray(f)){let C=Array.isArray(g)?g:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,C))}}}};if(o(n,a),o(a,n),n.customWeeks)for(var c in n.customWeeks)s.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)s.customWeeks[c]?s.customWeeks[c+"_second"]=a.customWeeks[c]:s.customWeeks[c]=a.customWeeks[c];return s}};var hn=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let a=this._cache.get(t)[i.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache,s=n.getUTCFullYear(),o;a.has(t)?o=a.get(t):(o=[],a.set(t,o));let c=o[s];c||(c=o[s]=new Map),c.set(r,i)}clear(){this._cache=new Map}},yn=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let a=n[t];if(a===void 0)return-1;let s=a[i.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=n.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=i}clear(){this._cache={}}},mn=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(i,s),s},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r)),c=a.date.add(o,1,"month").valueOf();for(;o.valueOf()<c;)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(i,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function kh(){return typeof Map<"u"?new hn:new yn}var gn=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let a=n[r];a||(a=n[r]={});let s=a[i];s||(s=a[i]={});let o=t.getUTCFullYear(),c=s[o];return c||(c=s[o]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=this._endDateCacheKey(o,r),l;if(s.endDates[c]===void 0){let d=a(),u=d.valueOf();s.endDates[c]=u,s.durations[this._durationCacheKey(o,u)]=r,l=d}else l=new Date(s.endDates[c]);return l}getDuration(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(o,c),d;if(s.durations[l]===void 0){let u=a();s.durations[l]=u.valueOf(),d=u}else d=s.durations[l];return d}clear(){this._cache={}}};function vn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=kh(),this._largeUnitsCache=new mn(this),this._dateDurationCache=new gn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}vn.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,a=new Date(e),s=new Date(t);i=i||1;var o=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var h=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),h=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&h)&&(l=n[r+"_start"](new Date(a)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),o+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&h?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var g=this._getUnitOrder(r),C=this.units[g-1];C&&!this._isWorkTime(a,C)&&(c=this._getClosestWorkTimeFuture(a,C))}a=c}return o},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var a=i[n];if(t>=a.start&&r<=a.end)return 60;if(t<a.end&&r>a.start){var s=Math.min(r,a.end)-Math.max(t,a.start);return s/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=ut(this._getMinutesPerDay,this):o=ut(this.getHoursPerDay,this);a.valueOf()<s.valueOf();){if(s-a>1e3*60*60*24*32&&a.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,1,"month");continue}else if(s-a>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,7,"day");continue}}n+=o(a),a=this._nextDate(a,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,a=0;a<i.length;a++){var s=i[a];if(r.end>=s.start&&r.start<=s.end){var o=Math.max(s.start,r.start),c=Math.min(s.end,r.end);n+=(c-o)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(o,c,r,i),h=d+f+u;return h},_getHoursBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(o,c,r,i),h=d+f+u;return Math.round(h)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var a=n.from,s=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<s.valueOf())&&(i=s.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:s.valueOf(),toReadable:new Date(s),name:t}),e.parsed.haveCustomWeeks=!0;var o=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)o.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var a=r[n],s=e.dates[a],o=t.dates[a];if(s!==o&&!(Array.isArray(s)&&Array.isArray(o)&&this._arraysEqual(s,o)))return!1}return!0},equals:function(e){if(!(e instanceof vn))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],a=r.parsed.customWeeks[i];if(!a||!this._compareSettings(n,a))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=n&&r.customWeeksBoundaries[a].to>n){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[n]!==void 0?s=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(s=r.dates[e.getUTCDay()]),s===!0?r.hours:s||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(o){typeof o=="number"?t.push(o*60*60):typeof o=="string"&&o.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],a=t[i+1],s=a-n;r.push({start:n,end:a,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(ut(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(ut(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),a*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var a=new Date(t),s=new Date(r);for(n=n||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return s._calculateEndDate(t,r,i,n*a)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var a=0,s=e;a<t&&!(n&&n(s));){var o=this._nextDate(s,r,i),c=new Date(o.valueOf()+1);i>0&&(c=new Date(o.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,s=o}return{end:s,start:e,added:a}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,a.start=d}}var h=r;return i===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:h}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(i,t);n=a.added,i=a.end;var s=t-n;if(s){for(var o=i;n<t;){var c=this._nextDate(o,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,o=c}i=o}if(n<t){var s=t-n;a=this._addHoursUntilDayEnd(i,s),i=a.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,a.start=d}}var h=r;return i===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:h}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,a=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),s=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),o=this._getWorkHours(e),c=o.length-1;c>=0&&i<t;c--){var l=o[c];if(s>l.start&&a<=l.end){var d=Math.min(s,l.end),u=Math.max(a,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var h=Math.abs(Math.round((d-u)/60));n-=h,i+=h,s=u}}var g=r;return i===t&&(g=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:i,end:g}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(i),s=this._subtractMinutesUntilHourStart(i,t);n+=s.added,i=s.end;for(var o=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==o&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),o=f);var h=t-n,g=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=g&&h>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var C=!1,A=null,k=null,S=c.length-1;S>=0;S--)if(c[S].start<g-1&&c[S].end>=g-1){C=!0,A=c[S],k=c[S-1];break}if(C)if(g===A.end&&h>=A.durationMinutes)n+=A.durationMinutes,i=this.$gantt.date.add(i,-A.durationMinutes,"minute");else if(!a&&h<=g/60-A.startMinute)n+=h,i=this.$gantt.date.add(i,-h,"minute");else if(a)h<=g/60-A.startMinute?(n+=h,i=this.$gantt.date.add(i,-h,"minute")):(n+=g/60-A.startMinute,k?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,k.end)):i=this.$gantt.date.day_start(i));else{var D=this._getMinutesPerHour(i);D<=h?(n+=D,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,h),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var p=this._getClosestWorkTimePast(i,"hour");if(p.valueOf()===i.valueOf()){var p=this.$gantt.date.add(i,-1,"day"),y=this._getWorkHours(p);if(y.length){var v=y[y.length-1];p.setUTCSeconds(v.durationSeconds)}}i=p}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var E=t-n;s=this._subtractMinutesUntilHourStart(i,E),n+=s.added,i=s.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(i,t);n+=a.added,i=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==s&&(o=this._getWorkHours(i),c=this._getMinutesPerDay(i),s=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!o.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(o[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o[o.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var h=!1,g=null,C=0;C<o.length;C++)if(o[C].start<=f&&o[C].end>f){h=!0,g=o[C];break}if(h)if(f===g.start&&u>=g.durationMinutes)n+=g.durationMinutes,i=this.$gantt.date.add(i,g.durationMinutes,"minute");else if(u<=g.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var A=this._getMinutesPerHour(i);A<=u?(n+=A,l?i=this.$gantt.date.add(i,A,"minute"):i=this._nextDate(i,"hour",r)):(a=this._addMinutesUntilHourEnd(i,u),n+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var k=t-n;a=this._addMinutesUntilHourEnd(i,k),n+=a.added,i=a.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),a=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-a)?i=n:i=a}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),a=!0),r=this._getWorkHours(i));var s=this._getTimeOfDayStamp(i);if(a&&(s=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n);return a||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(n&&!this._isWorkTime(a,n)&&(r>0?a=this._getClosestWorkTimeFuture(a,n):a=this._getClosestWorkTimePast(a,n),this._isWorkTime(a,t)));){if(o++,o>s)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=n:Array.isArray(o)&&(a=this._checkWorkHours(o))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var Ue={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function Dh(){function e(n){return n.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(n,a){return a.mergeCalendars(n.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function i(n,a){var s=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(n,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:i}}var Th=Dh();function kc(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Ue.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}kc.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new Sc,n;return e.forEach((function(a){n?n=this._createCalendarFromConfig(i.merge(n,a)):n=a}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new vn(this.$gantt,Ic(this.$gantt));t.id=String(dn());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=kt(e.getConfig()):e.worktime?t=kt(e.worktime):t=kt(e);var r=kt(this.defaults.fulltime.worktime);return ke(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=Ue.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Th.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Ue.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Ue.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Ue.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][t]){n=i[a][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||dn(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function An(e,t){this.argumentsHelper=t,this.$gantt=e}An.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},s=0;if(a[r])s=Math.round((t-e)/(i*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=n.add(o,i,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(n.add(o,i,r)-o))}return Math.round(s)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof An},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function Dc(e){this.$gantt=e.$gantt,this.argumentsHelper=Ic(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new An(this.$gantt,this.argumentsHelper)}Dc.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var _h=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,a){return t.calculateEndDate(r,i,n,a)},mergeCalendars:ut(e.mergeCalendars,e),createCalendar:ut(e.createCalendar,e),addCalendar:ut(e.addCalendar,e),getCalendar:ut(e.getCalendar,e),getCalendars:ut(e.getCalendars,e),getResourceCalendar:ut(e.getResourceCalendar,e),getTaskCalendar:ut(e.getTaskCalendar,e),deleteCalendar:ut(e.deleteCalendar,e)}},Ph={create:_h};function Tc(e){var t=new kc(e),r=new Dc(t),i=Ph.create(t,r);ke(e,i)}var _c={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{}};function Pc(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||_c,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let a=e.onEvent;return a&&a(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:gc,mixin:ke,copy:kt,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=Cc(r),r.date.init(),Tc(r),r}function Eh(e={}){let t=Pc(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var Ec={createCalendar:Eh};var UL=3600*1e3;function wc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Rh}=Ec,Be="__replay_default__";function Lh(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(a=>Number.isNaN(a)))return e;let r=t[0],i=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${i+1}:00`]:e}var Rc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Lc="__main_global__",bh={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function bc(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function wh(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:Lh(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Oc(e){let t=Rh({config:{work_time:!0}});t.addCalendar({id:Be,worktime:Rc}),t.addCalendar({id:Lc,worktime:bh});let r=new Set(e.filter(d=>!bc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>bc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?wh(d.worktime):Rc});let n=mc(t),a=n.getCalendar(Be),s=n.getCalendar(Lc);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([Be]);for(let d of i)o.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let h=a;return o.has(u)?h=n.getCalendar(d)??a:r.has(u)&&(h=s),c.set(u,h),h}}}}function xc(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return Oh(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let a=e.getActivity(n);if(!a)break;r.push(String(n)),i=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function Oh(e,t){let r=[],i=new ft;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let a of e.getChildren(n))i.enqueue(a)}return r}var Wr=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,ge(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:"remove",activityId:t,before:ge(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:"link-remove",linkId:t,before:Nc(r)})}noteCorrelativeBefore(t,r){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let i=this._journal;if(!i)return;let n=ge(r);i.scheduledBefore.has(t)||i.scheduledBefore.set(t,n),i.before.has(t)||i.before.set(t,n),i.dirty.add(t)}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:Nc(r)}))}};function Nc(e){return{...e}}var Ur=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Fc(t);return this.reader.getCalendar(r??Be)}getClosestWorkTime(t){let r=`${In(t.task)}|${t.dir}|${t.date.getTime()}`;return Cn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:nt.HOUR}))}calculateEndDate(t){let r=`${In(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Cn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${In(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Cn(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function Cn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var xh="__default__";function Fc(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function In(e){return Fc(e)??xh}var Br=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,a=this.activities.size;for(;i&&!b(i);){if(i===r)return!0;if(++n>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||b(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(b(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(b(r.parentId)){this._roots.push(r.id);continue}let i=String(r.parentId),n=this._childrenByParent.get(i)??[];n.push(r.id),this._childrenByParent.set(i,n)}let t=(r,i)=>{let n=this.activities.get(r),a=this.activities.get(i);return n&&a?Qi(n,a):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Hr=class{checkedSet=new Set;hiddenSet=new Set;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[])}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet)}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden)}};var De=class{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_cache={ids:null,visualOrderIds:null};_writeCapture=new Wr;_viewState=new Hr;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;constructor(t){for(let r of t.activities)this._activities.set(r.id,r);for(let r of t.links)this._links.set(String(r.id),r),this._indexLink(r);this._calendar=new Ur(Oc(t.calendars)),this._flags=Fh(t),this._hierarchy=new Br(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=To(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}hydrateViewState(t){this._viewState.hydrate(t)}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??Mc}getIncomingLinkIds(t){return this._incoming.get(String(t))??Mc}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,r===L.PARENT&&this._hierarchy.markDirty(),Sn(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,yc(r,i)),r===L.PARENT&&this._hierarchy.markDirty(),Sn(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let a of Object.keys(r))Reflect.set(i,a,Reflect.get(r,a)),a===L.PARENT&&(n=!0),Sn(a)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r),this._links.set(String(t.id),{...t}),this._indexLink(t)}_indexLink(t){Uc(this._outgoing,String(t.source),t.id),Uc(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Wc(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),Wc(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!Nh(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&(this._captureViewStateOnce(),this._viewState.forget(i)),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._viewStateBefore!==null&&this._viewState.restore(this._viewStateBefore),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind==="link-add"&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind==="insert"&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind==="remove"&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind==="link-remove"&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind==="link-field"&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},Mc=[];function Nh(e){return e===Ai.LAG||e===Ai.TYPE}function Sn(e){return e===L.PARENT||e===L.CORRELATIVE_ID}function Wc(e,t){return e.filter(r=>String(r)!==String(t))}function Uc(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Fh(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function et(e){return structuredClone(e)}function Bc(e,t){let r=e.getActivity(t);return r?et(r):null}function Hc(e){return e.getAllActivities().map(et)}function jc(e){return e.getAllIds().map(String)}function Vc(e,t){e.forEachActivity((r,i)=>t(i))}function Yc(e,t){let r=t==="0"?kn(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(et(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function kn(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{b(n.parentId)&&i.push(a)}),i}return[...e.getChildren(r)].map(String)}function $c(e){return e.checkedIds().map(String)}function Gc(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=b(i.parentId)}),r}return e.getChildren(t).length>0}function Kc(e,t){let r=e.getLink(t);return r?St(r):null}function zc(e){return e.getAllLinks().map(t=>St(t))}function jr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Mh(e){return e.reduce((t,r)=>jr(r)<jr(t)?r:t)}function Wh(e){return e.reduce((t,r)=>jr(r)>jr(t)?r:t)}function Uh(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function qc(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Uh(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Mh(i),endHour:Wh(n)}}function Jc(e,t){return{calendars:e.calendarReader,hierarchy:xc(e),activityReader:wc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function Xc(e){return We(e)}function Dn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function tl(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!=="created")continue;let a=e.getActivity(String(n.id));a&&r.set(String(n.id),J(a))}for(let n of t.links){if(n.kind!=="created")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function el(e){return e.kind!=="inline-edit"||!Me.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Zc(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function rl(e,t){if(!Zc(e)||!Zc(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function il(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},a=i.fields??{},s={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...i,fields:s}]};return Dn(o)}function nl(e){return e.kind==="persistence-acknowledge"?"clear-on-success":e.kind==="sir-sync"||e.kind==="activity-lookahead-sync"||e.kind==="baseline-apply"||e.kind==="ponderator-criterion-set"||e.kind==="status-criteria-set"?"skip":"record"}function Tn(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&_.CUSTOM_ID in t.fields)return!0;return!1}function _n(e,t,r){let i=[],n=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);i.push({id:o,kind:"updated",fields:Qc(s.fields,r),after:c?J(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?J(c):null})}else i.push({id:o,kind:"deleted",after:null});else if(r==="before")i.push({id:o,kind:"deleted",after:null});else{let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?J(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);n.push({id:o,kind:"updated",fields:Qc(s.fields,r),after:c?St(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);n.push({id:o,kind:"created",after:c?St(c):null})}else n.push({id:o,kind:"deleted",after:null});else if(r==="before")n.push({id:o,kind:"deleted",after:null});else{let c=e.getLink(o);n.push({id:o,kind:"created",after:c?St(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Bh(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Qc(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:et(i.after),after:et(i.before)}:{before:et(i.before),after:et(i.after)}]))}function Bh(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function Pn(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function al(e,t){ol(e,t,"before")}function sl(e,t){ol(e,t,"after")}function ol(e,t,r){let i=t.changeSet;for(let n of i.activities)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Z(e,n.id,a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${n.id}`);e.addActivity(J(a))}else e.removeActivity(String(n.id));else if(r==="before")e.removeActivity(String(n.id));else{let a=t.afterSnap?.get(String(n.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${n.id}`);e.addActivity(J(a))}for(let n of i.links)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Ns(e,String(n.id),a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${n.id}`);e.addLink(a)}else e.removeLink(String(n.id));else if(r==="before")e.removeLink(String(n.id));else{let a=t.afterLinks?.get(String(n.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${n.id}`);e.addLink(a)}for(let n of i.viewState??[])n.checked&&e.setChecked(n.activityId,r==="before"?n.checked.before:n.checked.after),n.visible&&e.setVisible(n.activityId,r==="before"?n.visible.before:n.visible.after)}var Hh=100,jh=600,Vr=class{constructor(t=Hh){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=jh&&n!==void 0&&rl(n,t)?this.undoStack[this.undoStack.length-1]=il(n,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.shift()),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()??null}takeRedo(){return this.redoStack.pop()??null}pushRedo(t){this.redoStack.push(t)}pushUndo(t){this.undoStack.push(t)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}};function Vh(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Yh(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function cl(e){return{id:String(e.id),worktime:Yh(e.worktime)}}function Yr(e,t,r,i=[]){let n=t.map(Vh),a=[...r.map(cl),...i.map(cl)];return{activities:[...e],links:n,calendars:a}}var ll=["id","proplannerId","parentId","name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","assignedDefaultCalendar","dateOrigin","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","correlativeId","uniqueCorrelativeId","customId","subcontractId","isLookahead","newActivityIds","hasNewActivities","pendingRequestIds","responsableIds","tagIds"],dl=new Set(["startDate","endDate","constraintDate","dateOrigin"]),ul=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function fl(e){let t=ll.map(r=>[r,$h(r,e[r])]);return Object.fromEntries(t)}function $h(e,t){return dl.has(e)?t instanceof Date?new Date(t):null:ul.has(e)?Array.isArray(t)?[...t]:[]:t}function pl(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of ll)if(!Gh(r,e[r],t[r]))return!0;return!1}function Gh(e,t,r){return dl.has(e)?Kh(t,r):ul.has(e)?zh(t,r):(t??null)===(r??null)}function Kh(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function zh(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],i=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==i.length?!1:r.every((n,a)=>n===i[a])}var $r=class{initialized=!1;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.activitiesAtLastSave.set(String(r.id),fl(r))}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{lag:r.lag,type:r.type})}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let i=this.activitiesAtLastSave.get(String(r.id));return i?pl(r,i):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let i=this.linksAtLastSave.get(String(r.id));return i?r.lag!==i.lag||r.type!==i.type:!0}):[]}clear(){this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var hl=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var En=[!1,!0,!0,!0,!0,!0,!1],yl=new Set(["1","true"]),Rn="DURATION",ml="asap",gl={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo","AS SOON AS POSSIBLE":"asap","AS LATE AS POSSIBLE":"alap","START NO EARLIER THAN":"snet","START NO LATER THAN":"snlt","FINISH NO EARLIER THAN":"fnet","FINISH NO LATER THAN":"fnlt","MUST START ON":"mso","MUST FINISH ON":"mfo"};function vl(e,t){let r=[],i=e.map(a=>{let s=iy(a,t);return a.should_be_showed===!1&&r.push(s.id),s});ny(i);let n=new Set(i.map(a=>a.id));return ay(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function qh(e){return e===0}function Jh(e,t){if(!e)return null;let r=gl[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),ml):r}function Xh(e,t){let r=Jh(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Lt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function Zh(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function Qh(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function ty(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Ln(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)ty(r)&&t.push(String(r.id));return t}function ey(e){return e==="0"?null:String(e)}function ry(e,t){return Array.isArray(e)?e.map(r=>wr(r,t)).filter(r=>r!==null):[]}function iy(e,t){let r=Zh(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=Xh(e,t.reporter),o=e.type==="milestone",c=Lt(e.start_date),l=o?c:Lt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:ey(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Re(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:qh(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Lt(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:e.custom_id,subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Qh(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Ln(e.pendingRequests),responsableIds:Ln(e.responsables),tagIds:Ln(e.tags),baselinePoints:ry(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Re(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function ny(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function ay(e,t,r){for(let i of e)i.parentId!==null&&(t.has(i.parentId)||(r.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),i.parentId=null))}function Sl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>cy(c,i)),o=(r??[]).map(c=>ly(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:oy(s)}}function oy(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function kl(e,t){let r=yy(e.working_days),{days:i,hours:n}=hy(e,r),a=dy(t.exceptionsSource,t.exceptionRange),s={days:i,hours:n};return a&&(s.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:s}}function cy(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return kl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function ly(e,t){return kl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function dy(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=uy(i.from_date,i.to_date,t);if(n.length===0)continue;let a=fy(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function uy(e,t,r){let i=Al(e),n=Al(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],s=r?Math.max(i,r.start):i,o=r?Math.min(n,r.end):n;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function Al(e){if(typeof e!="string")return null;let t=hl.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function fy(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=py(t);if(r.length>0)return r}}var Cl=/^\d{1,2}:\d{2}$/;function py(e){let t=[];for(let r of e){let i=_l(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!Gr(o)&&!Gr(c)&&Cl.test(o)&&Cl.test(c)&&t.push(`${o}-${c}`);continue}let s=Tl(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Dl),t}function Il(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function Dl(e,t){return Il(e)-Il(t)}function hy(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Tl(l,d);for(let f=0;f<7;f+=1){let h=u[f],g=r[f];h&&g&&g.push(h)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=_l(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(Dl);let o=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:o}),hours:o}}function Tl(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(o=>o.trim()),n=t.split(",").map(o=>o.trim());if(!(i.length===n.length&&i.length>0&&i.length<=7))return r;let s=[...r];for(let o=0;o<i.length;o+=1){let c=i[o],l=n[o];Gr(c)||Gr(l)||(s[o]=`${c}-${l}`)}return s}function _l(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function yy(e){if(typeof e!="string")return[...En];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...En]:t.map(r=>yl.has(r))}var my=new Set(["false","null"]);function Gr(e){return!e||my.has(e)}function gy(e){return e==="0"||e==="1"||e==="2"||e==="3"}function vy(e){if(typeof e!="string")return null;let t=Xa(e);return t||(gy(e)?e:null)}function El(e,t){let r=[];for(let i of e)try{r.push(Ay(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return Cy(r)}function Ay(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let s=vy(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:i,source:n,target:a,type:s,lag:pt(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function Cy(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||Pl(r)>Pl(n))&&t.set(i,r)}return[...t.values()]}function Pl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Iy(e){if(typeof e!="string")return Rn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Rn}}function Sy(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function ky(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Rl(e){let t=Sy(e),r=ky(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:Iy(e.activity_creter),statusCriteria:ai}}function Kr(e,t=oe){let r=Rl(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=Sl(e.calendars,e.sector.calendars,e.baseCalendars,Dy(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=vl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=El(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Dy(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let s=new Date(a.start_date).getTime(),o=new Date(a.end_date).getTime();Number.isFinite(s)&&(t=Math.min(t,s)),Number.isFinite(o)&&(r=Math.max(r,o))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function Ll(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function bl(e={}){let t=e.seed??Date.now(),r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function wl(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)}}}function Ol(e){return!!e&&typeof e=="string"&&e.trim().length>0}function zr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function qr(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function xl(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Nl(e,t){return!t&&Ol(e)}function Fl(e,t){return t&&Ol(e)}function je(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function He(e){if(!je(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Ty(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!je(t))return r;let i=t.length;return r.padStart(i,"0")}function mt(e,t){let r=He(e),i=He(t),n=r+i;return Ty(n,e)}function Jr(e,t){let r=He(e),i=He(t);return r<i?-1:r>i?1:0}function Xr(e,t){return Jr(e,t)<=0?e:t}function Zr(e,t){return Jr(e,t)>=0?e:t}function Ml(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Xr(t,r))}function Wl(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Zr(t,r))}function Ul(e){return{prefix:e,baseSuffix:null}}function Bl(e,t){let r=qr(e);return{prefix:zr(e),baseSuffix:mt(r,t)}}function Hl(e){return{prefix:e,baseSuffix:null}}function jl(e,t){return Nl(e,t)?"parentConversion":Fl(e,t)?"pasteReference":"noContext"}function _y(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Qr=class{prefixMap=new Map;processedIds=new Set;_journal=null;beginCustomIdTransaction(){this._journal=[]}commitCustomIdTransaction(){this._journal=null}rollbackCustomIdTransaction(){let t=this._journal;if(t!==null){for(let r of[...t].reverse()){let{prefix:i}=this.analyzeCustomId(r.customId);r.prefixBefore===null?this.prefixMap.delete(i):this.prefixMap.set(i,r.prefixBefore),r.hadId?this.processedIds.add(r.customId):this.processedIds.delete(r.customId)}this._journal=null}}_noteCustomIdBefore(t){if(this._journal===null)return;let{prefix:r}=this.analyzeCustomId(t),i=this.prefixMap.get(r);this._journal.push({customId:t,prefixBefore:i?_y(i):null,hadId:this.processedIds.has(t)})}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return zr(t)}extractSuffix(t){return qr(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=Xr(r,i.min),i.max=Zr(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=Xr(i,n.min),n.max=Zr(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:mt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);if(n.usedSuffixes.has(i)){let a=n.quantity-1;if(a===0)this.prefixMap.delete(r);else{let s=new Set(n.usedSuffixes);s.delete(i);let o=Array.from(s);o.length===0?this.prefixMap.delete(r):(n.usedSuffixes=s,n.min=Ml(o),n.max=Wl(o),n.quantity=a,this._recalculateNext(r))}}return this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${mt(r.max,this.suffixIncrement)}`.length>20}_findFirstAvailableGap(t){if(!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;Jr(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=mt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(!this.prefixMap.has(t)){let o=r&&je(r)?r:this.suffixIncrement;return`${t}${o}`.length>20?null:o}let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!je(r)){let o=mt(i.max,n);return`${t}${o}`.length>20?null:o}let a=r;for(let o=0;o<100;o++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=mt(a,n)}let s=mt(i.max,n);return`${t}${s}`.length>20?null:s}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),a=0;for(;n.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,mt(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:a}=this.analyzeCustomId(i);(n||a)&&(this._updatePrefixStats(n,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=xl(r),a=jl(n,i),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){let f=this.prefixMap.get(s).max;c=mt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:o,d=this.getNextAvailableSuffix(s,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${s}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return Ul(this.defaultPrefix);case"pasteReference":return Bl(r,this.suffixIncrement);default:return Hl(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),s=mt(a,this.suffixIncrement),o=this.getNextAvailableSuffix(n,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${o}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};function Vl(e){let t=[];e.forEachActivity((r,i)=>{r.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,L.TYPE,se),Py(e,r)}function Py(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:q.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,L.START_DATE,n),e.setActivityField(t,L.END_DATE,a)}function ti(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(n);if(!a)return 0;let s=[...e.getChildren(n)],o=s.length===0?lt(a.workHours,a.progress):s.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,L.REAL_WORK_HOURS,o),r.push(n),o};for(let n of t)i(n);return r}async function Yl(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(ct(t),r.updateDurationForPrimaveraEndDate&&Ry(t),Ly(t),ti(t),n){a&&(bt(t,a),It(t,r.statusCriteria));return}let s=await i.schedule({});Ee(t,s),by(t),Ey(t),await le(t,void 0,!1),a&&(bt(t,a),It(t,r.statusCriteria))}function Ey(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}))})}function Ry(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Ly(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=Et(t.constraintDate,n,r))})}function by(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=Et(t.constraintDate,i,r))})}var Tt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function $l(e){let t=e.clock??null,r=t?Le(t()):null,i=e.reporter??oe,n=Kr({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=Ge(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Yr(n.activities,n.links,n.calendars,o),l=new De(c);l.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let d=new or(l,i);Vl(l);let u=Ll({knownIds:n.activities.map(A=>A.id)}),f=bl({knownIds:n.links.map(A=>A.id)}),h=wl({knownIds:n.activities.map(A=>A.uniqueCorrelativeId)}),g=new Qr({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(g.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let A=o.find(k=>k.baseDefault)?.id??null;Or(l,e.baselinePoints,r,i,A)}let C=Yl({state:l,sector:a,scheduler:d,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:l,scheduler:d,activityIdGen:u,linkIdGen:f,uidGen:h,customIdTracker:g,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:C}}var ei=class{_status=Tt.READY;coreRuntime;_undo=new Vr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=$l(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==Tt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(async()=>{let n=await this._runCriticalPathAndCapture();return this._criticalPathRevision=this._scheduleRevision,n}));let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return et(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Bc(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),Hc(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),Yc(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Kc(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),zc(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?et(i[r]):null}getAllIds(){return this.assertReady(),jc(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Vc(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),kn(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),$c(this.coreRuntime.state)}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),Gc(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?et(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>et(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>et(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),qc(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities()).map(et)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}async dispatch(t,r={}){return this._enqueue(()=>this._dispatchInner(t,r))}async _dispatchInner(t,r={}){this.assertReady();let i=Jc(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=nl(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a;try{a=await hc(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(s=>s.baseDefault)?.id??null,now:this.coreRuntime.clock?Le(this.coreRuntime.clock()):null}),a.ok||this._rollback()}catch(s){throw this._rollback(),s}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(a.ok&&n==="record"&&Pn(a.changes)){let s=tl(this.coreRuntime.state,a.changes);this._undo.record(Dn(a.changes,a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),el(t),Date.now())}return a.ok&&n==="clear-on-success"&&(this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities()),this._saveTracker.snapshotLinks(this.getAllLinksView()),this._undo.clear()),a.ok?(mo(t)&&Pn(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),et(a)):a}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_recordScheduleMutation(t){this._scheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===Tt.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},i=new De(Yr(this.coreRuntime.state.getAllActivities().map(o=>J(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==Tt.DESTROYED&&this._scheduleRevision===t,a=(async()=>{let o=await Yi(i,this.coreRuntime.sector.hoursPerDay,n);if(!n())return null;let c=o??new Map;return this._enqueue(async()=>{if(!n())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let l;try{for(let[d,u]of c)this.coreRuntime.state.setActivityFields(d,u);l=j(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(d){throw this._rollback(),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:l}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let s=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(s,s),a}async _runCriticalPathAndCapture(){if(this._status===Tt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Sr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=j(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:t}}_recomputeAfterHistoryRestore(){let t=this.coreRuntime.state;if(Nr(t),ti(t),$t(t),this.coreRuntime.clock){let r=Le(this.coreRuntime.clock());bt(t,r);let i=!1;t.forEachActivity(n=>{i||=rt(n)!==null}),i&&Vt(t,r,this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null),It(t,this.coreRuntime.sector.statusCriteria)}}undo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeUndo();return r?(al(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),Tn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce(),_n(this.coreRuntime.state,r,"before")):null});return t.then(r=>{r&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",i)})},()=>{}),t}redo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeRedo();return r?(sl(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),Tn(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce(),_n(this.coreRuntime.state,r,"after")):null});return t.then(r=>{r&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",i)})},()=>{}),t}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=Tt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new $r;assertReady(){if(this._status===Tt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Tt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction()}catch(t){throw this._status=Tt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function Gl(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?n.lag!==i.lag||n.type!==i.type:!1})}var Kl=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var zl={asap:"AS SOON AS POSSIBLE",alap:"AS LATE AS POSSIBLE",snet:"START NO EARLIER THAN",snlt:"START NO LATER THAN",fnet:"FINISH NO EARLIER THAN",fnlt:"FINISH NO LATER THAN",mso:"MUST START ON",mfo:"MUST FINISH ON"};var ql=8;var G={PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},wy={[G.PERSISTENCE_ACKNOWLEDGE]:!0,[G.BASELINE_APPLY]:!0,[G.PONDERATOR_CRITERION_SET]:!0,[G.STATUS_CRITERIA_SET]:!0,[G.INLINE_EDIT]:!0,[G.DATES_BATCH]:!0,[G.BULK_EDIT]:!0,[G.LINK_CREATE]:!0,[G.LINK_UPDATE]:!0,[G.LINK_DELETE]:!0,[G.LINKS_BATCH]:!0,[G.ACTIVITY_CREATE]:!0,[G.ACTIVITY_DELETE]:!0,[G.ACTIVITY_MOVE]:!0,[G.ACTIVITY_INDENT]:!0,[G.ACTIVITY_OUTDENT]:!0,[G.ACTIVITY_SET_PROGRESS]:!0,[G.ACTIVITY_PASTE]:!0,[G.SELECTION_TOGGLE]:!0,[G.SELECTION_REPLACE]:!0,[G.VISIBILITY_SET]:!0,[G.SIR_SYNC]:!0,[G.ACTIVITY_LOOKAHEAD_SYNC]:!0},Jl=Object.keys(wy);var Xl={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return nd(Oy);})();
1
+ "use strict";var ScheduleCore=(()=>{var di=Object.defineProperty;var Id=Object.getOwnPropertyDescriptor;var Sd=Object.getOwnPropertyNames;var kd=Object.prototype.hasOwnProperty;var Dd=(e,t)=>{for(var r in t)di(e,r,{get:t[r],enumerable:!0})},Td=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Sd(t))!kd.call(e,n)&&n!==r&&di(e,n,{get:()=>t[n],enumerable:!(i=Id(t,n))||i.enumerable});return e};var _d=e=>Td(di({},"__esModule",{value:!0}),e);var wm={};Dd(wm,{ACTIVITY_TYPE:()=>tr,CALENDAR_UNIT:()=>at,COLUMN:()=>P,CONSTRAINT_TYPE:()=>Y,CONSTRAINT_TYPE_TO_LABEL:()=>md,CREATION_KIND:()=>Ad,DEFAULT_HOURS_PER_DAY:()=>gd,DISPATCH_ACTION_KIND:()=>K,DISPATCH_ACTION_KINDS:()=>vd,DISPATCH_TRACK_EVENT:()=>mt,LINK_CODE_TO_TYPE:()=>Xt,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>us,NEW_ACTIVITY_DEFAULTS:()=>Nr,REJECTION_REASON:()=>E,ROOT_PARENT_ID:()=>F,ScheduleCore:()=>oi,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>hd,computeExpectedProgress:()=>Oi,expectedProgressFromBaseline:()=>Ie,getActiveBaseline:()=>it,getUnsavedActivities:()=>yd,isRootParent:()=>w,normalizeParentKey:()=>qt,parseFromBackend:()=>Qr,willRunCriticalPath:()=>pl,yieldToBrowser:()=>Z});var pt=class{items=[];head=0;enqueue(t){this.items.push(t)}dequeue(){if(this.head>=this.items.length)return;let t=this.items[this.head];return this.head+=1,t}peek(){if(!(this.head>=this.items.length))return this.items[this.head]}get size(){return this.items.length-this.head}isEmpty(){return this.head>=this.items.length}};var Ge=e=>String(e);function Un(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Ge(t),l=new Set([...i].map(String)),d=new Set(l),u=Pd(c,n).filter(s),f=u.filter(m=>!a(m)),h=r&&f.length<u.length;r&&!h?d.add(c):d.delete(c);for(let m of f)r?d.add(m):d.delete(m);return h||Ed({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Rd(l,d),parentBlocked:h}}function Pd(e,t){let r=[],i=new pt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let s of t.getChildrenIds(a)){let o=Ge(s);n.has(o)||(n.add(o),r.push(o),i.enqueue(o))}}return r}function Ed(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:s,next:o}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=Ge(c);if(a(l))return;let d=n.getChildrenIds(l).map(Ge).filter(s),u=d.some(a),f=d.filter(v=>!a(v)),m=f.length>0&&f.every(v=>o.has(v))&&!u;if(r){if(!i||!m||o.has(l))return;o.add(l)}else{if(m||!o.has(l))return;o.delete(l)}c=n.getParentId(l)}}function Rd(e,t){let r=[],i=[];for(let n of t)e.has(n)||r.push(n);for(let n of e)t.has(n)||i.push(n);return{checked:r,unchecked:i}}function se(e){return(e.pendingRequestIds?.length??0)>0}var E={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Bn=(e,t)=>{let r=e.getActivity(t);return r!=null&&se(r)},Hn=(e,t,r)=>{let i=[],n=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&i.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)n(a,!0);for(let a of r.unchecked)n(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function jn(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?o=>n.has(o):o=>Bn(r,o),s=Un({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:o=>r.getChildren(o),getParentId:o=>{let c=r.getParentId(o);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:o=>r.activityExists(o),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:Hn(e,r,s.changed)}}function Vn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!Bn(r,s))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(s=>!n.has(s)),unchecked:[...n].filter(s=>!i.has(s))};return{ok:!0,changes:Hn(e,r,a)}}function oe(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=String(n),s=t.has(a),o=e.isVisible(a);o!==s&&(e.setVisible(a,s),r.push({activityId:a,visible:{before:o,after:s}}))}),r}function Yn(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=oe(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var bd=["Waiting","Done","Doing","Overdue","Advancement"],Ld=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function ui(e,t){return e===null||t<=0?null:e/t}function wd(e,t){let r=t.getTime()-e.getTime();return Math.floor(r/864e5)+1}var Od={name:{valueKind:"string",extract:e=>e.name},description:{valueKind:"string",extract:e=>e.description},customId:{valueKind:"string",extract:e=>e.customId},correlativeId:{valueKind:"number",extract:e=>e.correlativeId},uniqueCorrelativeId:{valueKind:"number",extract:e=>Number(e.uniqueCorrelativeId)},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>ui(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>wd(e.startDate,e.endDate)},cost:{valueKind:"number",extract:e=>e.cost},usedCost:{valueKind:"number",extract:e=>e.usedCost},realCost:{valueKind:"number",extract:e=>e.realCost},workHours:{valueKind:"number",extract:e=>e.workHours},realWorkHours:{valueKind:"number",extract:e=>e.realWorkHours},ponderator:{valueKind:"number",extract:e=>e.ponderator},freeSlackDays:{valueKind:"number",extract:(e,t)=>ui(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>ui(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},expectedProgressBaseline:{valueKind:"number",extract:e=>e.expectedProgressBaseline},baselineDurationDays:{valueKind:"number",extract:e=>e.baselineSnapshot?.durationDays??null},baselineCost:{valueKind:"number",extract:e=>e.baselineSnapshot?.cost??null},baselineWorkHours:{valueKind:"number",extract:e=>e.baselineSnapshot?.workHours??null},startDate:{valueKind:"date",extract:e=>e.startDate},endDate:{valueKind:"date",extract:e=>e.endDate},constraintDate:{valueKind:"date",extract:e=>e.constraintDate},baselineStartDate:{valueKind:"date",extract:e=>e.baselineSnapshot?.startDate??null},baselineEndDate:{valueKind:"date",extract:e=>e.baselineSnapshot?.endDate??null},earlyStart:{valueKind:"date",extract:e=>e.criticalPath?.earlyStart??null},earlyFinish:{valueKind:"date",extract:e=>e.criticalPath?.earlyFinish??null},lateStart:{valueKind:"date",extract:e=>e.criticalPath?.lateStart??null},lateFinish:{valueKind:"date",extract:e=>e.criticalPath?.lateFinish??null},responsableIds:{valueKind:"id-array",extract:e=>e.responsableIds},tagIds:{valueKind:"id-array",extract:e=>e.tagIds},status:{valueKind:"enum",order:bd,extract:e=>e.status},constraintType:{valueKind:"enum",order:Ld,extract:e=>e.constraintType},calendarId:{valueKind:"reference",extract:e=>e.calendarId===null?null:String(e.calendarId)},subcontractId:{valueKind:"reference",extract:e=>e.subcontractId===null?null:String(e.subcontractId)},isCritical:{valueKind:"boolean",extract:e=>e.isCritical}};function xt(e){return Od[e]??null}function xd(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function Nd(e,t,r){let i=e===null;return r==="includes"?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r==="notIncludes"?i||!String(e).toLowerCase().includes(t.toLowerCase()):r==="is"?!i&&String(e)===t:r==="isNot"?i||String(e)!==t:!1}function Fd(e,t,r){return e===null||typeof e!="number"?r==="notEquals":r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="lessThan"?e<t:r==="greaterOrEqual"?e>=t:r==="lessOrEqual"?e<=t:!1}function Md(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function Wd(e,t,r){let n=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function Ud(e,t,r){let i=e!==null&&t.has(String(e));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function Kn(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function $n(e,t,r){let i=xt(t.field);if(i===null)return!1;let n=i.extract(e,r),{operator:a}=t;return i.valueKind==="string"?Nd(n,String(t.value),a):i.valueKind==="number"?Fd(n,Number(t.value),a):i.valueKind==="date"?Md(n,xd(t.value),a):i.valueKind==="id-array"?Wd(n,Kn(t.value),a):Ud(n,Kn(t.value),a)}function Bd(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(i=>$n(e,i,r)):t.criteria.every(i=>$n(e,i,r))}function Hd(e,t){let r=e.startDate.getTime(),i=e.endDate.getTime(),n=t.start.getTime(),a=t.end.getTime(),s=r>=n&&i<=a,o=r>=n&&r<=a,c=n>=r&&n<=i;return s||o||c}function jd(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function ze(e){let{activities:t,parentOf:r,filter:i,context:n}=e,a=i.dateRange,s=new Set,o=[];for(let c of t){let l=Bd(c,i,n),d=a===void 0||Hd(c,a);l&&d&&(s.add(String(c.id)),o.push(c.id))}for(let c of o)jd(c,r,s);return s}function ce(e){return{hoursPerDay:e,locale:"en"}}var Vd={string:new Set(["includes","notIncludes","is","isNot"]),number:new Set(["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]),date:new Set(["after","before"]),"id-array":new Set(["someOf","notSomeOf"]),enum:new Set(["someOf","notSomeOf"]),boolean:new Set(["someOf","notSomeOf"]),reference:new Set(["someOf","notSomeOf"])};function Gn(e){let t=xt(e.field);return t===null?"unknown_field":Vd[t.valueKind].has(e.operator)?Yd(e,t.valueKind):"unknown_operator"}function Yd(e,t){let{value:r}=e;return t==="id-array"||t==="enum"?Array.isArray(r)?null:"invalid_value":Array.isArray(r)?"invalid_value":t==="number"?Number.isFinite(Number(r))?null:"invalid_value":t==="date"?Kd(r)?null:"invalid_value":null}function Kd(e){return e instanceof Date?!0:typeof e=="string"||typeof e=="number"?!Number.isNaN(new Date(e).getTime()):!1}function zn(e){return e.criteria.length===0&&e.dateRange===void 0}function $d(e,t,r){let i=e.getAllActivities();return zn(t)?new Set(i.map(n=>String(n.id))):ze({activities:i,parentOf:n=>e.getParentId(n),filter:t,context:ce(r)})}function qn(e,t){let{adapter:r,hoursPerDay:i}=t;for(let c of e.criteria){let l=Gn(c);if(l!==null)return{ok:!1,reason:l}}let n=e.dateRange===void 0?{criteria:e.criteria,logic:e.logic}:{criteria:e.criteria,logic:e.logic,dateRange:e.dateRange};r.setActiveFilter(zn(n)?null:n);let a=$d(r,n,i),s=oe(r,a);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:s}}}var F="0";function w(e){return e==null||e===0||e==="0"}function qt(e){return w(e)?"0":String(e)}var fi=Number.MAX_SAFE_INTEGER;function lt(e,t){let r=hi(e,t),i=t.getOrderComparator?.()??null;return r.sort(i===null?qe:(n,a)=>i(n,a)||qe(n,a)),r.map(n=>String(n.id))}function Xn(e){let t=[],r=n=>{t.push(n);let a=lt(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=lt("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function Zn(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=Qn(i),a=lt(n,r),s=a.findIndex(o=>String(o)===String(e));if(s<=0)return null;for(let o=s-1;o>=0;o--){let c=a[o];if(c!==void 0&&!Gd(t,c))return c}return null}function pi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=Qn(r);return lt(i,t).findIndex(a=>String(a)===String(e))}function hi(e,t){if(String(e)==="0")return t.getAllActivities().filter(a=>a.parentId===null);let i=t.getChildren(e),n=[];for(let a of i){let s=t.getActivity(a);s&&n.push(s)}return n}function qe(e,t){let r=Jn(e),i=Jn(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Jn(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:fi}function Qn(e){let t=e.parentId;return t===null?"0":t}function Gd(e,t){return e.has(t)?!0:e.has(String(t))}function Je(e){let t=[],r=i=>{let n=lt(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let a of n)r(a)};return r("0"),t}function zd(e){return xt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function ta(e,t){let{adapter:r}=t;for(let a of e.rules){let s=zd(a);if(s!==null)return{ok:!1,reason:s}}let i=e.rules.length===0?null:{rules:e.rules};return r.setActiveOrder(i),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:Je(r)}}}var ea="text";var ra="description";var ia="duration";var na="progress";var aa="cost";var sa="used_cost";var oa="hhWorkTime";var ca="start_date";var la="end_date";var da="constraint_type";var ua="constraint_date";var fa="calendar_id";var pa="custom_id";var ha="subcontractId";var ya="responsables";var ma="tags";var ga="custom_predecessors";var va="custom_sucessors";var Aa="real_work";var Ca="real_cost";var Ia="expected_progress";var Sa="expected_progress_base";var ka="start_base";var Da="end_base";var Ta="duration_base";var _a="cost_base";var Pa="work_base";var Ea="calendarDuration";var Ra="is_critical",ba="earlyStart",La="earlyFinish",wa="lateStart",Oa="lateFinish",xa="freeSlack",Na="totalSlack";var Fa="correlative_id";var Ma="unique_correlative_id";var Wa="ponderator";var X={FUTURE:"future",PAST:"past"},at={HOUR:"hour",DAY:"day"},Nt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Xe="status";var yi="Baseline";function Ze(e){return e==="Actual"?"Actual":yi}var qd={TEXT:ea,DESCRIPTION:ra,DURATION:ia,PROGRESS:na,COST:aa,USED_COST:sa,HH_WORK_TIME:oa,START_DATE:ca,END_DATE:la,CONSTRAINT_TYPE:da,CONSTRAINT_DATE:ua,CALENDAR_ID:fa,CUSTOM_ID:pa,SUBCONTRACT_ID:ha,RESPONSABLES:ya,TAGS:ma,CUSTOM_PREDECESSORS:ga,CUSTOM_SUCESSORS:va},Jd={REAL_WORK:Aa,REAL_COST:Ca,EXPECTED_PROGRESS:Ia,EXPECTED_PROGRESS_BASE:Sa,START_BASE:ka,END_BASE:Da,DURATION_BASE:Ta,COST_BASE:_a,WORK_BASE:Pa,CALENDAR_DURATION:Ea,IS_CRITICAL:Ra,EARLY_START:ba,EARLY_FINISH:La,LATE_START:wa,LATE_FINISH:Oa,FREE_SLACK:xa,TOTAL_SLACK:Na,CORRELATIVE_ID:Fa,UNIQUE_CORRELATIVE_ID:Ma,PONDERATOR:Wa,STATUS:Xe},P={...qd,...Jd};function Ua(e,t){throw new Error(t)}function Ba(e,t){return()=>t()===e}var Y={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Xd={mso:()=>!0,mfo:()=>!0,snlt:(e,t)=>e<t,snet:(e,t)=>e>t,fnlt:(e,t)=>e<t,fnet:(e,t)=>e>t};function ja(e,t,r){if(!t)return{violated:!1};let i=Xd[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Zd=new Set(["mso","snet","snlt"]);function Re(e,t,r){return Zd.has(e)?t:r}function Va(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Qd={snet:{startOfDay:!0,direction:X.FUTURE},snlt:{startOfDay:!0,direction:X.PAST},fnet:{startOfDay:!1,direction:X.FUTURE},fnlt:{startOfDay:!1,direction:X.PAST},mso:{startOfDay:!0,direction:X.FUTURE},mfo:{startOfDay:!1,direction:X.PAST}},Qe=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Ha=(e,t)=>new Date(e.getTime()+t*864e5),tu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function mi(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Qd[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Qe(i),dir:X.FUTURE,task:e});if(tu(n,i))return i.getTime()!==Qe(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Ha(Qe(i),1),dir:X.PAST,task:e});let a=Qe(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:Ha(a,1),dir:X.PAST,task:e})}function Ya(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i==="asap"||i==="alap")return r;let n=mi(e,t);if(!n)return r;let a=o=>t.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e}),s=o=>t.calculateEndDate({startDate:o,durationHours:-e.durationHours,task:e});switch(i){case"snet":return{earliestStart:n,latestStart:null,earliestEnd:a(n),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:a(n)};case"fnet":return{earliestStart:s(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(n),earliestEnd:null,latestEnd:n};case"mso":{let o=a(n);return{earliestStart:n,latestStart:n,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(n);return{earliestStart:o,latestStart:o,earliestEnd:n,latestEnd:n}}default:return r}}function Ka(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function gi(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var W={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var tr={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},$a={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var vi=typeof window>"u",eu=!vi&&typeof MessageChannel<"u";function Z(){return eu?new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(null)}):Promise.resolve()}async function er(e,t){return performance.now()-e<$a.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Z(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function le(e){return vi||await Z(),e()?{aborted:!1}:{aborted:!0}}function rr(e,t){let{inDegree:r,successors:i}=ru(e,t),n=iu(r),a=nu(n,r,i),s=a.length<e.length,o=s?au(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function ru(e,t){let r=new Map,i=new Map;for(let n of e)r.set(n,0),i.set(n,[]);for(let n of t){let a=n.source,s=n.target;!r.has(a)||!r.has(s)||(i.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:i}}function iu(e){let t=new pt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function nu(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return i}function au(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var ir=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=rr(t,r),this.cached)}};function Ga(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Ai={project:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:"recursive-leaf-sum",promotesToProjectOnFirstChild:!1},task:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:"own-baseline",promotesToProjectOnFirstChild:!0},milestone:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:"zero",promotesToProjectOnFirstChild:!0}};function Ci(e){return e==="project"||e==="task"||e==="milestone"}function Pt(e,t){return t||Ci(e)&&Ai[e].alwaysSummary}function Jt(e){return e==="milestone"}function Ft(e){return Ci(e)&&Ai[e].promotesToProjectOnFirstChild}var Ii="project",de="task";function be(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function za(e,t){let r=t.getActivity(e);return r?Pt(r.type,t.getChildren(e).length>0):!1}function qa(e,t,r){let i=String(t),n=r.getActivity(e);for(;n?.parentId&&String(n.parentId)!=="0";){if(String(n.parentId)===i)return!0;n=r.getActivity(n.parentId)}return!1}function Za(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);if(a.length===0){String(n)!==String(e)&&r.push(n);continue}for(let s of a)i.push(s)}return r}function su(e){let t=new Map;for(let r of e)Ja(t,String(r.source),r),Ja(t,String(r.target),r);return t}function Ja(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function ou(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let s of e)cu(s,n,t,r,i)||a.push(s);return a.length>0?a:e}function cu(e,t,r,i,n){let a=String(e),s=r.getActivity(e);if(!s||s.autoScheduling===!1)return!1;let o=i.get(a)??[];for(let c of o)if(lu(c,a,s,t,r,n))return!0;return!1}function lu(e,t,r,i,n,a){if(du(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=uu(e,t);if(!i.has(String(o)))return!1;let c=n.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&fu(e,r,c))}function du(e){return e.source===e.target}function uu(e,t){return String(e.source)===t?e.target:e.source}function fu(e,t,r){let i=e.lag??0,n=Math.abs(i);return String(e.target)===String(r.id)&&n<=r.durationHours||String(e.target)===String(t.id)&&n<=t.durationHours}function Qa(e,t){let r=[],i=su(e),n=0;for(let a of e){let s=za(a.source,t),o=za(a.target,t);if(pu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Xa(a.source,s,t,i,!0),l=Xa(a.target,o,t,i,!1);n=Cu(r,c,l,a,t,n,i)}return r}function pu(e,t,r,i){return r&&qa(e.source,e.target,i)||t&&qa(e.target,e.source,i)}function Xa(e,t,r,i,n){return t?ou(Za(e,r),r,i,n):[e]}function hu(e,t,r){let i=Za(e,t);if(i.length===0)return null;let n=null,a=null;for(let s of i){let o=r(s);if(!o)continue;(n===null||o.startDate<n)&&(n=o.startDate),(a===null||o.endDate>a)&&(a=o.endDate)}return n===null||a===null?null:{startDate:n,endDate:a}}function nr(e,t){return hu(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function yu(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function mu(e,t,r,i){if(!t)return 0;let n=i.getActivity(e);return!r||!n?-t.durationHours:-i.calculateDuration({startDate:r.startDate,endDate:n.endDate,task:t})}function gu(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function vu(e,t,r,i,n){if(gu(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Au(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=nr(e.source,t),a=nr(e.target,t),s=e.type===W.START_TO_START||e.type===W.START_TO_FINISH,o=e.type===W.FINISH_TO_FINISH||e.type===W.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:a?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-yu(i,a,t):0,summarySourceId:e.type===W.START_TO_START&&n?e.source:void 0}}function Cu(e,t,r,i,n,a,s){let o=Au(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:h,summarySourceId:m}=o,v=a;for(let A of t){let k=f?mu(A,c,l,n):0;for(let D of r){if(String(A)===String(D))continue;let _=vu(D,d,c,n,s);e.push(Iu(i,A,D,v,k,h,u+_,m,_!==0&&h===0?i.target:void 0)),v+=1}}return v}function Iu(e,t,r,i,n,a,s,o,c){return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,_sourceLag:n,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var ar=class{invalidate(){}get(t,r){return Qa(t,r)}};function Su(e){let t=new Map,r=i=>(t.has(i)||t.set(i,new Set),t.get(i));for(let i of e)r(i.source).add(i.id),r(i.target).add(i.id);return{neighbors:t}}function ku(e,t,r){let i=new Set,n=new Map,a=new pt;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(i.has(o))continue;i.add(o);let c=r.neighbors.get(s);if(c)for(let l of c){let d=t.get(l);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;n.has(u)||n.set(u,d);let f=String(d.source)===o?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function ts(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=Su(t),n=ku(e,r,i),a=new Set([String(e)]);for(let s of n)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:n}}function es(e,t,r){let i=r.type===W.FINISH_TO_START,n=r.type===W.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:i,isFF:n,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case W.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case W.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case W.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case W.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1}}}function Du(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=nr(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function Tu(e,t,r,i,n){let a=t.durationHours===0&&n;return{successorStart:i.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function rs(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=es(e,t,r),l=Du(r,e,i)??n,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Tu(e,t,r,i,o||c);let h=o?t:e,m=i.getClosestWorkTime({date:e.endDate,dir:"future",task:h});if(l!==0&&(m=i.calculateEndDate({startDate:m,durationHours:l,task:e})),a!==0&&(m=i.calculateEndDate({startDate:m,durationHours:a,task:t})),s!==0&&(m=i.calculateEndDate({startDate:m,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:i.getClosestWorkTime({date:m,dir:"past",task:t}),link:r};let v=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:v,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}function is(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=es(t,e,r),o=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-a,task:e})),n!==0&&(o=i.calculateEndDate({startDate:o,durationHours:-n,task:t})),o}function ns(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===Y.ASAP||a===Y.ALAP)continue;let s=Ya(n,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function sr(e,t,r){let i={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},n=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;n===null?a=gi(e.startDate,i):Ka(n,i)?a=n:a=gi(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function as(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case Y.MSO:case Y.MFO:return new Date(i);case Y.SNET:case Y.FNET:return i>t?new Date(i):t;case Y.SNLT:case Y.FNLT:return i<t?new Date(i):t;default:return t}}function _u(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function ss(e,t,r){return Si(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Si(e,t,r){return t.dragWithMultiple&&_u(e,r)}async function cs(e,t,r,i,n,a){let s=new Map;for(let u of t){let f=String(u.target);s.has(f)||s.set(f,[]),s.get(f).push(u)}let o=u=>{let f=a.get(u);if(f?.startDate&&f.endDate)return{startDate:f.startDate,endDate:f.endDate};let h=r.getActivity(u);return h?{startDate:h.startDate,endDate:h.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let f=await er(d,n);if(f.aborted)return a;d=f.newSliceStart;let h=r.getActivity(u);if(!h||!h.autoScheduling||h.progress===100||Pu(h,r))continue;let m=s.get(String(u))??[],v=null,A=null,k=!1;for(let C of m){let T=r.getActivity(C.source);if(!T)continue;let S=o(C.source),R=S.startDate.getTime()!==T.startDate.getTime()||S.endDate.getTime()!==T.endDate.getTime(),x={...T,startDate:S.startDate,endDate:S.endDate},L=ss(x,c,l),V={...x,startDate:L.startDate,endDate:L.endDate},G=Si(C.source,c,l)?{...C,lag:0}:C,vt=rs(V,h,G,r);(!v||vt.successorStart>v)&&(v=vt.successorStart,A=String(C.id),k=C._summaryTargetId!==void 0&&!R)}v!==null&&k&&v<h.startDate&&(v=new Date(h.startDate));let _=a.get(u),p=_?{..._}:{activityId:u,startDate:h.startDate,endDate:h.endDate,drivingLinkId:null,kind:"asap",conflict:!1},g=p.earliestStart||p.latestStart||p.earliestEnd||p.latestEnd;if(!(!v&&!g)){if(v){let C=v;h.type===tr.MILESTONE&&(C=as(h,v)),p.drivingLinkId=A,p.startDate=C,p.endDate=r.calculateEndDate({startDate:C,durationHours:h.durationHours,task:h}),p.earliestSchedulingStart=C,p.earliestSchedulingEnd=p.endDate}else h.constraintType===Y.MSO?p.earliestStart&&(p.startDate=p.earliestStart,p.endDate=p.earliestEnd??r.calculateEndDate({startDate:p.earliestStart,durationHours:h.durationHours,task:h})):h.constraintType===Y.MFO&&p.latestStart&&(p.startDate=p.latestStart,p.endDate=p.latestEnd??r.calculateEndDate({startDate:p.latestStart,durationHours:h.durationHours,task:h}));sr(h,p,r),a.set(u,p)}}return a}function Pu(e,t){return Pt(e.type,t.getChildren(e.id).length>0)}async function ls(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let A of o)A.constraintType===Y.ALAP&&l.push(A.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let A of t){let k=String(A.source);d.has(k)||d.set(k,[]),d.get(k).push(A);let D=String(A.target);u.has(D)||u.set(D,[]),u.get(D).push(A)}let f=A=>{let k=s.get(A);if(k)return{startDate:k.startDate,endDate:k.endDate};let D=i.getActivity(A);return D?{startDate:D.startDate,endDate:D.endDate}:{startDate:new Date,endDate:new Date}},h=A=>!A.parentId||w(A.parentId)?i.getProjectEnd():f(A.parentId).endDate,m=(A,k)=>{let D=A,_=0;for(;D&&!w(D)&&_++<c+1;){if(String(D)===String(k))return!0;let p=i.getActivity(D);if(!p||!p.parentId)break;D=p.parentId}return!1},v=performance.now();for(let A of e){let k=await er(v,a);if(k.aborted)return s;v=k.newSliceStart;let D=i.getActivity(A);if(!D||D.constraintType!==Y.ALAP||!D.autoScheduling||D.progress===100||Pt(D.type,i.getChildren(A).length>0))continue;let _=h(D);if(!_)continue;let p=_,g=null,C=!1,T=d.get(String(A))??[];for(let Ct of T){if((Ct.lag??0)<0)continue;let ae=i.getActivity(Ct.target);if(!ae||ae.autoScheduling===!1)continue;let Wn=f(Ct.target),Cd={...ae,startDate:Wn.startDate,endDate:Wn.endDate},$e=is(Cd,D,Ct,i);$e<p&&(p=$e),(g===null||$e<g)&&(g=$e,C=D.parentId&&!w(D.parentId)?m(Ct.target,D.parentId):!1)}if(g!==null)if(C)p=g;else{let Ct=f(A).endDate,ae=Ct.getTime()>_.getTime()?Ct:_;p=g<ae?g:ae}else p>_&&(p=_);let R=(u.get(String(A))??[]).some(Ct=>Ct.type===W.FINISH_TO_START||Ct.type===W.FINISH_TO_FINISH),x=new Date(Date.UTC(p.getUTCFullYear(),p.getUTCMonth(),p.getUTCDate())),L=()=>i.getClosestWorkTime({date:x,dir:"past",task:D}),V=i.getClosestWorkTime({date:p,dir:"future",task:D}).getTime()===p.getTime(),G;D.durationHours===0&&g===null?G=R&&V?L():i.getClosestWorkTime({date:p,dir:"past",task:D}):D.durationHours===0?R?G=L():G=i.getClosestWorkTime({date:p,dir:"future",task:D}):G=i.getClosestWorkTime({date:p,dir:"future",task:D});let vt=i.calculateEndDate({startDate:G,durationHours:-D.durationHours,task:D}),Ee=s.get(A),At=Ee?{...Ee}:{activityId:A,startDate:vt,endDate:G,drivingLinkId:null,kind:"alap",conflict:!1};At.startDate=vt,At.endDate=G,At.drivingLinkId=null,At.kind="alap";let ci=At.earliestSchedulingStart??null;At.earliestSchedulingStart=null,At.earliestSchedulingEnd=null;let li=ci!==null&&ci.getTime()>vt.getTime()?ci:vt;At.latestSchedulingStart=li,At.latestSchedulingEnd=li===vt?G:i.calculateEndDate({startDate:li,durationHours:D.durationHours,task:D}),sr(D,At,i),s.set(A,At)}return s}var ue={warn(){},error(){}};function Le(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let i=t.plans.get(r);if(!i)continue;let n=e.getLiveActivity(r);n&&(n.startDate=i.startDate,n.endDate=i.endDate,e.updateActivity(r))}})}function ds(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=n.get(s)??[];c.push(o),n.set(s,c)}return Eu(n,i,r)}function Eu(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new pt;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;i.has(o)||(i.add(o),n.enqueue(o))}}return!1}function Mt(e,t){switch(e.kind){case"create":return Ru(e,t);case"update":return bu(e,t);case"delete":return Lu(e,t)}}function Ru(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:"activity-missing"};let a=r.getAllLinks();for(let l of a)if(String(l.source)===String(e.source)&&String(l.target)===String(e.target)&&l.type===e.type)return{applied:!1,rejected:"duplicate",linkId:l.id};let s=a.map(l=>({source:l.source,target:l.target}));if(ds(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??wu)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function bu(e,t){let{port:r}=t;return r.getLink(e.linkId)?(e.lag!==void 0&&r.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&r.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function Lu(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}var or=null;function wu(){return or===null&&(or=Date.now()),or+=1,String(or)}var us={[W.FINISH_TO_START]:"fs",[W.START_TO_START]:"ss",[W.FINISH_TO_FINISH]:"ff",[W.START_TO_FINISH]:"sf"},Xt={fs:W.FINISH_TO_START,ss:W.START_TO_START,ff:W.FINISH_TO_FINISH,sf:W.START_TO_FINISH},fs="fs";function ps(e){if(e in Xt)return Xt[e]}var hs=";",ys=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function cr(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(hs)){if(n.length===0)continue;let a=Ou(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function Ou(e){let t=e.toLowerCase(),r=ys.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?Xt[n]:Xt[fs],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:o,lag:c}}function dr(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=lr(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.target)===String(t)&&s.set(lr(c.source,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function lr(e,t){return`${String(e)}::${t}`}function ur(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],a=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=lr(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let s=new Map;for(let c of r)String(c.source)===String(t)&&s.set(lr(c.target,c.type),c);let o=[];for(let[c,l]of s)a.has(c)||o.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=s.get(c);d&&d.lag!==l.lag&&o.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)s.has(c)||o.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:o,unresolved:n}}function ht(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var ms={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:X.FUTURE,date:e,unit:at.HOUR}):t.isWorkTime(e,at.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function ki(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var Di=ms;var fr=class{adapter;reporter;currentCalculationId=0;topoCache=new ir;expandedLinksCache=new ar;constructor(t,r=ue){this.adapter=t,this.reporter=r}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(t={}){let r=++this.currentCalculationId,i=Ba(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Mu(this.adapter);let a=Wt("schedule.total"),s=Wt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Et(s);let l=c;if((await le(i)).aborted)return{...n,cancelled:!0};let d=Wt("schedule.scoping"),u=this.adapter.getAllIds(),f=Wu(t,l,this.adapter),h=f.links,m=f.idSet;Et(d);let v=Wt("schedule.topologicalSort"),A=Bu(this.topoCache,u,l,m);if(Et(v),A.hasCycles)return Et(a),{...n,cycles:[A.cycleNodes]};if((await le(i)).aborted)return{...n,cancelled:!0};let k=Wt("schedule.processConstraints"),D=new Map;if(ns(A.ordered,this.adapter,D),Et(k),(await le(i)).aborted)return{...n,cancelled:!0};let _=Wt("schedule.asapPass"),p=await cs(A.ordered,h,this.adapter,t,i,D);if(Et(_),(await le(i)).aborted)return{...n,cancelled:!0};let g=Wt("schedule.alapPass"),C=await ls(A.reversed,h,p,this.adapter,t,i);if(Et(g),(await le(i)).aborted)return{...n,cancelled:!0};let T=Wt("schedule.diff"),S=[];for(let[R,x]of C){let L=this.adapter.getActivity(R);if(!L)continue;let V=L.startDate.getTime()!==x.startDate.getTime(),G=L.endDate.getTime()!==x.endDate.getTime();(V||G)&&S.push(R)}return Et(T),Et(a),{plans:C,updatedIds:S,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},Nu=!1;function Fu(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Nu}function Wt(e){return{name:e,startedAt:performance.now()}}function Mu(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Et(e){if(!Fu())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Wu(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=ts(i,t);return Uu(n,t,r)}function Uu(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let s of r.getAllActivities()){let o=String(s.id);s.constraintType===Y.ALAP&&!i.has(o)&&(n.add(o),i.add(o))}if(n.size===0)return{idSet:i,links:e.links};let a=[...e.links];for(let s of t)(n.has(String(s.source))||n.has(String(s.target)))&&a.push(s);return{idSet:i,links:a}}function Bu(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let s=i?Array.from(i):t;return rr(s,r)}if(!i)return n;let a=Ga(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function gs(e,t,r){let i=t.getActivity(e);if(!i)return;let n=r?{...i,endDate:r.endDate}:i,a=t.calendarReader.getCalendar(String(i.calendarId));for(let s of t.getIncomingLinkIds(e)){let o=t.getLink(s);if(!o)continue;let c=t.getActivity(o.source);if(!c||c.constraintType==="alap"||Jt(i.type)&&(o.type===W.START_TO_FINISH||o.type===W.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ki(c,n,o.type),f=Di.computeLagBetweenTasks(d,u,a);f!==o.lag&&Mt({kind:"update",linkId:o.id,lag:f},{port:t})}}function vs(e,t){let r=t.getActivity(e);r&&Jt(r.type)&&(r.durationHours=0)}function fe(e){let t=0,r=!1;for(let i of e)i.ponderator>0&&(t+=i.ponderator/100*i.progress,r=!0);return r?t:null}function pr(e){return Number(e.toFixed(2))}function dt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function pe(e,t,r=!0,i={}){let n=t?ju(e,t):$u(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await Hu(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function hr(e,t){As(e,t,"skip")}async function Hu(e,t,r,i={recomputeRealWork:!1}){let a=0;for(let s of e)As(s,t,r,i.recomputeRealWork),a+=1,a%200===0&&await Z()}function ju(e,t){let r=new Set;for(let a of t)Vu(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Cs(i,e);return Is(i,n)}function Vu(e,t,r){let i=t.getParentId(e);for(;i&&!w(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function Yu(e,t,r){let i=null,n=null,a=0,s=[];for(let o of e){let c=t.getActivity(o);if(!c)continue;let l=c.startDate.getTime(),d=c.endDate.getTime();(i===null||l<i)&&(i=l),(n===null||d>n)&&(n=d),r&&(a+=Ku(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:s}}function As(e,t,r="freeze-when-no-contribution",i=!1){let n=t.getActivity(e);if(!n)return;let a=t.getChildren(e);if(a.length===0)return;let s=Yu(a,t,i);if(s.minStart===null||s.maxEnd===null)return;let o=String(n.calendarId??""),c=t.calendarReader.getCalendar(o),l=new Date(s.minStart),d=new Date(s.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u);let f=fe(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",pr(f??0)),i&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Ku(e,t){return t?Number(e.realWorkHours)||0:dt(e.workHours,e.progress)}function $u(e){let t=Gu(e),r=Cs(t,e);return Is(t,r)}function Gu(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Cs(e,t){let r=new Map;for(let i of e)r.set(i,zu(i,t));return r}function zu(e,t){let r=0,i=e;for(;i&&!w(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Is(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ss={updateActivityDuration:vs,updateTaskTiming:Ju("updateTaskTiming"),adjustLinkLagOnTaskMove:gs,recordLastStartDate:qu};function qu(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Ut(e,t,r,i){for(let n of t){let a=n in Ss?Ss[n]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${n} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,i??null)}}function Ju(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function O(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function N(e){return{ok:!1,reason:e}}function U(){return{valid:!0}}function Q(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function B(){return{allowed:!0}}function z(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function M(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var ks={targetField:"name",canEdit(){return B()},parseInput(e){return typeof e!="string"?N("not_a_string"):O(e)},validate(){return U()},transform(e,t){return M({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var Ds={targetField:"description",canEdit(){return B()},parseInput(e){return typeof e!="string"?N("not_a_string"):O(e.trim())},validate(){return U()},transform(e,t){return M({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function It(e){return e.constraintType??Y.ASAP}var yr=100;function he(e){return e.progress>=yr}function rt(e,t){return Pt(e.type,t.hasChildren(e.id))}function Ts(e){return e.progress>0}function _s(e){return e.hasLookaheadTasks}function we(e,t){return Math.round(Math.ceil(e*t*60)/60)}var ye=e=>({endDate:e});function Zt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=n=>Number(r.find(a=>a.type===n)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Oe(e,t){if(!t||t==="UTC"){let f=new Date(e);return f.setUTCHours(23,59,0,0),f}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=f=>Number(r.find(h=>h.type===f)?.value),n=i("year"),a=i("month"),s=i("day"),o=Date.UTC(n,a-1,s,23,59,0,0),c=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(o)),l=f=>Number(c.find(h=>h.type===f)?.value),u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")===24?0:l("hour"),l("minute"),l("second"))-o;return new Date(o-u)}function Xu(e,t){let r=Zt(t);for(;!e.isWorkTime(r,at.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Zt(r);return r}function Ti(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:at.HOUR})}function _i(e,t){let r=Xu(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:X.PAST,date:i,unit:at.HOUR})}var mr=new Set(["snet","snlt","mso"]),Pi=new Set(["fnet","fnlt","mfo"]),Bt=new Set(["asap","alap"]),gr="snet";function Rt(e,t,r){if(!mr.has(r)&&!Pi.has(r))return e;let i=mr.has(r)?Ti(t,e):_i(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var bt=()=>({constraintType:gr});var Ht=e=>({constraintDate:e}),Ps=e=>({constraintDate:e});var Es={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Rs={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id",UNKNOWN_CALENDAR:"unknown_calendar"};function me(e,t,r){return ja(e,t,r)}function ge(e,t,r){return Va(e,t,r)}var Ls={targetField:"durationHours",canEdit(e,t){return he(e)?z("completed","cant_edit_completed_activity"):rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?N("not_a_number"):O(r.inputUnit==="hours"?i:we(i,r.hoursPerDay))},validate(e,t,r){return bs(r)?Q(Rs.NEGATIVE_DURATION):Zu(t,r)?Q("unchanged"):U()},transform(e,t,r){if(bs(t))return M({},{autoSchedule:!1,postProcessors:[]});let i=Qu(e,t,r),n=tf(e,t,r,i.violated);return{...M(n,{autoSchedule:!0,postProcessors:[Es.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ge(i.constraintType,i.constraintDate,ws(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function bs(e){return Math.sign(e)===-1}function Zu(e,t){return e===t}function Qu(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!=="fnet"&&n!=="fnlt"&&n!=="mfo")return{violated:!1};let a=i.calculateEndDate(e.startDate,t);return me(n,e.constraintDate,a)}function tf(e,t,r,i=!1){let n={};i&&Object.assign(n,bt(),Ht(e.startDate));let a=be(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=ws(e,t,r);return s&&Object.assign(n,ye(s)),n}function ws(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ve=e=>({realWorkHours:e});var ef=0,rf=yr,Os=0,xs={targetField:"progress",canEdit(e,t){return _s(e)?z("has_lookahead_tasks","cant_edit_actvity_with_task"):rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):O(t)},validate(e,t,r){return nf(r)?Q("out_of_range"):U()},transform(e,t,r){let i=af(t),n=sf(t),a=lf(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ve(a.get(e.id)??0)},o=n?of(e,t,i,r.hierarchy,a):[],c=n?uf(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?pf(e,t):void 0;return M(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function nf(e){return e<ef||e>rf}function af(e){return e===Os}function sf(e){return e===yr||e===Os}function of(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:cf(t,r,n.get(s)??0)}))}function cf(e,t,r){return{progress:e,autoScheduling:t,...ve(r)}}function lf(e,t,r){let i=new Map,n=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?n(c.id):dt(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):dt(e.workHours,t);return i.set(e.id,a),i}function df(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=a=>t.getChildProgressInfo(a).some(s=>t.hasChildren(s.id)),n=a=>t.getAncestorIds(a).length;return r.filter(a=>i(String(a))).map(String).sort((a,s)=>n(s)-n(a))}function uf(e,t,r){let i=new Map;i.set(e.id,t);for(let s of r.getDescendantIds(e.id))i.set(s,t);let n=[...df(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of n){let o=ff(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function ff(e,t,r){let i=r.getChildProgressInfo(e).map(n=>({progress:t.has(n.id)?t.get(n.id):n.progress,ponderator:n.ponderator??0}));return Number((fe(i)??0).toFixed(2))}function pf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Ns={targetField:"cost",canEdit(e,t){return rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e,t){if(String(e).trim()==="")return O(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):O(r)},validate(){return U()},transform(e,t,r){let i=hf(e,t,r.hierarchy);return M({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function hf(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.cost;i.set(a,s),n.push({activityId:a,fields:{cost:s}})}return n}var Fs={targetField:"usedCost",canEdit(e,t){return rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e,t){if(String(e).trim()==="")return O(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):O(r)},validate(){return U()},transform(e,t,r){let i=yf(e,t,r.hierarchy);return M({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function yf(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=i.has(o.id)?i.get(o.id):o.usedCost;i.set(a,s),n.push({activityId:a,fields:{usedCost:s}})}return n}var Ms={targetField:"workHours",canEdit(e,t){return rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e){if(String(e).trim()==="")return O(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):O(t)},validate(){return U()},transform(e,t,r,i){let n=Ws(t,e.progress),a=String(i).trim()===""?[]:mf(e,t,n,r.hierarchy);return M({workHours:t,...ve(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Ws(e,t){return dt(e,t)}function mf(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let s=[];for(let o of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(o)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??Ws(d.workHours,d.progress);c+=u,l+=f}n.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...ve(l)}})}return s}function vr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Ei(e,t){return e.getTime()<t.getTime()}function Ae(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Ar=e=>({durationHours:e});var Us={targetField:"startDate",canEdit(e,t){return rt(e,t)?z("summary","summary_column_value"):Ts(e)?z("has_progress","cant_edit_activity_with_progress"):B()},parseInput(e,t,r){return Ae(e)?O(Zt(e,"UTC")):N("invalid_date")},validate(e,t,r,i){if(vr(t,r))return Q("unchanged");let n=gf(e,r,i);return n||U()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return M({startDate:t,...bt(),...Ht(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=Ti(i,t),a=e.type==="milestone",s=a?n:i.calculateEndDate(n,e.durationHours),o=n;return{...M({startDate:n,...ye(s),...a?Ar(0):{},...bt(),...Ht(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:vf(e,n,i)}},trackEvent:"activity_start_date_entry"};function gf(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=Zt(i);return t.getTime()<n.getTime()?Q("before_parent_start"):null}function vf(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=Re(It(e),t,i),a=me(It(e),e.constraintDate,n);if(a.violated)return ge(a.constraintType,a.constraintDate,n)}var Af=99.999,Hs={targetField:"endDate",canEdit(e,t){return rt(e,t)?z("summary","summary_column_value"):Cf(e)?z("completed","cant_edit_completed_activity"):B()},parseInput(e,t,r){if(!Ae(e))return N("invalid_date");let i=Zt(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,at.DAY)?O(_i(n,i)):r.dateFormat.split(" ").length>1?O(i):O(n.getClosestWorkTime({direction:"past",date:i,unit:at.HOUR})):O(i)},validate(e,t,r,i){if(vr(e.endDate,r))return Q("unchanged");if(If(r,e))return Q("before_date_origin");if(Sf(r,e))return Q("before_start_date");let n=kf(r,e,i);return n||U()},transform(e,t,r){let i=Df(e,t),n=Tf(e,t,r,!!i);return{...M(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function Cf(e){return e.progress>=Af}function If(e,t){return t.dateOrigin?Ei(e,t.dateOrigin):!1}function Sf(e,t){return Ei(e,t.startDate)}function kf(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,at.DAY)?null:Q("not_working_day"):null}function Df(e,t){if(It(e)===Y.MSO)return;let i=Re(It(e),e.startDate,t),n=me(It(e),e.constraintDate,i);if(n.violated)return ge(n.constraintType,n.constraintDate,i)}function Tf(e,t,r,i=!1){let n={};Jt(e.type)&&!i&&Bs(e)?Object.assign(n,Ht(e.startDate)):(i||Bs(e))&&Object.assign(n,bt(),Ht(e.startDate));let o=_f(e,t,r),c=be(e.durationHours,o);return c&&(n.type=c),Object.assign(n,Ar(o)),n.endDate=t,n}function Bs(e){return Bt.has(It(e))}function _f(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Pf=new Set(Object.values(Y)),js={targetField:"constraintType",canEdit(e,t){return he(e)?z("completed","cant_edit_completed_activity"):rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e){let t=String(e).toLowerCase();return Ef(t)?O(t):N("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let i=Rf(e,t,r);return M(i,{autoSchedule:!0})}};function Ef(e){return Pf.has(e)}function Rf(e,t,r){let i=Lf(e,t);return{constraintType:t,...Ps(bf(e,t,i,r))}}function bf(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?Rt(r,n,t):r}function Lf(e,t){return Bt.has(t)?null:mr.has(t)?e.startDate:Pi.has(t)?e.endDate:e.constraintDate}var Vs={targetField:"constraintDate",canEdit(e,t){return he(e)?z("completed","cant_edit_completed_activity"):rt(e,t)?z("summary","summary_column_value"):B()},parseInput(e){return Ae(e)?O(e):N("invalid_date")},validate(){return U()},transform(e,t,r){let i=Ys(e)?gr:It(e),n=r.calendars.getCalendar(e.calendarId),a=n?Rt(t,n,i):t,s=wf(e,a);return M(s,{autoSchedule:!0})}};function wf(e,t){return{constraintDate:t,...Ys(e)?bt():{}}}function Ys(e){return Bt.has(It(e))||!e.constraintType}var Ks={targetField:"calendarId",canEdit(){return B()},parseInput(e){let t=String(e).trim();return Of(t)?N("empty_calendar"):O(t)},validate(e,t,r,i){return xf(e.calendarId,r)?Q("unchanged"):i.calendars.getCalendar(r)?U():Q("unknown_calendar")},transform(e,t,r){return M(Nf(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Of(e){return e===""}function xf(e,t){return e===t}function Nf(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Ff(e.startDate):e.startDate,o=n.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=o),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,ye(n.calculateEndDate(c,e.durationHours)))}return i}function Ff(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var $s={targetField:"customId",canEdit(){return B()},parseInput(e){if(e==null)return N("empty_custom_id");if(typeof e!="string")return N("not_a_string");let t=e.trim();return t.length===0?N("empty_custom_id"):t.length>20?N("exceeds_max_length"):O(t)},validate(){return U()},transform(e,t){return M({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var Gs={targetField:"subcontractId",canEdit(){return B()},parseInput(e){if(e==null)return O(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return O(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?N("not_an_integer"):O(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?N("not_an_integer"):O(e):N("not_an_integer")},validate(){return U()},transform(e,t){return M({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function xe(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function Cr(e){return e.some(t=>xe(t)===null)}var zs={targetField:"responsableIds",canEdit(){return B()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):N("not_an_array")},validate(e,t,r){return Cr(r)?Q("missing_id"):U()},transform(e,t){let r=t.map(xe).filter(i=>i!==null);return M({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var qs={targetField:"tagIds",canEdit(){return B()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):N("not_an_array")},validate(e,t,r){return Cr(r)?Q("missing_id"):U()},transform(e,t){let r=t.map(xe).filter(i=>i!==null);return M({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Mf=new Map([[P.TEXT,ks],[P.DESCRIPTION,Ds],[P.DURATION,Ls],[P.PROGRESS,xs],[P.COST,Ns],[P.USED_COST,Fs],[P.HH_WORK_TIME,Ms],[P.START_DATE,Us],[P.END_DATE,Hs],[P.CONSTRAINT_TYPE,js],[P.CONSTRAINT_DATE,Vs],[P.CALENDAR_ID,Ks],[P.CUSTOM_ID,$s],[P.SUBCONTRACT_ID,Gs],[P.RESPONSABLES,zs],[P.TAGS,qs]]);function jt(e){return Mf.get(e)}function Ce(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:"constraint_violation",activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var b={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Ri={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var Wf=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Js=new Set(Wf);function tt(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Xs(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function te(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Tt(e.constraintDate),dateOrigin:Tt(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Tt(t.startDate),endDate:Tt(t.endDate)})),baselineSnapshot:Uf(e.baselineSnapshot),criticalPath:Bf(e.criticalPath)}}function Tt(e){return e===null?null:new Date(e)}function Uf(e){return e===null?null:{...e,startDate:Tt(e.startDate),endDate:Tt(e.endDate)}}function Bf(e){return e===null?null:{...e,earlyStart:Tt(e.earlyStart),earlyFinish:Tt(e.earlyFinish),lateStart:Tt(e.lateStart),lateFinish:Tt(e.lateFinish)}}function et(e){return structuredClone(e)}var to=200;function Vt(e,t){let r=new Set([String(e)]);for(let i of t.cascadeMutations??[])r.add(String(i.activityId));return r}async function q(e,t){let r=new Map,i=0;for(let n of t){i+=1,i%to===0&&await Z();let a=e.getActivity(n);a&&r.set(n,J(a))}return r}function J(e){return te(e)}function Ir(e,t){let r=e.getActivity(t);return r?te(r):null}function Yt(e,t,r){Zs(e,t,r.patch);for(let i of r.cascadeMutations??[])Zs(e,i.activityId,i.fields)}function Zs(e,t,r){for(let[i,n]of Object.entries(r)){if(!Js.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);tt(e,t,i,n)}}async function eo(e,t,r,i){let n=[],a=0;for(let s of r){a+=1,a%to===0&&await Z();let o=Hf(e,t,s,i);o&&n.push(o)}return n}function Hf(e,t,r,i){let n=e.getActivity(r);if(!n)return{id:r,kind:"deleted",after:null};let a=t.get(r);if(!a&&i?.has(r))return jf(r,i.get(r),n);let s=Li(a,n);return Vf(s,i,r,n),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(n)}}function jf(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function Vf(e,t,r,i){if(!t?.has(r)||Object.hasOwn(e,"correlativeId"))return;let n=t.get(r);n!==i.correlativeId&&(e.correlativeId={before:n,after:i.correlativeId})}function Li(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);for(let s of a)(Object.hasOwn(i,s)!==Object.hasOwn(n,s)||!bi(i[s],n[s]))&&(r[s]={before:Qs(i[s]),after:Qs(n[s])});return r}function Qs(e){return e===null||typeof e!="object"?e:et(e)}function bi(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,o)=>bi(s,t[o]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,i=t,n=Object.keys(r),a=Object.keys(i);return n.length!==a.length?!1:n.every(s=>Object.hasOwn(i,s)&&bi(r[s],i[s]))}function Sr(e,t,r){let i=new Set;i.add(e);for(let n of t)i.add(n);for(let n of r)i.add(n);return i}function wi(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function kr(e,t,r,i,n){for(let a of t){if(r.has(a.activityId)||(n.add(a.activityId),i.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=J(s);a.before!==void 0&&(o.correlativeId=a.before),i.set(a.activityId,o)}}var Yf=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Lt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(Yf);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,s]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(s)))}function Ie(e,t,r,i){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let n=i.calculateDuration(e,r),a=i.calculateDuration(e,t);return a===0?0:n*100/a}var Kf=e=>e.type==="project",$f=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=s=>s instanceof Date?s:Lt(String(s));return Ie(a(e.startDate),a(e.endDate),t,n)};function Gf(e,t,r){let i=[],n=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),i.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!Kf(o)){let d=$f(o,t,r);return n(s,d),d}let c=0;for(let d of r.getChildren(s)){let u=a(d),f=r.getActivity(d),h=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*h}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}function wt(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Gf(r,t,e)}function it(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var zf=e=>e.type==="project",qf=e=>it(e),Jf=(e,t,r,i)=>{let n=qf(e);if(!n)return 0;let a=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!a||!n.startDate||!n.endDate?0:Ie(n.startDate,n.endDate,t,a)};function Oi(e,t,r,i=null){let n=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),n.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!zf(c)){let u=Jf(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),h=r.getActivity(u),m=typeof h?.ponderator=="number"?h.ponderator:0;l+=f*m}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function Kt(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>tt(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),Oi(n,t,i,r)}var ro=e=>Math.round(e*100)/100;function Xf(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Zf(e,t){let r=ro(e),i=ro(t);return r>99.99?Nt.DONE:i>r?Nt.OVERDUE:e>0&&r>i?Nt.ADVANCEMENT:e===0&&t===0?Nt.WAITING:e>0&&r<i?Nt.DOING:Nt.WAITING}function St(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=Zf(a,Xf(i,t));i.status!==s&&(tt(e,n,Xe,s),r.push(n))}),r}function xi(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(n,a)=>s=>s===void 0?t[n]():(t[a](s),i),i={__isMomentShim:!0,clone:()=>xi(t),hours:r("getUTCHours","setUTCHours"),minutes:r("getUTCMinutes","setUTCMinutes"),seconds:r("getUTCSeconds","setUTCSeconds"),milliseconds:r("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>t.getTime(),toDate:()=>new Date(t.getTime()),getTime:()=>t.getTime()};return i}xi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var yt=xi;function Qf(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Dr(e){return Qf(e)&&!isNaN(e.getTime())}function I(e,t,r,i){if(!Dr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(i)}`);let n=t;return e.calculateEndDate({start_date:new Date(n),duration:r,unit:"hour",task:i})}function ut(e){if(!Dr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:i,activity:n}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:i,unit:"hour",task:n})}var tp=e=>e?e.$level===1:!1,ep=e=>e.type==="project",rp=e=>e.$level!==0,ip=e=>e.type==="task",np=e=>e.type==="task"||e.type==="milestone",st={byFirstLevel:tp,filterByParentType:ep,avoidSubproject:rp,byTaskType:ip,byTaskTypeAndMilestone:np};var y=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var H=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function ee(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function io(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=ap({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=sp({gantt:t,subprojectsWithNoLinks:a}),o=op({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:cp,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function ap(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(st.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function sp(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(o=>{let c=t.getTask(o),l=st.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function op(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function cp(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[i]);n.push(o)}return n}function no({gantt:e,linkProperty:t,direction:r}){try{let i=lp(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return dp(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function lp(e,t){return e.getTaskByTime().filter(st.avoidSubproject).filter(st.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function dp(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?n.add(a.id):o.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function ao({gantt:e,direction:t,linkProperty:r}){try{let i=up(e),n=new Set,a=new Set,s=new Set;t==="backward"&&hp(i).forEach(d=>{n.add(d.id)});let o=fp(i,t,r),c=pp(i,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(i){throw i}}function up(e){return e.getTaskByTime().filter(st.filterByParentType).filter(st.avoidSubproject)}function fp(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,s=i.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function pp(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function hp(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function so({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=yp(r),o=mp(r),c=a[s];if(!Array.isArray(c))return;gp(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function yp(e){return e==="forward"?"$source":"$target"}function mp(e){return e==="forward"?"target":"source"}function gp(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Ne={identifySecondLevelActivities:io,identifyInitialActivities:no,identifyParentsWithAndWithoutLinks:ao,identifyForbiddenActivities:so};function Tr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Ni({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===H.FS&&t===0?ut({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Fe(r,e,i,n)}function oo({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:I(r,n,e,i),ef:n}}function co({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=I(r,n,e,i);return{es:n,ef:a}}function Fe(e,t,r,i){if(![H.FS,H.SS,H.FF].includes(t))return e;let a=[H.FS,H.SS].includes(t)?"future":"past";return ut({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Fi=class{constructor(t,r,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Tr(t),i=this.activity.constraint_type;return i==="snet"?this.handleSNETConstraint(r):i==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=ee(i),a=r.linkLag,s=r.es,o=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=co({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t&&t.ef>r.ef?t:r}handleFNLTConstraint(t){let r=oo({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return t?t.ef>r.ef?r:t:r}calculateSSLink({lag:t,predecessorEs:r}){let i=Ni({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity);t>0&&(n=Fe(n,"ss",this.activityCalendar,this.activity));let a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=Ni({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=Fe(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=ut({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=I(this.activityCalendar,i,t,this.activity),a=I(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=I(this.activityCalendar,r,t,this.activity),n=I(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Fe(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},lo=Fi;var Mi=class{constructor(t){this.linkedActivitiesData=t.linksWithActivityData,this.activity=t.activity,this.gantt=t.gantt}calculate(){if(this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let t=[];for(let r of this.linkedActivitiesData){let i=ee(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let n=r.linkLag,a=r.ls,s=r.lf;if(i==="ss"){let o={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(i==="ff"){let o={lag:n,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(i==="fs"){let o={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(i==="sf"){let o={lag:n,workTime:s,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(o);t.push({ls:c,lf:l})}}if(this.activity.constraint_type==="fnlt"){let r=this.getMinLfFromLinks(t),i=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([i,r]):i}else{let r=this.getMinLfFromLinks(t);if(r===!1){let i=this.gantt.getSubtaskDates();return{ls:I(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null;if(t===0)return a=I(this.activityCalendar,r,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=I(this.activityCalendar,o,n,this.activity),s=I(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=I(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=I(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=I(this.activityCalendar,c,n,this.activity),o=I(this.activityCalendar,s,i,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,s=null,o=r;return s=I(this.activityCalendar,o,i,this.activity),a=I(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=I(this.activityCalendar,r,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=I(this.activityCalendar,c,i,this.activity),s=I(this.activityCalendar,o,n,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:I(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=yt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),ut({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),yt.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},uo=Mi;function fo(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=vp(t),l=null;if(s==="forward"){let d=Ap(o,i,n,a);l=new lo(d,t,a),l=l.calculate()}else{let d=Cp(o,i,n,a);l=new uo({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function vp(e){return{duration:e.duration,calendarId:e.calendar_id}}function Ap(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);return o?{es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function Cp(e,t,r,i){return e.length===0?[]:e.map(n=>{let a=i.getLink(n);if(!a)return console.warn(`Link not found: ${n}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=i.getTask(s);return c?{ls:o.ls,lf:o.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function yo(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Ip(t.id,r))return null;let a=Sp(t.id,i),s=kp(a,r);return s.length===0?null:Dp(s,n)}function Ip(e,t){return t.has(e)}function Sp(e,t){let r=t.get(e);return r?r.childrens:[]}function kp(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Dp(e,t){if(t==="forward"){let r=po(e,"es"),i=ho(e,"ef");return{es:r,ef:i}}else{let r=po(e,"ls"),i=ho(e,"lf");return{ls:r,lf:i}}}function po(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function ho(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Wi={parentWithLinks:fo,parentWithNoLinks:yo};var Ui=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[y.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}calculateAndStoreParentWithLinks(t){let r=Wi.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&i}handleParentWithNoLinks(){let t=Wi.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:n,maxEf:a}=i.reduce((s,{es:o,ef:c})=>({minEs:new Date(Math.min(s.minEs.getTime(),new Date(o).getTime())),maxEf:new Date(Math.max(s.maxEf.getTime(),new Date(c).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:n,ef:a}),this.parentCalculationFromChildren.add(this.activity.id)}setDatesToParentsWithLinksBackward(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:n,maxLf:a}=i.reduce((s,{ls:o,lf:c})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(o).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(this.activity.id,{ls:n,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}},mo=Ui;var Bi=class{constructor({gantt:t,linkProperty:r}){this.gantt=t,this.linkProperty=r,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let t=this.getFirstLevelParents();for(let r of t){let i=this.processEachActivity(r),{activitiesByLevel:n}=i,a=this.getAllLevels(n),s=this.getDeepestLevel(a),o=this.createResult(r,i,s,a);this.structureOfParents.set(r.id,o)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(st.byFirstLevel).filter(st.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,i,n)},t.id),{parentsIds:r,allTasks:i,activitiesByLevel:n}}initializeParent(t){let r=Number(t.id),i=!!t[this.linkProperty]?.length,n=t.$level;this.singleParents.set(r,{level:n,hasLink:i,childrens:[]})}processActivity(t,r,i,n){let a=Number(t.id),s=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,a=this.hasLink(t),s={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let i=t.$level,n=Number(t.parent);r.has(i)||r.set(i,new Map);let a=r.get(i);a.has(n)||a.set(n,[]),a.get(n).push({id:Number(t.id),isParent:this.isProjectActivity(t),calculated:!1})}getAllLevels(t){return new Set(t.keys())}getDeepestLevel(t){return t.size===0?0:Math.max(...t)}createResult(t,r,i,n){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},go=Bi;var Hi=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction==="forward"?"$target":"$source",this.linkDirection=this.direction==="forward"?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let a=i.get(r);for(let[s,o]of a)if(o.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(s);this.calculateParentWithNoLinks(l,o);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(st.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=Ne.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=i}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Ne.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let a=this.gantt.getLink(i)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new go({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,i=new Set,n=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((s,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),n.has(c.$level)||n.set(c.$level,new Map);let d=n.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),s({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=Ne.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=Ne.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:i,ef:n}=r;this.calculations.set(t.id,{es:i,ef:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:i,lf:n}=r;this.calculations.set(t.id,{ls:i,lf:n,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,i=new Set(this.calculations.keys()),n=new Map;return t.forEach(a=>{a&&n.set(a.id,a)}),n.forEach((a,s)=>{if(i.has(s))return;let o=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>n.has(l)||i.has(l)),r.set(s,o)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],s=o=>{if(n.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!i.has(o)&&!r.has(o)){n.add(o);let c=t.get(o)||[];for(let l of c)s(l);n.delete(o),i.add(o),a.push(o)}};for(let o of t.keys())!i.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let a=this.gantt.getCalendar(i.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)==="forward"){let o=i.start_date,c=i.end_date;return{es:o,ef:c}}else{if(n>=100)return{ls:yt(i.start_date).clone(),lf:yt(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,a);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=yt(t.start_date).clone(),n=yt(t.end_date).clone(),a=t.duration,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=t.constraint_type||y.ASAP;if(s.includes(o))n=this.projectDates.end_date,i=I(r,n,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(i=t.constraint_date,n=I(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=I(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||y.ASAP,a=this.projectDates.end_date,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=[y.SNLT,y.FNLT];if(s.includes(n))i=Math.max(t.end_date,a);else if(n===y.MSO)i=t.end_date;else if(n===y.MFO||o.includes(n)){let c=Math.min(a,t.constraint_date);i=Math.max(c,t.end_date)}return{ls:r,lf:new Date(i)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(i=>Number(this.gantt.getTask(i).progress)===100).map(i=>this.gantt.getTask(i)).forEach(i=>{let n=i.type==="project";this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),n&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction==="forward"?"es":"ls"]:i.start_date,[this.direction==="forward"?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new mo({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},$t=Hi;function Tp(e,t,r){let i={es:null,ef:null};if(!e)return i;if([y.SNET,y.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}else if(t===y.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=I(r,n,e.duration,e)}else if(t===y.MFO){let n=new Date(e.constraint_date);i.es=I(r,n,-e.duration,e),i.ef=n}return i}var _r=Tp;var ji=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=H.FS){let s=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let o=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===H.FS&&n===0?o=ut({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[H.FF,H.SF].includes(a)?(l=I(s,o,i,this.referenceActivity),c=I(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=I(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=I(s,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,H.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,H.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,H.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![H.FS,H.SS,H.FF].includes(r))return t;let a=[H.FS,H.SS].includes(r)?"future":"past";return ut({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},vo=ji;var Me=class extends vo{constructor(t){super(t)}calculate(){if(this.links.length===0)return new $t(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(i=>{let n=this.gantt.getLink(i);if(!n)throw new Error("Link data not found",{cause:{linkId:i}});return this.calculateLink(n)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),n=this.parentsCalculations.get(r).es,a=I(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return Tr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Vi=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,i=new Set(t);for(let n of t){let a=this.gantt.getTask(n);a.type==="project"?this.handleProjectActivity(n,a,r,i):this.handleNonProjectActivity(n,a,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let a=this.pendingParentsWithNoLinks.has(t),s=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(i.add(t),n.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,i=t.constraint_type;return(this.direction==="forward"?i==="fnlt"||i==="snlt":i==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),s=this.pendingParentsWithLinks.has(a),o=this.calculationOfParentsFromLinks.has(a);if(s&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(r.$target.length===0&&r.$source.length===0){i.add(t),n.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){i.add(t),n.delete(t);return}l&&(i.add(t),n.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=n[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let i of t){let n=this.gantt.getLink(i);n&&r.push(Number(n[this.linkDirection]))}return r}},Pr=Vi;var Yi=(e,t)=>()=>t()===e;var Ki=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var _p=16,We=async e=>performance.now()-e>_p?(await Z(),performance.now()):e;var Ue=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await We(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await We(c),r([u])}for(let u of l){if(!s())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}o=d}};var $i=class extends $t{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new Pr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Ue({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(i.type==="project")return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,a=i.constraint_type||y.ASAP,s=[y.SNET,y.SNLT,y.FNLT,y.FNET],o=[y.ASAP,y.ALAP,y.SNET,y.FNET,y.SNLT,y.FNLT],c=this.gantt.getCalendar(i.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let l=Number(i.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new Me({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new Me({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let h=_r(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,h),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,h,{es:d,ef:u})),[y.MSO,y.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,h),i.progress===0)d=h.es,u=h.ef;else{let m=i.end_date;a===y.MFO&&(m=Math.max(h.ef,i.end_date)),d=i.start_date,u=m}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,i="greater"){if(i==="greater")return r.ef>t.ef?r:t;if(i==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,i){let n=[y.SNET,y.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r);if(!i)throw new Error("Error trying to get link",{cause:{linkId:r}});let n=i.source,a=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Ao=$i;var Gi=class{constructor(t){this.activity=t.activity,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.forwardPathCalculations=t.calculatedForwardActivitiesMap,this.gantt=t.ganttInstance}getForwardOrBackwardCalculations(t,r=null){return r===y.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=H.FS){let s=this.gantt.getCalendar(this.activity.calendar_id);if(!s)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let o=t,c=this.activity.type==="milestone";if(c&&n===0){let d=I(s,o,r,this.activity),u=I(s,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===H.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===H.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===H.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===H.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let i=this.getValueForSS(t,r),n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,H.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===y.ALAP?"ef":"lf",a=i[n],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,H.FF)}calculateFS(t,r){let i="ls";i=r===y.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,o,s,H.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(i,n,a,s,H.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=yt(r).clone();return I(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=yt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),ut({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),a=t.getWorkHours(i)[0];if(!a||!a.includes("-"))return!1;let s=a.split("-")[0];if(!s.includes(":"))return!1;let o=s.split(":");return o.length<2?!1:(s=parseInt(o[0],10),yt.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return o=I(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=I(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=I(i,l,a,this.activity),c=I(i,o,n,this.activity),s||(o=this.getLastWorkingHour(o,i,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=I(i,r,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=I(i,c,a,this.activity),o=I(i,s,n,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=I(i,r,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=I(i,l,n,this.activity),o=I(i,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=I(i,r,n),s=I(i,o,a,this.activity),{ls:o,lf:s}):(o=I(i,r,n,this.activity),s=I(i,o,a,this.activity),{ls:o,lf:s})}},Co=Gi;var zi=class extends Co{constructor(t){super(t),this.constraint=t.constraint||y.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new $t(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),i=!1;r&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let n=this.links.map(s=>{let o=this.gantt.getLink(s);if(!o)throw new Error("Link not found",{cause:{linkId:s}});if(!this.parentsWithFullProgress.has(Number(o.target)))return this.calculateLink(o)}).filter(s=>s);if(n.length!==0){let s=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(n),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=I(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);n.push({ls:c,lf:o});let l=this.getMinDateFromLinks(n);return{ls:l.ls,lf:l.lf,minFromLinks:l}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(t=null){try{let r=this.activity.duration,i=this.gantt.getCalendar(this.activity.calendar_id);if(!i)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let n=t?t.lf:this.projectDates.end_date;if(!n)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:I(i,n,-r,this.activity),lf:n}}catch(r){throw Error(r.message)}}SnetSnltMsoMinDate(t){let r=Math.min(t.lf,this.projectDates.end_date);return new Date(Math.max(r,this.activity.end_date))}calculateLink(t){let r=this.gantt.getTask(t.target);if(!r||r.progress>0&&r.type!=="project")return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===y.ALAP)return y.ALAP;if(this.constraint===y.FNET||this.constraint===y.SNET)return"snet-fnet";if(this.constraint===y.FNLT)return y.FNLT}getSpecialParamForSf(){return!![y.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![y.MFO,y.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===y.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.SNET||this.constraint===y.SNLT||this.constraint===y.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===y.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===y.ALAP||this.constraint===y.ASAP?t.reduce((i,n)=>n.lf<i.lf?n:i):t.reduce((r,i)=>i.ls<r.ls?i:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,i)=>i.lf<r.lf?i:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let i=Math.min(t.lf,this.projectDates.end_date),n=this.activity.end_date,a=this.activity.constraint_date;if(r===y.ASAP)return new Date(Math.max(i,n));if(r===y.FNET||r===y.FNLT){let s=Math.min(i,a);return new Date(Math.max(i,s))}if(r===y.ALAP)return new Date(Math.min(i,n))}},Io=zi;function Pp(e,t,r){let i={ls:null,lf:null};return r===y.MSO&&(i.ls=t.constraint_date,i.lf=I(e,i.ls,t.duration,t)),r===y.MFO&&(i.lf=t.constraint_date,i.ls=I(e,i.lf,-t.duration,t)),i}var So=Pp;var qi=class extends $t{constructor(t,r,i){super(t,"backward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.activitiesWaitingForCalculation=new Set,this.calculations=new Map,this.mapOfRelationsWithActivitiesIds=new Map,this.activitiesWaitingForCalculation=new Set,this.forwardPathCalculations=r,this.forwardConstraintsMap=i,this.constraintMap=new Map,this.minFromLinks=new Map,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.parentsWithFullProgress=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateLfAndLs(t))))))}async iterativeCalculateLfAndLs(t){let r=new Pr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await Ue({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:i=>this.calculateStartAndFinishTimes(i),shouldKeepPending:i=>this.calculationOfParentsFromLinks.has(i)&&!this.calculations.has(i),isCalculated:i=>this.calculations.has(i),onActivityProcessed:i=>this.activitiesWaitingForCalculation.delete(i),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,n=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=n.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let i=this.gantt.getTask(r);if(!i)throw new Error("Activity not found",{cause:{activityId:r}});let n=i.$source,a=i.constraint_type||y.ASAP,s=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(i.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(i.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(i,this.direction);this.setCalculations(i,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(i)}if(i.type==="project")return this.doCalculationForParentType(i);if(s===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(s>0&&s<100&&(a===y.MSO||a===y.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===y.MSO||a===y.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===y.SNLT||a===y.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:o,lf:c},a)),this.setCalculations(i,o,c),this.minFromLinks.set(i.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,i){let n=this.forwardConstraintsMap.get(t);if(!n){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);n=_r(a,i,s)}return r.lf<n.ef?r:{ls:n.es,lf:n.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let i of t){let n=this.gantt.getLink(i);if(!n)continue;let a=this.gantt.getTask(n.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:i,lf:n}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(n=new Date(Math.min(n,a.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===y.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===y.MFO){let i=Math.min(t.constraint_date,this.projectDates.end_date),n=new Date(Math.max(i,t.end_date));this.setCalculations(t,t.start_date,n);return}}setCalculations(t,r,i){this.calculations.set(t.id,{ls:r,lf:i,text:t.text})}calculateLfandLsFromLinks(t,r,i,n,a){return new Io({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let i=this.gantt.getCalendar(t.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let n=So(i,t,r);this.constraintMap.set(t,n),this.setCalculations(t,n.ls,n.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let i=this.gantt.getLink(r).source,n=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,a=0;if([y.ASAP,y.ALAP,y.SNET,y.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,i.lf)),n=t.start_date}else a=i.lf,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([y.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=I(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);n=new Date(Math.min(l.getTime(),d.lf.getTime())),a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=I(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=I(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:I(this.gantt.getCalendar(t.calendar_id),s,-t.duration,t),lf:s});let c=this.getMinLfFromLinks(o);this.calculations.set(t.id,{ls:c.ls,lf:c.lf,text:t.text})}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,i)=>i.lf<r.lf?i:r):!1}},ko=qi;function Do(){return null}var To=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:a})=>({totalFloat:{es:e.calculations.get(r)?.es||0,ef:e.calculations.get(r)?.ef||0,ls:t.calculations.get(r)?.ls||0,lf:t.calculations.get(r)?.lf||0,constraintsMap:e.constraintsMap.get(r),totalFloatSnltFnlt:e.totalFloatSnltFnlt.get(r),totalFloatForMsoMfo:e.totalFloatForMsoMfo.get(r),minFromLinks:t.minFromLinks.get(r),activity:i,gantt:n},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:i,projectDates:a,gantt:n}});var Ji=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.es=t.es,this.ef=t.ef,this.ls=t.ls,this.lf=t.lf,this.constrainstMap=t.constraintsMap,this.totalFloatSnltFnlt=t.totalFloatSnltFnlt,this.totalFloatForMsoMfo=t.totalFloatForMsoMfo,this.minFromLinks=t.minFromLinks}getTotalFloat(){let{constraint_type:t}=this.activity,r=Number(this.activity.progress);if(r===100)return 0;if(t||(t=y.ASAP),t===y.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===y.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===y.SNET||t===y.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===y.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===y.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===y.MSO||t===y.MFO)return r===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateAlap(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r),n=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let r=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}return t/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let t=this.calculationWithCalendar(this.lf,this.ef),r=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,i)/this.gantt.config.hoursPerDay}return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(t,r)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===y.SNLT?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let n=0;return this.activity.constraint_type===y.MSO?n=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):n=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(n,i)/this.gantt.config.hoursPerDay}getMinValue(...t){return Math.min(...t)}calculationWithCalendar(t,r){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)})}},_o=Ji;var Xi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===y.MSO||t===y.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=y.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),s=this.gantt.getTask(n.target);if(!s)return{linkId:n.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),f=Math.max(0,u);return this.linksFreeFloatObject[n.id]=f,{linkId:n.id,freeFloat:f,hasProgress:o}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=y.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[y.SNLT,y.FNLT].includes(t)?n=this.doCalculationForSnltFnlt(t,i,r):n=this.doGeneralCalculation(i,r),Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=y.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===y.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,i){let n=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(i,r,n)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===y.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=ee(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=({direction:s,constraint:o=y.ASAP})=>o===y.ALAP?this.backwardMap.get(n)[s]:this.forwardMap.get(n)[s];if(t===y.ASAP||t===y.SNET||t===y.FNET||t===y.MSO||t===y.MFO)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===y.ALAP)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:y.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({constraint:y.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:y.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({constraint:y.ALAP,direction:"ls"})}};if(t===y.SNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}};if(t===y.FNLT)return{fs:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(i).ls:this.forwardMap.get(i).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(i).lf:this.forwardMap.get(i).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=t===y.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,n=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(n))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let i=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(i))return this.durationCache.get(i);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return r.length===0?null:Math.min(...r)}},Po=Xi;var Eo=e=>({totalFloat:new _o(e.totalFloat).getTotalFloat(),freeFloat:new Po(e.freeFloat).getFreeFloat()});var Zi=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let s=performance.now(),o=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:o,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=To({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:h}=Eo(u);o.set(l,f),c.set(l,h),s=await We(s)}return{totalFloatMap:o,freeFloatMap:c}};var Qi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let i=++this.currentCalculationId,n=Yi(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||Do(),Ki(this.gantt))return!1;let o=new Ao(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new ko(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let{totalFloatMap:u,freeFloatMap:f}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=u,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(s){return this.forwardPathCalculations?.size,!1}}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await Zi({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){return this.forwardPathCalculations?.size,{totalFloatMap:new Map,freeFloatMap:new Map}}}},Ro=Qi;var Ep=e=>e==="fnet"||e==="fnlt"||e==="mfo",Rp=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function bp(e,t){let r=e.constraintDate;if(!r||!Ep(e.constraintType))return r;let i=Rp(r);if(r.getTime()!==i.getTime())return r;let n=t.getClosestWorkTime({date:i,dir:"future",task:e});return n.getUTCFullYear()===r.getUTCFullYear()&&n.getUTCMonth()===r.getUTCMonth()&&n.getUTCDate()===r.getUTCDate()?mi(e,t):r}function Lp(e){return{calculateEndDate:({start_date:t,duration:r})=>e.calculateEndDate(t,r),calculateDuration:({start_date:t,end_date:r})=>e.calculateDuration(t,r),getWorkHours:t=>e.getWorkHours(t),$gantt:{getClosestWorkTime:({date:t,dir:r,unit:i})=>e.getClosestWorkTime({date:t,direction:r,unit:i??"hour"})}}}function wp(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let s=r.get(n);if(s!=null)return s;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!a.has(n)&&(a.add(n),l=i(String(c),a)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function Op(e){let t=wp(e),r=new Map;return e.forEachActivity((i,n)=>{let a=String(n);r.set(a,{id:Number(n),parent:i.parentId===null?0:Number(i.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:bp(i,e)})}),r}function xp(e){let t=new Map;for(let s of e.values()){let o=t.get(s.parent);o?o.push(s):t.set(s.parent,[s])}let r=[],i=new Set,n=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)n.push(s[o])};for(a(t.get(0));n.length>0;){let s=n.pop();i.has(s)||(i.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())i.has(s)||r.push(s);return r}function Np(e){let t=null,r=null;return e.forEachActivity(i=>{if(i.startDate){let n=i.startDate.getTime();t=t==null?n:Math.min(t,n)}if(i.endDate){let n=i.endDate.getTime();r=r==null?n:Math.max(r,n)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function bo(e,t){let r=new Map,i=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=Lp(u);return r.set(l,f),f},n=Np(e);await Z();let a=Op(e);await Z();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await Z();let o=xp(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>a.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target),lag:l.lag}:null},getCalendar:i,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>n,refreshData:()=>{}}}var Fp=1e3;function Mp(e,t,r){let i=o=>o==null?null:new Date(o),n=r.forward?.get(e),a=r.backward?.get(e),s=r.totalFloat.get(e)??null;return{criticalPath:{earlyStart:i(n?.es),earlyFinish:i(n?.ef),lateStart:i(a?.ls),lateFinish:i(a?.lf),totalSlackHours:s},isCritical:t<100&&s!=null&&s<=0,freeSlackHours:r.freeFloat.get(e)?.activityFreeFloat??null}}async function tn(e,t,r=()=>!0){if(!r())return null;let i=await bo(e,t);if(!r())return null;let n=new Ro(i);if(!await n.calculate(i,r)||!r())return null;let s={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},o=new Set([...s.forward?.keys()??[]]),c=new Map,l=0;for(let d of o){if(++l>=Fp&&(l=0,await Z(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,Mp(d,f,s))}return r()?c:null}async function Er(e,t,r=()=>!0){let i=await tn(e,t,r);if(!i||!r())return!1;for(let[n,a]of i){if(!r())return!1;e.setActivityFields(n,a)}return!0}function Gt(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(String(n));if(!a)return 0;let s=[...e.getChildren(String(n))],o;if(s.length===0){let c=it(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=i(String(l));o=c}return e.setActivityField(String(n),b.REAL_COST,o),r.push(String(n)),o};for(let n of t)i(n);return r}var Lo=new Set;var wo=new Set(["activity-outdent","activity-indent"]);var Be=new Set([P.TEXT,P.DESCRIPTION,P.COST,P.USED_COST,P.CUSTOM_ID,P.RESPONSABLES,P.SUBCONTRACT_ID,P.TAGS]),Wp=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),Up=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function xo(e){return!Up.has(e.kind)}var Bp=new Set;function Hp(e){return e.kind==="inline-edit"?Be.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Be.has(t.column)):!1}function en(e,t){return!(Wp.has(e.kind)||t.has(e.kind)||Hp(e))}function No(e){return en(e,Bp)}function He(e){return en(e,Lo)}function Fo(e){return en(e,wo)}function rn(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===P.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===P.PROGRESS):!1}function jp(e){return Fo(e)&&rn(e)}var Oo=new Set([P.PROGRESS,P.HH_WORK_TIME,P.DURATION,P.COST,P.USED_COST,P.REAL_COST]);function Vp(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?Oo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>Oo.has(t.column)):!1}var nt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",CRITICAL_PATH:"critical-path"};function Mo(e,t,r){let i=new Set;t.ran&&i.add(nt.AUTOSCHEDULE),i.add(nt.PARENT_BOUNDS),Vp(e)&&i.add(nt.PARENT_PROGRESS),rn(e)&&i.add(nt.REAL_WORK);let n=!r.skipAutoSchedule;return n&&Fo(e)&&i.add(nt.EXPECTED_PROGRESS),n&&jp(e)&&i.add(nt.REAL_COST),n&&He(e)&&!r.skipCriticalPath&&i.add(nt.CRITICAL_PATH),i}async function $(e,t){let r=Yp(t);r.has(nt.AUTOSCHEDULE)&&await zp(e.adapter,t);let i=r.has(nt.AUTOSCHEDULE)?await Kp(e,t.autoscheduleFrom):Gp();return await qp(e.adapter,t,i.scheduledIds,r),await Jp(e,r,t.now),i}function Yp(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,i=new Set(Mo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&i.add(nt.PARENT_PROGRESS),i}async function Kp(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=$p(e.adapter,i.updatedIds);return Le(e.adapter,i),n}function $p(e,t){let r=[];for(let i of t){let n=String(i);r.push(n);let a=e.getActivity(n);a&&e.noteScheduledBefore(n,a)}return{scheduledIds:r}}function Gp(){return{scheduledIds:[]}}async function zp(e,t){let r=t.collectDirty?t.collectDirty([]):wi(t.recomputeParentsFrom,[]);r.size!==0&&await pe(e,r,!1)}async function qp(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):wi(t.recomputeParentsFrom,r);await pe(e,n,i.has(nt.PARENT_PROGRESS),{recomputeRealWork:i.has(nt.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function Jp(e,t,r){t.has(nt.EXPECTED_PROGRESS)&&r!==null&&(Xp(e.adapter)&&Kt(e.adapter,r,e.defaultBaseCalendarId??null),wt(e.adapter,r),St(e.adapter,e.sector.statusCriteria)),t.has(nt.REAL_COST)&&Gt(e.adapter),t.has(nt.CRITICAL_PATH)&&await Er(e.adapter,e.sector.hoursPerDay)}function Xp(e){let t=!1;return e.forEachActivity(r=>{it(r)&&(t=!0)}),t}var Zp=new Set([P.CONSTRAINT_TYPE,P.CONSTRAINT_DATE]),Qp=new Set(["mso","mfo"]);function Rr(e){return Zp.has(e)}function br(e){return e===P.CONSTRAINT_DATE}function Lr(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||Bt.has(a)||Qp.has(a))return!1;let s=nn(n.startDate),o=nn(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=th(t,a,String(n.calendarId??""),i),l=nn(n.constraintDate);return eh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function th(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?Rt(e,n,t):e}function nn(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function eh(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function wr(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await $(e,Wo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=i(s,o);a=a||c}if(a){let s=await $(e,Wo(t));n=ih(n,s.scheduledIds)}return He(t.action)&&await $(e,rh(t)),{scheduledIds:n}}function Wo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function rh(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function ih(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function nh(e,t){let r=i=>i.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function an(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let s=a.pendingRequestIds??[];if(!se({pendingRequestIds:s}))continue;let o=t.getActivity(n),c=o==null;if(!c&&!nh(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)i.push({kind:"sir-auto-reject",activityId:n,sirId:d,reason:l});c||t.setActivityField(n,"pendingRequestIds",[])}return i}async function j(e,t){let r=sh(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let d=ch(n);oh(e,n,d,i,r)}let a=t.sirDetection==="before-diff"?an(i,e,r):[],s=ah(t.correlativeShifts,r),o=await eo(e,i,r,s),c=t.sirDetection==="after-diff"?an(i,e,r):a,l=t.warnings??[];return{source:t.source,activities:o,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...c.length>0?{effects:c}:{},...l.length>0?{warnings:l}:{}}}function ah(e,t){if(!e||e.length===0)return;let r=new Map;for(let i of e)r.set(i.activityId,i.before),t.add(i.activityId);return r}function sh(e,t){let r=new Set;for(let i of t.touchedIds)r.add(i);for(let i of t.scheduledIds)r.add(i);if(t.includeAllIds)for(let i of e.getAllIds())r.add(i);return r}function oh(e,t,r,i,n){for(let a of t.dirty){if(r.has(a)||i.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(Li(s,o)).length!==0&&(i.set(a,s),n.add(a))}}function ch(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function kt(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function Or(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:kt(d)});continue}if(n.kind==="delete"){let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:"deleted",fields:d?{source:{before:String(d.source),after:void 0},target:{before:String(d.target),after:void 0},type:{before:d.type,after:void 0},lag:{before:Number(d.lag),after:void 0}}:void 0,after:null});continue}let o=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};o&&o.type!==c.type&&(l.type={before:o.type,after:c.type}),o&&Number(o.lag)!==Number(c.lag)&&(l.lag={before:Number(o.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:kt(c)})}return i}function Se(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let i of e.getIncomingLinkIds(t)){let n=e.getLink(i);n&&r.set(String(n.id),Number(n.lag))}return r}function ke(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let a=t.getLink(n);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:kt(a)})}return i}function xr(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Uo(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=jt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);lh(e.column)&&a.invalidateExpandedLinksCache(),e.column===b.PARENT&&a.invalidateAllCaches();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??E.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??E.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??E.INVALID,alertKey:f.notification?.messageKey};if(e.column===P.CUSTOM_ID&&d.value!==null){let S=i.getActivity(e.activityId),R=S?S.customId:null,x=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:E.CUSTOM_ID_DUPLICATE}}let h=o.transform(c,d.value,n,d.raw),m=Vt(e.activityId,h),v=await q(i,m),A=Se(i,String(e.activityId)),k=c.constraintDate;Yt(i,e.activityId,h),Ut(e.activityId,h.postProcessors??[],i,v.get(String(e.activityId))??null);let D=ke(A,i,String(e.activityId));if(e.column===P.CUSTOM_ID){let S=v.get(String(e.activityId)),R=S?S.customId:null,x=typeof R=="string"?R:null,L=typeof d.value=="string"?d.value:null;x!==L&&r.customIdTracker.trackCustomIdChange(x,L)}let _=()=>({action:e,autoscheduleFrom:h.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:S=>Sr(e.activityId,m,S),now:r.now,options:t}),p=Rr(e.column),{scheduledIds:g}=await(p?wr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:_(),revertTargets:br(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:k}],revert:(S,R)=>Lr(S,R,i,n.calendars)}):$({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},_())),C=(h.trackingEvents??[]).map(S=>({name:S.name,properties:S.properties??{}})),T=Ce(e.activityId,h.constraintWarning);return{ok:!0,changes:await j(i,{source:e,beforeSnap:v,touchedIds:m,scheduledIds:g,sirDetection:"before-diff",links:D,trackingEvents:C,...T?{warnings:[T]}:{},hoursPerDay:s.hoursPerDay})}}function lh(e){return e===P.DURATION||e===b.AUTO_SCHEDULING}function dh(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind==="create"){r.add(String(n.source)),r.add(String(n.target));continue}let a=t.getLink(n.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),i.set(n.linkId,{...a}))}return{activityIds:r,links:i}}function uh(e,t,r,i){return e.map((n,a)=>{let s=n.kind==="create"?i?.get(a):void 0,o=Mt(n,{port:t,newLinkId:s?()=>s:r.next});return{op:n,finalLinkId:o.applied?o.linkId:null,rejected:o.applied?null:o.rejected??"link_op_rejected"}})}function fh(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Bo(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let i=e.type;if(i!==void 0&&!Object.values(W).some(a=>a===i))return{ok:!1,reason:E.INVALID_LINK_TYPE};let n=e.lag;if(n!==void 0&&!Number.isFinite(n))return{ok:!1,reason:E.INVALID_LINK_LAG}}return sn([gh(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Ho(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>hh(s,i)),a=ph(e.operations);return sn(n,e,t,r,a)}function ph(e){let t=new Map;return e.forEach((r,i)=>{r.kind==="create"&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function hh(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ht(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ht(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function sn(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let{activityIds:l,links:d}=dh(e,a),u=await q(a,l),f=uh(e,a,c,n);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let h=yh(f,d,a),{scheduledIds:m}=await $({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:h,recomputeParentsFrom:l,now:i.now,options:r}),v=Or(f,d,a);return{ok:!0,linkVerdicts:f.map((A,k)=>A.rejected===null?{operationIndex:k,kind:A.op.kind,ok:!0,linkId:String(A.finalLinkId)}:{operationIndex:k,kind:A.op.kind,ok:!1,reason:A.rejected}),__beforeLinks:fh(d),changes:await j(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:m,links:v,hoursPerDay:o.hoursPerDay})}}function yh(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=mh(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function mh(e,t,r){return e.kind==="create"?e.target:e.kind==="delete"?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function gh(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:ht(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:ht(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function jo(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:E.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let s=e.column===P.CUSTOM_PREDECESSORS,{specs:o}=cr(e.newValue),c=o.map(m=>({...m,lag:ht(m.lag,n.hoursPerDay)})),l=new Map;i.forEachActivity(m=>{m.correlativeId!=null&&l.set(String(m.correlativeId),m.id)});let d=m=>l.get(m)??null,u=s?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let m of u){let v=i.getLink(m);v&&f.push(v)}let h=s?dr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):ur({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return sn(h.operations,e,t,r)}var mt={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};function ct(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{w(a.parentId)&&t.push(a)}),t.sort(Ko);let r=[];Vo(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),vh(a,n)}n+=1;let s=hi(String(a.id),e);s.sort(Ko),Vo(r,s)}return i}function Vo(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Yo(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:fi}var Ko=(e,t)=>Yo(e)-Yo(t);function vh(e,t){e.correlativeId=t}function cn(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0,a=0;for(let c of i){let l=t.getActivity(c);if(!l)continue;let d=on(l,b.WORK_HOURS),u=Ah(c,l,d,t);n+=d,a+=u}t.setActivityField(r,b.WORK_HOURS,n),t.setActivityField(r,b.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||w(o))break;r=o}}function $o(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||w(i)||cn(i,t)}function on(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ah(e,t,r,i){return i.hasChildren(e)?on(t,b.REAL_WORK_HOURS):dt(r,on(t,b.PROGRESS))}function ln(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Ch(c,b.USED_COST))}t.setActivityField(r,b.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||w(s))break;r=s}}function Go(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||w(i)||ln(i,t)}function Ch(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function dn(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let o of i){let c=t.getActivity(o);c&&(n+=Ih(c,b.COST))}t.setActivityField(r,b.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||w(s))break;r=s}}function zo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||w(i)||dn(i,t)}function Ih(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Nr=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),qo="New Master Plan",Jo="New Activity";var Sh=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Xo=new Set(Sh);function kh(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!Xo.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Zo(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=kh(e.activityOverrides??{}),n=e.numTasksInGantt===0?qo:Jo,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=Dh(r,e.fallbackStartDate,i.startDate),l={...Nr,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:X.FUTURE,task:l}),u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function Dh(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Th(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,i=e.endDate;return!(r instanceof Date)||!(i instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(i),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function De(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ft(t.type):_h(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(s=>String(s)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=Ii,(e.promotionSource??"create")==="create"&&(a.constraintType=Y.ASAP,a.constraintDate=null,a.progress=0,a.expectedProgressBaseline=0)),{parentId:e.parentId,fields:a,promotionSnapshot:Th(t)}}function _h(e){return Ft(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Fr(e,t,r,i){let n=t,a=n==="0",s=un(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=ot(c),d=s.map(ot).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=s.find(l=>l.id===r);if(c){let l=ot(c),d=s.map(ot).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return s.length===0?0:Math.max(...s.map(ot))+1}var re=Number.MAX_SAFE_INTEGER,Qo=Number.MAX_SAFE_INTEGER-1;function ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:re}function un(e,t){let r=[];return e.forEachActivity(i=>{qt(i.parentId)===t&&r.push(i)}),r}function tc(e,t,r){let i=e,n=zt(e,r);for(;n!=null&&t.has(n);)i=n,n=zt(n,r);return i}function zt(e,t){let r=t.getActivity(e);if(!r)return null;let i=qt(r.parentId),n=lt(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function ec(e,t,r,i){let n=lt(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let a=n.map(ot);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let s=a[r-1],o=a[r];return(s+o)/2}async function fn(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=Ph(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,h=Rh(e.activityId,i,o),m=c.next(),v={id:h,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Nh(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:m,activityOverrides:e.overrides??{}},k=Zo(v,{getActivity:C=>i.getActivity(C),calculateEndDate:C=>i.calculateEndDate(C),getClosestWorkTime:C=>i.getClosestWorkTime(C)}).newTask;k.realWorkHours=dt(k.workHours,k.progress),Lh(k,e,t,u,d,r);let D=Fr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);k.correlativeId=D;let _=new Set([h]);d&&_.add(d.id);let p=d!==null&&i.getChildren(d.id).length===0,g=r.skipBeforeSnap?new Map:await q(i,_);return i.addActivity(k),wh(e,h,d,i,r.preserveParentCustomId??!1,p),$o(h,i),Go(h,i),zo(h,i),Oh(i,h,g,_,r),{ok:!0,newId:h,parent:d,newActivity:k,beforeSnap:g,initialTouched:_}}function Ph(e,t){let r=w(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:E.PARENT_NOT_FOUND};if(i!==null&&se(i))return{ok:!1,reason:E.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:E.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Eh(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function Eh(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:E.ANCHOR_SIBLING_WRONG_PARENT}:null}function Rh(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function bh(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Lh(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=bh(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=i??a.customIdReferenceId,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function wh(e,t,r,i,n,a){if(!r)return;let s=De({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:a,getParent:o=>i.getActivity(o)??null});if(s){for(let[o,c]of Object.entries(s.fields))o===b.CUSTOM_ID&&n||tt(i,s.parentId,o,c);s.promotionSnapshot&&i.setPromotionSnapshot(s.parentId,s.promotionSnapshot)}}function Oh(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=ct(e);n.skipBeforeSnap||kr(e,a,new Set([String(t)]),r,i)}async function xh(e,t,r,i,n){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:mt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(l.properties.event_source=t.eventSource),j(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:i,trackingEvents:[l],hoursPerDay:n})}async function rc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=await fn(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;i.setActivityField(o,"autoScheduling",!1);let l;try{l=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{i.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d}=l;return{ok:!0,changes:await xh(i,e,s,d,a.hoursPerDay)}}function Nh(e){for(let r of e.values())if(r.is_default)return r.id;let t=e.values().next();return!t.done&&t.value?t.value.id:"global"}function Fh(e,t){if("afterSiblingId"in e){let a=t.getActivity(e.afterSiblingId);return a?{ok:!0,parentId:a.parentId==null?"0":String(a.parentId),firstAfter:e.afterSiblingId}:{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,n=un(t,r).sort((a,s)=>ot(a)-ot(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function Mh(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function ic(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=Fh(e.destination,i);if(!s.ok)return s;let o=await q(i,new Set),c=new Set,l=new Map,d=[],u;for(let k of e.activities){let D=l.get(k.originalParentId),_,p,g;D!==void 0?_=D:(_=s.parentId,u===void 0?(p=s.firstAfter,g=s.firstBefore):p=u);let C=await fn({kind:"activity-create",parentId:_,afterSiblingId:p,beforeSiblingId:g,...k.activityId?{activityId:k.activityId}:{},overrides:Mh(k.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,...D!==void 0?{customIdReferenceId:e.referenceActivityId,preserveParentCustomId:!0}:{}});if(!C.ok)return C;if(k.baselineSnapshot!==void 0){let T=k.baselineSnapshot;i.setActivityField(C.newId,"baselineSnapshot",T?{...T,startDate:T.startDate?new Date(T.startDate):null,endDate:T.endDate?new Date(T.endDate):null}:null)}l.set(k.originalId,C.newId),d.push(C.newId),D===void 0&&(u=C.newId)}let f=ct(i),h=new Set(d.map(String));kr(i,f,h,o,c);for(let k of d)c.add(String(k));let m=[];for(let k of e.links){let D=l.get(k.source),_=l.get(k.target);if(D===void 0||_===void 0)continue;let p={kind:"create",source:D,target:_,type:k.type,lag:ht(k.lag,a.hoursPerDay)},g=Mt(p,{port:i,newLinkId:k.linkId?()=>k.linkId:r.linkIdGen.next});m.push({op:p,finalLinkId:g.applied?g.linkId:null,rejected:g.applied?null:g.rejected??"link_op_rejected"})}let{scheduledIds:v}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),A=Or(m,new Map,i);return{ok:!0,changes:await j(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:v,links:A,hoursPerDay:a.hoursPerDay})}}function nc(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:i,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function ac(e,t){let r=[...new Set(e.activityIds.map(String))],i=r.map(a=>t.adapter.getActivity(a));if(i.some(a=>!a))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let n=[];for(let[a,s]of r.entries()){let o=i[a];if(!o)continue;let c={};o.isLookahead!==e.isLookahead&&(c.isLookahead={before:o.isLookahead,after:e.isLookahead},t.adapter.setActivityField(s,"isLookahead",e.isLookahead)),o.hasLookaheadTasks!==e.hasLookaheadTasks&&(c.hasLookaheadTasks={before:o.hasLookaheadTasks,after:e.hasLookaheadTasks},t.adapter.setActivityField(s,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(c).length!==0&&n.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:n,links:[],calendars:[],trackingEvents:[]}}}function Ot(e,t){cn(e,t),ln(e,t),dn(e,t)}function sc(e,t){let r=new Set,i=[];for(let n of e){let a=String(n);r.has(a)||(r.add(a),i.push(a))}for(;i.length>0;){let n=i.pop(),a=t.getChildren(n);for(let s of a){let o=String(s);r.has(o)||(r.add(o),i.push(o))}}return r}function oc(e,t){let r=new Set;for(let i of e){for(let n of t.getOutgoingLinkIds(i))r.add(String(n));for(let n of t.getIncomingLinkIds(i))r.add(String(n))}return[...r]}function Wh(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function Uh(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function Te(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=Wh(e.promotionSnapshot)??(i?{type:de,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Uh(t,r,e.computeEndDate)}:{type:de});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(n.newActivityIds=s)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function cc(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,i=r.filter(n=>!e.idsRemoved.has(n)&&!e.idsRemoved.has(String(n)));return i.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}var lc=200;async function dc(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:s}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:E.ACTIVITY_IDS_EMPTY};for(let T of e.activityIds)if(!i.getActivity(T))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let o=sc(e.activityIds,i),c=oc(o,i),l=new Set;for(let T of e.activityIds){let S=i.getActivity(T);if(!S)continue;let R=S.parentId;if(w(R))continue;let x=String(R);o.has(x)||l.add(x)}let d=new Set([...o,...l]),u=await q(i,d),f=new Map;for(let T of c){let S=i.getLink(T);S&&f.set(T,{...S})}let h=new Set,m=0;for(let T of o){m+=1,m%lc===0&&await Z();let S=i.getActivity(T);if(!S)continue;let R=w(S.parentId)?null:i.getActivity(String(S.parentId)),x=R?.hasNewActivities===!0&&R.newActivityIds.some(V=>String(V)===String(T));(S.isNewActivity===!0||x)&&h.add(T);let L=S.customId;typeof L=="string"&&L.length>0&&a.releaseCustomId(L)}for(let T of c)i.removeLink(T);let v=Hh(i,o),A=0;for(let T of o)A+=1,A%lc===0&&await Z(),i.removeActivity(T);for(let T of l){let S=i.getActivity(T);if(!S)continue;Bh(S,h,i);let R=i.getChildren(T),x=Te({parent:S,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(T),computeEndDate:(L,V)=>i.calculateEndDate({startDate:L,durationHours:V,task:S}),idsRemoved:o});if(!x){hr(T,i);continue}for(let[L,V]of Object.entries(x.fields))tt(i,T,L,V);if(S.customId==null||S.customId===""){let L=zt(T,i),V=L?i.getActivity(L)?.customId:null,G=a.generateCustomIdForRestoredChild(typeof V=="string"&&V?V:null);i.setActivityField(T,b.CUSTOM_ID,G)}}for(let T of l)Ot(T,i);let k=ct(i),{scheduledIds:D}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),_={name:mt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(_.properties.event_source=e.eventSource);let p=new Map;for(let[T,S]of f)p.set(T,S);let g=new Map;for(let T of o){let S=u.get(String(T));S&&g.set(String(T),S)}let C=await j(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:D,sirDetection:"after-diff",links:jh(f),trackingEvents:[_],hoursPerDay:s.hoursPerDay,correlativeShifts:k});return{ok:!0,changes:v.length>0?{...C,viewState:v}:C,__beforeSnap:g,__beforeLinks:p}}function Bh(e,t,r){let i=cc({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))tt(r,i.parentId,n,a)}function Hh(e,t){let r=[];for(let i of t){let n=e.isChecked(i),a=e.isVisible(i);!n&&a||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function jh(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(i.source),after:void 0},target:{before:String(i.target),after:void 0},type:{before:i.type,after:void 0},lag:{before:Number(i.lag),after:void 0}},after:null});return t}function Mr(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let a=String(n.source),s=String(n.target);!r.has(a)&&!r.has(s)||(uc(s,a,t)||uc(a,s,t))&&i.push(String(n.id))}return i}function uc(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let a=r.getActivity(i);if(!a)return!1;let s=a.parentId;if(s===null||w(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function fc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let s=i.getActivity(e.activityId);if(!s)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let o=w(e.parentId);if(!o&&!i.getActivity(e.parentId))return{ok:!1,reason:E.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:E.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:E.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let g=i.getActivity(c);if(!g)return{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND};if((g.parentId===null?"0":String(g.parentId))!==e.parentId)return{ok:!1,reason:E.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=qt(l),u=String(e.parentId),f=d!==u,h=new Set([e.activityId]);f?(d!=="0"&&h.add(d),u!=="0"&&h.add(u)):d!=="0"&&h.add(d);let m=await q(i,h);f&&i.setActivityField(e.activityId,b.PARENT,u);let v=Fr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,b.CORRELATIVE_ID,v),f){if(!o){let g=i.getActivity(e.parentId);if(g){let C=g.customId,T=Ft(g.type)&&i.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,S=De({parentId:e.parentId,newChildId:e.activityId,getParent:R=>i.getActivity(R)??null,isCurrentlyLeaf:T,promotionSource:"reparent"});if(S){for(let[R,x]of Object.entries(S.fields))tt(i,S.parentId,R,x);S.promotionSnapshot&&i.setPromotionSnapshot(S.parentId,S.promotionSnapshot),S.fields.customId===null&&xr(C,r.customIdTracker)}}}if(d!=="0"){let g=i.getActivity(d);if(g){let C=i.getChildren(d),T=Te({parent:g,remainingChildIds:C.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(S,R)=>i.calculateEndDate({startDate:S,durationHours:R,task:g}),idsRemoved:new Set([e.activityId])});if(T){for(let[V,G]of Object.entries(T.fields))tt(i,d,V,G);let S=zt(d,i),R=S?i.getActivity(S)?.customId:null,x=typeof R=="string"&&R?R:null,L=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(d,b.CUSTOM_ID,L)}}}}f&&(d!=="0"&&Ot(d,i),o||Ot(e.parentId,i));let A=ct(i);for(let g of A){if(h.add(g.activityId),m.has(g.activityId))continue;let C=i.getActivity(g.activityId);if(!C)continue;let T=J(C);g.before!==void 0&&(T.correlativeId=g.before),m.set(g.activityId,T)}let k=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:D}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:r.now,options:t,recomputeParentProgress:f}),_=f?Mr([e.activityId],i):[],p={name:mt.ACTIVITY_MOVE,properties:{activity_id:e.activityId,new_parent_id:e.parentId,after_sibling_id:e.afterSiblingId??null,before_sibling_id:e.beforeSiblingId??null,invalid_link_ids:_.map(String)}};return e.eventSource!==void 0&&(p.properties.event_source=e.eventSource),{ok:!0,changes:await j(i,{source:e,beforeSnap:m,touchedIds:h,scheduledIds:D,sirDetection:"before-diff",trackingEvents:[p],hoursPerDay:a.hoursPerDay})}}async function pc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:E.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set(s),f=[...e.activityIds].sort((p,g)=>{let C=i.getActivity(p),T=i.getActivity(g),S=C?ot(C):re,R=T?ot(T):re;return S-R});for(let p of f){if(!i.getActivity(p)){c.push({activityId:p,reason:E.ACTIVITY_NOT_FOUND}),u.delete(p);continue}let C=Zn(p,u,i);if(C==null){c.push({activityId:p,reason:E.INDENT_NO_ELIGIBLE_SIBLING}),u.delete(p);continue}let T=i.getActivity(p)?.parentId,S=w(T)?"0":String(T);d.push({activityId:p,newParentId:C,oldParentId:S}),o.add(p),o.add(C),S!=="0"&&o.add(S)}let h=await q(i,o);for(let{activityId:p,newParentId:g}of d)i.setActivityField(p,b.PARENT,g),i.setActivityField(p,b.CORRELATIVE_ID,Qo),l.push(p);let m=new Set;for(let{activityId:p,newParentId:g}of d){if(m.has(g))continue;m.add(g);let C=i.getActivity(g);if(!C)continue;let T=C.customId,S=Ft(C.type)&&i.getChildren(g).filter(L=>!l.includes(L)).length===0,R=C.hasNewActivities&&C.newActivityIds.some(L=>String(L)===String(p)),x=De({parentId:g,newChildId:p,getParent:L=>i.getActivity(L)??null,isCurrentlyLeaf:S,promotionSource:"reparent"});if(x){for(let[L,V]of Object.entries(x.fields))tt(i,x.parentId,L,V);x.promotionSnapshot&&i.setPromotionSnapshot(x.parentId,x.promotionSnapshot),R||(i.setActivityField(g,b.HAS_NEW_ACTIVITIES,!1),i.setActivityField(g,b.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(g,b.CONSTRAINT_TYPE,"asap"),i.setActivityField(g,b.CONSTRAINT_DATE,null),i.setActivityField(g,b.CUSTOM_ID,null),xr(T,r.customIdTracker)}let v=new Set;for(let p of d)p.oldParentId!=="0"&&v.add(p.oldParentId),v.add(p.newParentId);for(let p of v)Ot(p,i);let A=ct(i);for(let p of A){if(o.add(p.activityId),h.has(p.activityId))continue;let g=i.getActivity(p.activityId);if(!g)continue;let C=J(g);p.before!==void 0&&(C.correlativeId=p.before),h.set(p.activityId,C)}let{scheduledIds:k}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),D=Mr(l,i),_={name:mt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(p=>({activity_id:p.activityId,reason:p.reason})),invalid_link_ids:D}};return e.eventSource!==void 0&&(_.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(p=>{let g=c.find(C=>String(C.activityId)===String(p));return g?{activityId:String(p),ok:!1,reason:g.reason}:{activityId:String(p),ok:!0}}),changes:await j(i,{source:e,beforeSnap:h,touchedIds:o,scheduledIds:k,trackingEvents:[_],hoursPerDay:a.hoursPerDay})}}async function hc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:E.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let p of e.activityIds){let g=p;i.getActivity(g)&&(o.set(g,pi(g,i)),c.set(g,tc(g,s,i)))}let l=new Set,d=[],u=[],f=new Set,h=[],m=[...e.activityIds].sort((p,g)=>{let C=i.getActivity(p),T=i.getActivity(g),S=C?ot(C):re,R=T?ot(T):re;return S-R});for(let p of m){let g=p,C=i.getActivity(g);if(!C){d.push({activityId:g,reason:E.ACTIVITY_NOT_FOUND});continue}let T=C.parentId;if(w(T)){d.push({activityId:g,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let S=String(T),R=i.getActivity(S);if(!R){d.push({activityId:g,reason:E.ACTIVITY_NOT_FOUND});continue}let x=R.parentId;if(w(x)){d.push({activityId:g,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let L=String(x),V=pi(S,i)+1,G=c.get(g);if(G!=null&&s.has(G)){let vt=o.get(G)??-1,Ee=o.get(g)??-1;vt>=0&&Ee>=0&&(V+=Ee-vt)}h.push({activityId:g,grandparentKey:L,oldParentKey:S,targetIndexInGrandparent:V}),l.add(String(g)),l.add(String(S)),L!=="0"&&l.add(String(L)),f.add(S)}let v=await q(i,l);for(let p of h){i.setActivityField(p.activityId,b.PARENT,p.grandparentKey);let g=ec(i,p.grandparentKey,p.targetIndexInGrandparent,p.activityId);i.setActivityField(p.activityId,b.CORRELATIVE_ID,g),u.push(p.activityId)}for(let p of f){let g=i.getActivity(p);if(!g)continue;let C=i.getChildren(p),T=Te({parent:g,remainingChildIds:C.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(p),computeEndDate:(V,G)=>i.calculateEndDate({startDate:V,durationHours:G,task:g}),idsRemoved:new Set(h.filter(V=>V.oldParentKey===p).map(V=>V.activityId))});if(!T){hr(p,i);continue}for(let[V,G]of Object.entries(T.fields))tt(i,p,V,G);let S=zt(p,i),R=S?i.getActivity(S)?.customId:null,x=typeof R=="string"&&R?R:null,L=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(p,b.CUSTOM_ID,L)}let A=new Set;for(let p of f)A.add(String(p));for(let p of h)p.grandparentKey!=="0"&&A.add(String(p.grandparentKey));for(let p of A)Ot(p,i);let k=ct(i);for(let p of k){if(l.add(p.activityId),v.has(p.activityId))continue;let g=i.getActivity(p.activityId);if(!g)continue;let C=J(g);p.before!==void 0&&(C.correlativeId=p.before),v.set(p.activityId,C)}let{scheduledIds:D}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),_={name:mt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(p=>({activity_id:String(p.activityId),reason:p.reason}))}};return e.eventSource!==void 0&&(_.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(p=>{let g=d.find(C=>String(C.activityId)===String(p));return g?{activityId:String(p),ok:!1,reason:g.reason}:{activityId:String(p),ok:!0}}),changes:await j(i,{source:e,beforeSnap:v,touchedIds:l,scheduledIds:D,trackingEvents:[_],hoursPerDay:a.hoursPerDay})}}async function yc(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:E.INVALID_PROGRESS_VALUE};let o=n.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let c=jt(P.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,n,e.newValue),d=Vt(e.activityId,l),u=await q(i,d);Yt(i,e.activityId,l),Ut(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await $({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:m=>Sr(e.activityId,d,m),now:r.now,options:t}),h=(l.trackingEvents??[]).map(m=>({name:m.name,properties:m.properties??{}}));return{ok:!0,changes:await j(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function mc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let m of e.edits){let v=Vh(m,r);if(s.push(v.verdict),!v.verdict.ok||!v.changes)continue;let A=Vt(m.activityId,v.changes);Yh(o,A,r);for(let p of A)c.add(p);let k=Se(i,m.activityId),D=Ir(i,String(m.activityId));Yt(i,m.activityId,v.changes),Ut(m.activityId,v.changes.postProcessors??[],i,D),d.push(...ke(k,i,m.activityId)),f||=!!v.changes.needsAutoSchedule;for(let p of v.changes.trackingEvents??[])l.push({name:p.name,properties:p.properties??{}});let _=Ce(m.activityId,v.changes.constraintWarning);_&&u.push(_)}let{scheduledIds:h}=await $({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f?"roots":null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:s,changes:await j(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:h,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Vh(e,t){let{ctx:r}=t,i=e.activityId,n=jt(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let a=r.activityReader.getActivity(e.activityId);if(!a)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??E.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??E.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??E.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Yh(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let n of i){let a=r.adapter.getActivity(n);a&&e.set(n,J(a))}}var pn=P.CUSTOM_ID;async function gc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(_=>_.column===P.DURATION)&&n.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],h=[],m=[],v=!1;for(let _ of e.edits){let p=Kh(_,r);if(o.push(p.verdict),!p.verdict.ok||!p.changes)continue;let g=Ce(_.activityId,p.changes.constraintWarning);g&&m.push(g);let C=Vt(_.activityId,p.changes);qh(c,C,r);for(let L of C)u.add(L);zh(l,_,c),br(_.column)&&d.add(String(_.activityId));let T=Se(i,_.activityId),S=Ir(i,String(_.activityId)),R=$h(_,r),x=p.changes;Yt(i,_.activityId,x),Ut(_.activityId,p.changes.postProcessors??[],i,S),Gh(_,R,r),h.push(...ke(T,i,_.activityId)),v||=!!p.changes.needsAutoSchedule;for(let L of p.changes.trackingEvents??[])f.push({name:L.name,properties:L.properties??{}})}let A={action:e,autoscheduleFrom:v?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},k=l.size>0,{scheduledIds:D}=await(k?wr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:A,revertTargets:[...l].filter(([_])=>!d.has(_)).map(([_,p])=>({activityId:_,priorConstraintDate:p})),revert:(_,p)=>Lr(_,p,i,r.ctx.calendars)}):$({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},A));return{ok:!0,verdicts:o,changes:await j(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:D,sirDetection:"before-diff",links:h,trackingEvents:f,warnings:m,hoursPerDay:a.hoursPerDay})}}function Kh(e,t){let{ctx:r}=t,i=e.activityId,n=jt(e.column);if(!n)return{verdict:{activityId:i,ok:!1,reason:E.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:i,ok:!1,reason:E.ACTIVITY_NOT_FOUND},changes:null};let s=n.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:i,ok:!1,reason:s.reason??E.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=n.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:i,ok:!1,reason:o.reason??E.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??E.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===pn&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,h=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),h))return{verdict:{activityId:i,ok:!1,reason:E.CUSTOM_ID_DUPLICATE},changes:null}}let d=n.transform(a,o.value,r,o.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function $h(e,t){if(e.column!==pn)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function Gh(e,t,r){if(e.column!==pn)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,a=typeof n=="string"?n:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function zh(e,t,r){if(!Rr(t.column))return;let i=String(t.activityId);if(e.has(i))return;let n=r.get(i);n&&e.set(i,n.constraintDate??null)}function qh(e,t,r){let i=new Set;for(let n of t)e.has(n)||i.add(n);if(i.size!==0)for(let n of i){let a=r.adapter.getActivity(n);a&&e.set(n,J(a))}}function Jh(e,t,r,i,n,a){let s=String(e.id);if(s.length===0||n.has(s))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${s}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let o=r(s);if(!o.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${s}"`);if(o.current!==null&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(s),a.add(e.proplannerId)}function vc(e,t,r,i){let n=new Set,a=new Set;for(let s of e)Jh(s,t,r,i,n,a)}function Ac(e,t){let r=e.activities??[],i=e.links??[],n=new Map;for(let c of t.adapter.getAllActivities())c.proplannerId!=null&&n.set(c.proplannerId,String(c.id));let a=new Map;for(let c of t.adapter.getAllLinks())c.proplannerId!=null&&a.set(c.proplannerId,String(c.id));vc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},n),vc(i,"link",c=>{let l=t.adapter.getLink(c);return{exists:l!==null,current:l?.proplannerId??null}},a);let s=[],o=[];return t.adapter.batchUpdate(()=>{for(let c of r){let l=t.adapter.getActivity(c.id);!l||l.proplannerId===c.proplannerId||(t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:l.proplannerId,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}}))}for(let c of i){let l=t.adapter.getLink(c.id);!l||l.proplannerId===c.proplannerId||(t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:l.proplannerId,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}}))}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function Cc(e){return typeof e=="string"&&e.length>0?Lt(e):e instanceof Date?e:null}function hn(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function Wr(e,t){let r=hn(e.duration),i=hn(e.cost),n=hn(e.hh_work);return r===null||i===null||n===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:Cc(e.start_date),endDate:Cc(e.end_date),durationDays:r,cost:i,workHours:n,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Ic(e,t,r){let i=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&i.set(c,o)});let n=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=i.get(o);if(c===void 0)continue;let l=n.get(c);l?l.push(s):n.set(c,[s])}let a=[];for(let[s,o]of n)e.setActivityField(s,"baselinePoints",o.map(c=>Wr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(n.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function Xh(e){let t=it(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Sc(e){let t=[];return e.forEachActivity((r,i)=>{let n=Xh(r);if(!n){r.baselineSnapshot!==null&&(e.setActivityField(i,"baselineSnapshot",null),t.push(i));return}e.setActivityField(i,"baselineSnapshot",n),t.push(i)}),t}function Ur(e,t,r,i,n=null){let a=new Set;for(let s of Ic(e,t,i))a.add(s);if(r)for(let s of Kt(e,r,n))a.add(s);for(let s of Sc(e))a.add(s);for(let s of Gt(e))a.add(s);return[...a]}function kc(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,a=0;for(let o of i){let c=Zh(String(o),t,r);n.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of i){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(it(c)){let u=n.get(String(o))??0;r.setActivityField(o,P.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,P.PONDERATOR,0)}}function Zh(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=it(i);if(!n)return 0;if(t==="COST")return Br(n.cost);if(t==="HH")return Br(n.workHours);let a=i.type;return a==="project"?Dc(e,r):a==="milestone"?0:Br(n.durationDays)}function Dc(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=it(n);if(!a)continue;let s=n.type;s==="project"?r+=Dc(String(i),t):s!=="milestone"&&(r+=Br(a.durationDays))}return r}function Br(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Tc(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,P.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&kc(String(i),e,t)})}function Hr(e){for(let t of Qh(e))ey(t,e)}function Qh(e){let t=new Set;e.forEachActivity((i,n)=>{e.getChildren(n).length>0&&t.add(n)});let r=new Map;for(let i of t)r.set(i,ty(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function ty(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ey(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let a of r){let s=t.getActivity(a);s&&i.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let n=fe(i);n!==null&&t.setActivityField(e,P.PROGRESS,pr(n))}function jr(e,t){Tc(t,e.adapter),Hr(e.adapter),e.now&&(Kt(e.adapter,e.now,e.defaultBaseCalendarId??null),wt(e.adapter,e.now)),Gt(e.adapter),e.now&&St(e.adapter,e.sector.statusCriteria)}function _c(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(i=>i.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}async function Pc(e,t){let r=await q(t.adapter,new Set(t.adapter.getAllIds())),i=_c(t),n=Ur(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return _c(t)!==i&&jr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await j(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function ry(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function Ec(e,t){ry(e.criterion);let r=new Set(t.adapter.getAllIds()),i=await q(t.adapter,r);return jr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await j(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Rc(e,t){let r=Ze(e.criteria),i=new Set(t.adapter.getAllIds()),n=await q(t.adapter,i),a=St(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await j(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function bc(e,t,r){return e.kind==="persistence-acknowledge"?Ac(e,r):e.kind==="baseline-apply"?Pc(e,r):e.kind==="ponderator-criterion-set"?Ec(e,r):e.kind==="status-criteria-set"?Rc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Bo(e,t,r):e.kind==="links-batch"?Ho(e,t,r):e.kind==="activity-create"?rc(e,t,r):e.kind==="activity-paste"?ic(e,t,r):e.kind==="activity-delete"?dc(e,t,r):e.kind==="activity-move"?fc(e,t,r):e.kind==="activity-indent"?pc(e,t,r):e.kind==="activity-outdent"?hc(e,t,r):e.kind==="activity-set-progress"?yc(e,t,r):e.kind==="dates-batch"?mc(e,t,r):e.kind==="bulk-edit"?gc(e,t,r):e.kind==="selection-toggle"?jn(e,yn(r)):e.kind==="selection-replace"?Vn(e,yn(r)):e.kind==="visibility-set"?Yn(e,yn(r)):e.kind==="filter-set"?qn(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?ta(e,{adapter:r.adapter}):e.kind==="sir-sync"?nc(e,r):e.kind==="activity-lookahead-sync"?ac(e,r):e.kind==="inline-edit"&&(e.column===P.CUSTOM_PREDECESSORS||e.column===P.CUSTOM_SUCESSORS)?jo(e,t,r):e.kind!=="inline-edit"?Ua(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Uo(e,t,r)}function yn(e){return{adapter:e.adapter}}var iy=new Set(["startDate","endDate","constraintDate"]);function Lc(e,t){return iy.has(e)&&typeof t=="string"?new Date(t):t}function wc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?ny(n,r):null}}}function ny(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,i){return e.calculateEndDate({start_date:r,duration:i,unit:t})},calculateDuration(r,i){return e.calculateDuration({start_date:r,end_date:i,unit:t})},isWorkTime(r,i){return e.isWorkTime({date:r,unit:i})},getWorkHours(r){return e.getWorkHours(r)}}}function ay(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ie(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function ne(e){return ie(e)&&!isNaN(e.getTime())}var sy={}.constructor.toString();function oy(e){var t=e.constructor.toString();return t!==sy}function cy(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Dt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ie(e):r=new Date(e);break;case ay(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Dt(e[t]);break;default:if(oy(e))r=Object.create(e);else{if(cy(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Dt(e[t]));break}return r||e}function _e(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function Oc(e){return typeof e<"u"}var Vr;function mn(){return Vr||(Vr=new Date().valueOf()),Vr++,Vr}function ft(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var dy=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return`"+to_fixed(date.get${t?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${t?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${t?"UTC":""}Date()+"`;case"%n":return`"+(date.get${t?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${t?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${t?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${t?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${t?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${t?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${t?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${t?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${t?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${t?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${t?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${t?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${t?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${t?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return n}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return n=>i(n,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},uy=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let o=0;o<n.length;o++)switch(n[o]){case"%j":case"%d":i+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${o}]||0;`;break;case"%i":i+=`set[4]=temp[${o}]||0;`;break;case"%Y":i+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${o}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let s=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return o=>s(o,r.locale)},xc={date_to_str:dy,str_to_date:uy},fy=(e,t,r)=>i=>e.replace(/%[a-zA-Z]/g,n=>{switch(n){case"%d":return t?r.date.to_fixed(i.getUTCDate()):r.date.to_fixed(i.getDate());case"%m":return t?r.date.to_fixed(i.getUTCMonth()+1):r.date.to_fixed(i.getMonth()+1);case"%j":return t?i.getUTCDate():i.getDate();case"%n":return t?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return t?r.date.to_fixed(i.getUTCFullYear()%100):r.date.to_fixed(i.getFullYear()%100);case"%Y":return t?i.getUTCFullYear():i.getFullYear();case"%D":return t?r.locale.date.day_short[i.getUTCDay()]:r.locale.date.day_short[i.getDay()];case"%l":return t?r.locale.date.day_full[i.getUTCDay()]:r.locale.date.day_full[i.getDay()];case"%M":return t?r.locale.date.month_short[i.getUTCMonth()]:r.locale.date.month_short[i.getMonth()];case"%F":return t?r.locale.date.month_full[i.getUTCMonth()]:r.locale.date.month_full[i.getMonth()];case"%h":return t?r.date.to_fixed((i.getUTCHours()+11)%12+1):r.date.to_fixed((i.getHours()+11)%12+1);case"%g":return t?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return t?i.getUTCHours():i.getHours();case"%H":return t?r.date.to_fixed(i.getUTCHours()):r.date.to_fixed(i.getHours());case"%i":return t?r.date.to_fixed(i.getUTCMinutes()):r.date.to_fixed(i.getMinutes());case"%a":return t?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return t?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(i.getUTCSeconds()):r.date.to_fixed(i.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(i)):r.date.to_fixed(r.date.getISOWeek(i));case"%w":return r.date.to_fixed(r.date.getWeek(i));default:return n}}),py=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),s=e.match(/%[a-zA-Z]/g);for(let o=0;o<s.length;o++)switch(s[o]){case"%j":case"%d":n[2]=a[o]||1;break;case"%n":case"%m":n[1]=(a[o]||1)-1;break;case"%y":n[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[o]||0;break;case"%i":n[4]=a[o]||0;break;case"%Y":n[0]=a[o]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[o]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(n[0],n[1],n[2],n[3],n[4],n[5])):new Date(n[0],n[1],n[2],n[3],n[4],n[5])},Nc={date_to_str:fy,str_to_date:py};function Fc(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var o=!1;return e.config.csp==="auto"?(i===null&&n(),o=i):o=e.config.csp,o}var s={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=xc;return a()&&(l=Nc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=xc;return a()&&(l=Nc),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),h=1+Math.floor(f/7);return h},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=r(o);if(f)return s._isoDateDetected?u&&(s._isoDateOnly=!1):(s._isoDateDetected=!0,s._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return s}function gn(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function vn(e,t,r,i,n,a){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=a,this}function An(e,t,r,i,n,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=s,this}function hy(e,t,r,i){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=i,this.unit=null,this.step=null,this}var Mc=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ie(t)?t={date:t}:t=_e({},t),!ne(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof gn)return t;var r;if(t.date?r=new gn(t.date,t.unit,t.task,null,t.calendar):r=new gn(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!ne(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof vn)return r;var i;if(ie(r)?i=new vn(r):i=new vn(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(i.task=r),i.dir=r.dir||"any",i.unit=r.unit||e.config.duration_unit,!ne(i.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(t){var r=hy,i;if(t instanceof r)return t;if(ie(t)?i=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(i.task=t)),i.unit=i.unit||e.config.duration_unit,i.step=i.step||e.config.duration_step,i.start_date=i.start_date||i.start||i.date,!ne(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!ne(i.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,i,n){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,i,n){var a=arguments[0];if(a instanceof An)return a;var s;if(ie(a)?s=new An(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new An(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(s.task=a,s.unit=null,s.step=null),s.unit=s.unit||e.config.duration_unit,s.step=s.step||e.config.duration_step,!ne(s.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return s}}};function Wc(){}Wc.prototype={_getIntervals:function(e){for(var t=[],r=0;r<e.length;r+=2)t.push({start:e[r],end:e[r+1]});return t},_toHoursArray:function(e){var t=[];function r(a){var s=String(a);return s.length<2&&(s="0"+s),s}function i(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var n=0;n<e.length;n++)t.push(i(e[n].start)+"-"+i(e[n].end));return t},_intersectHourRanges:function(e,t){var n=[],r=e.length>t.length?e:t,i=e===r?t:e;r=r.slice(),i=i.slice();for(var n=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<i.length;o++){var c=i[o];c.start<s.end&&c.end>s.start&&(n.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(i.splice(o,1),o--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],i=1;i<t.length;i++){var n=t[i];n.start<=r.end?(n.end>r.end&&(r.end=n.end),t.splice(i,1),i--):r=n}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=Dt(e.getConfig()),i=Dt(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let o=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(s.dates[u]=!1);for(let h in d.dates){let m=d.dates[h];if(h==u&&(s.dates[u]=!!(f&&m)),Array.isArray(f)){let v=Array.isArray(m)?m:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,v))}}}};if(o(n,a),o(a,n),n.customWeeks)for(var c in n.customWeeks)s.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)s.customWeeks[c]?s.customWeeks[c+"_second"]=a.customWeeks[c]:s.customWeeks[c]=a.customWeeks[c];return s}};var Cn=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let a=this._cache.get(t)[i.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache,s=n.getUTCFullYear(),o;a.has(t)?o=a.get(t):(o=[],a.set(t,o));let c=o[s];c||(c=o[s]=new Map),c.set(r,i)}clear(){this._cache=new Map}},In=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let a=n[t];if(a===void 0)return-1;let s=a[i.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=n.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=i}clear(){this._cache={}}},Sn=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(i,s),s},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r)),c=a.date.add(o,1,"month").valueOf();for(;o.valueOf()<c;)s+=n.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(i,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function yy(){return typeof Map<"u"?new Cn:new In}var kn=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let a=n[r];a||(a=n[r]={});let s=a[i];s||(s=a[i]={});let o=t.getUTCFullYear(),c=s[o];return c||(c=s[o]={durations:{},endDates:{}}),c}_endDateCacheKey(t,r){return String(t)+"-"+String(r)}_durationCacheKey(t,r){return String(t)+"-"+String(r)}getEndDate(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=this._endDateCacheKey(o,r),l;if(s.endDates[c]===void 0){let d=a(),u=d.valueOf();s.endDates[c]=u,s.durations[this._durationCacheKey(o,u)]=r,l=d}else l=new Date(s.endDates[c]);return l}getDuration(t,r,i,n,a){let s=this._getCacheObject(t,i,n),o=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(o,c),d;if(s.durations[l]===void 0){let u=a();s.durations[l]=u.valueOf(),d=u}else d=s.durations[l];return d}clear(){this._cache={}}};function Dn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=yy(),this._largeUnitsCache=new Sn(this),this._dateDurationCache=new kn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Dn.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(e){for(var t=0,r=this.units.length;t<r;t++)if(this.units[t]==e)return t},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(e){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var t=null;if(e.day||e.day===0)t=e.day;else if(e.date){var r=String(e.date.valueOf());this._cached_timestamps[r]?t=this._cached_timestamps[r]:(t=Date.UTC(e.date.getUTCFullYear(),e.date.getUTCMonth(),e.date.getUTCDate()),this._cached_timestamps[r]=t,this._cached_timestamps_count++)}return t},_checkIfWorkingUnit:function(e,t){if(!this["_is_work_"+t]){let r=this.$gantt.date[`${t}_start`](new Date(e)),i=this.$gantt.date.add(r,1,t);return this.hasDuration(r,i)}return this["_is_work_"+t](e)},_is_work_day:function(e){var t=this._getWorkHours(e);return Array.isArray(t)?t.length>0:!1},_is_work_hour:function(e){for(var t=this._getWorkHours(e),r=e.getUTCHours(),i=0;i<t.length;i++)if(r>=t[i].startHour&&r<t[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(e,t){var r=e.getUTCHours();return!e.getUTCHours()&&!e.getUTCMinutes()&&t&&(r=24),r*60*60+e.getUTCMinutes()*60},_is_work_minute:function(e){for(var t=this._getWorkHours(e),r=this._getTimeOfDayStamp(e),i=0;i<t.length;i++)if(r>=t[i].start&&r<t[i].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,i){var n=this.$gantt.date,a=new Date(e),s=new Date(t);i=i||1;var o=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(f=!0);for(var h=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),h=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&h)&&(l=n[r+"_start"](new Date(a)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),o+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&h?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var m=this._getUnitOrder(r),v=this.units[m-1];v&&!this._isWorkTime(a,v)&&(c=this._getClosestWorkTimeFuture(a,v))}a=c}return o},_getMinutesPerHour:function(e){var t=this._getTimeOfDayStamp(e),r=this._getTimeOfDayStamp(this._nextDate(e,"hour",1));r===0&&(r=1440*60);for(var i=this._getWorkHours(e),n=0;n<i.length;n++){var a=i[n];if(t>=a.start&&r<=a.end)return 60;if(t<a.end&&r>a.start){var s=Math.min(r,a.end)-Math.max(t,a.start);return s/60}}return 0},_getMinutesPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(i){r+=i.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,i){var n=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=ft(this._getMinutesPerDay,this):o=ft(this.getHoursPerDay,this);a.valueOf()<s.valueOf();){if(s-a>1e3*60*60*24*32&&a.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,1,"month");continue}else if(s-a>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(a);r=="hour"&&(c=c/60),n+=c,a=this.$gantt.date.add(a,7,"day");continue}}n+=o(a),a=this._nextDate(a,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,a=0;a<i.length;a++){var s=i[a];if(r.end>=s.start&&r.start<=s.end){var o=Math.max(s.start,r.start),c=Math.min(s.end,r.end);n+=(c-o)/60,r.start=c}}return Math.floor(n)},_getMinutesBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(o,c,r,i),h=d+f+u;return h},_getHoursBetween:function(e,t,r,i){var n=new Date(e),a=new Date(t);i=i||1;var s=new Date(n),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=o.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(s,o,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(o,c,r,i),h=d+f+u;return Math.round(h)},getConfig:function(){return this._worktime},_setConfig:function(e){this._worktime=e,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var e=this.getConfig();e.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},e.parsed.hours=this._parseHours(e.hours);for(var t in e.dates)e.parsed.dates[t]=this._parseHours(e.dates[t]);if(e.customWeeks){var r=null,i=null;for(var t in e.customWeeks){var n=e.customWeeks[t];if(n.from&&n.to){var a=n.from,s=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<s.valueOf())&&(i=s.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:s.valueOf(),toReadable:new Date(s),name:t}),e.parsed.haveCustomWeeks=!0;var o=e.parsed.customWeeks[t]={from:n.from,to:n.to,hours:this._parseHours(n.hours),dates:{}};if(n.days&&!n.dates){n.dates=n.dates||{};for(var t=0;t<n.days.length;t++)n.dates[t]=n.days[t],n.days[t]instanceof Array||(n.dates[t]=!!n.days[t]);delete n.days}for(var c in n.dates)o.dates[c]=this._parseHours(n.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(e){var t=JSON.stringify(this.getConfig());return e(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(t)),this._clearCaches(),!1)},_arraysEqual:function(e,t){if(e===t)return!0;if(!e||!t||e.length!=t.length)return!1;for(var r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0},_compareSettings:function(e,t){if(!this._arraysEqual(e.hours,t.hours))return!1;var r=Object.keys(e.dates),i=Object.keys(t.dates);if(r.sort(),i.sort(),!this._arraysEqual(r,i))return!1;for(var n=0;n<r.length;n++){var a=r[n],s=e.dates[a],o=t.dates[a];if(s!==o&&!(Array.isArray(s)&&Array.isArray(o)&&this._arraysEqual(s,o)))return!1}return!0},equals:function(e){if(!(e instanceof Dn))return!1;var t=this.getConfig(),r=e.getConfig();if(!this._compareSettings(t,r))return!1;if(t.parsed.haveCustomWeeks&&r.parsed.haveCustomWeeks){if(t.parsed.customWeeksBoundaries.length!=r.parsed.customWeeksBoundaries.length)return!1;for(var i in t.parsed.customWeeks){var n=t.parsed.customWeeks[i],a=r.parsed.customWeeks[i];if(!a||!this._compareSettings(n,a))return!1}}else if(t.parse.haveCustomWeeks!==r.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(e.date,!1)},_getWorkHours:function(e,t){var r=this.getConfig();if(t!==!1&&(r=r.parsed),!e)return r.hours;let i=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var n=this._timestamp({date:i});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=n&&r.customWeeksRangeEnd>n){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=n&&r.customWeeksBoundaries[a].to>n){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[n]!==void 0?s=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(s=r.dates[e.getUTCDay()]),s===!0?r.hours:s||[]},_getIntervalTimestamp:function(e,t){var r={start:0,end:0};r.start=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds();var i=t.getUTCHours();return!i&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(i=24),r.end=i*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),r},_parseHours:function(e){if(Array.isArray(e)){var t=[];e.forEach(function(o){typeof o=="number"?t.push(o*60*60):typeof o=="string"&&o.split("-").map(function(c){return c.trim()}).forEach(function(c){var l=c.split(":").map(function(u){return u.trim()}),d=parseInt(l[0]*60*60);l[1]&&(d+=parseInt(l[1]*60)),l[2]&&(d+=parseInt(l[2])),t.push(d)})});for(var r=[],i=0;i<t.length;i+=2){var n=t[i],a=t[i+1],s=a-n;r.push({start:n,end:a,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(ft(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(ft(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&i==1?n=this._getHoursBetween(e,t,r,i):r=="minute"&&i==1?n=this._getMinutesBetween(e,t,r,i):n=this._getWorkUnitsBetweenGeneric(e,t,r,i),a*Math.round(n)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;if(!i)return!1;var a=new Date(t),s=new Date(r);for(n=n||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,n)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;if(!i)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return s._calculateEndDate(t,r,i,n*a)})},_calculateEndDate:function(e,t,r,i){if(!r)return!1;if(i==1&&r=="minute")return this._calculateMinuteEndDate(e,t,i);if(i==-1&&r=="minute")return this._subtractMinuteDate(e,t,i);if(i==1&&r=="hour")return this._calculateHourEndDate(e,t,i);var n=this._addInterval(e,t,r,i,null);return n.end},_addInterval:function(e,t,r,i,n){for(var a=0,s=e;a<t&&!(n&&n(s));){var o=this._nextDate(s,r,i),c=new Date(o.valueOf()+1);i>0&&(c=new Date(o.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,s=o}return{end:s,start:e,added:a}},_addHoursUntilDayEnd:function(e,t){for(var r=this.$gantt.date.add(this.$gantt.date.day_start(new Date(e)),1,"day"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var f=Math.round((d-l)/3600);i+=f,n-=f,a.start=d}}var h=r;return i===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:h}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(i,t);n=a.added,i=a.end;var s=t-n;if(s){for(var o=i;n<t;){var c=this._nextDate(o,"day",r);c.setUTCHours(0),c.setUTCMinutes(0),c.setUTCSeconds(0);var l=0;if(r>0?l=this.getHoursPerDay(new Date(c.valueOf()-1)):l=this.getHoursPerDay(new Date(c.valueOf()+1)),n+l>=t)break;n+=l,o=c}i=o}if(n<t){var s=t-n;a=this._addHoursUntilDayEnd(i,s),i=a.end}return i},_addMinutesUntilHourEnd:function(e,t){if(e.getUTCMinutes()===0)return{added:0,end:new Date(e)};for(var r=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(e)),1,"hour"),i=0,n=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&i<t;o++){var c=s[o];if(a.end>=c.start&&a.start<=c.end){var l=Math.max(c.start,a.start),d=Math.min(c.end,a.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var f=Math.round((d-l)/60);n-=f,i+=f,a.start=d}}var h=r;return i===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:h}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,a=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),s=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),o=this._getWorkHours(e),c=o.length-1;c>=0&&i<t;c--){var l=o[c];if(s>l.start&&a<=l.end){var d=Math.min(s,l.end),u=Math.max(a,l.start),f=(d-u)/60;f>n&&(f=n,u=d-n*60);var h=Math.abs(Math.round((d-u)/60));n-=h,i+=h,s=u}}var m=r;return i===t&&(m=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:i,end:m}},_subtractMinuteDate:function(e,t,r){var i=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),n=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(i),s=this._subtractMinutesUntilHourStart(i,t);n+=s.added,i=s.end;for(var o=0,c=[],l=0;n<t;){var d=this.$gantt.date.day_start(new Date(i)),u=!1;i.valueOf()===d.valueOf()&&(d=this.$gantt.date.add(d,-1,"day"),u=!0);var f=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();f!==o&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),o=f);var h=t-n,m=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=m&&h>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var v=!1,A=null,k=null,D=c.length-1;D>=0;D--)if(c[D].start<m-1&&c[D].end>=m-1){v=!0,A=c[D],k=c[D-1];break}if(v)if(m===A.end&&h>=A.durationMinutes)n+=A.durationMinutes,i=this.$gantt.date.add(i,-A.durationMinutes,"minute");else if(!a&&h<=m/60-A.startMinute)n+=h,i=this.$gantt.date.add(i,-h,"minute");else if(a)h<=m/60-A.startMinute?(n+=h,i=this.$gantt.date.add(i,-h,"minute")):(n+=m/60-A.startMinute,k?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,k.end)):i=this.$gantt.date.day_start(i));else{var _=this._getMinutesPerHour(i);_<=h?(n+=_,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,h),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var p=this._getClosestWorkTimePast(i,"hour");if(p.valueOf()===i.valueOf()){var p=this.$gantt.date.add(i,-1,"day"),g=this._getWorkHours(p);if(g.length){var C=g[g.length-1];p.setUTCSeconds(C.durationSeconds)}}i=p}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var T=t-n;s=this._subtractMinutesUntilHourStart(i,T),n+=s.added,i=s.end}return i},_calculateMinuteEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(i,t);n+=a.added,i=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==s&&(o=this._getWorkHours(i),c=this._getMinutesPerDay(i),s=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!o.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(o[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o[o.length-1].end));break}else i=this.$gantt.date.add(i,1,"day"),i=this.$gantt.date.day_start(i);continue}for(var h=!1,m=null,v=0;v<o.length;v++)if(o[v].start<=f&&o[v].end>f){h=!0,m=o[v];break}if(h)if(f===m.start&&u>=m.durationMinutes)n+=m.durationMinutes,i=this.$gantt.date.add(i,m.durationMinutes,"minute");else if(u<=m.endMinute-f/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var A=this._getMinutesPerHour(i);A<=u?(n+=A,l?i=this.$gantt.date.add(i,A,"minute"):i=this._nextDate(i,"hour",r)):(a=this._addMinutesUntilHourEnd(i,u),n+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var k=t-n;a=this._addMinutesUntilHourEnd(i,k),n+=a.added,i=a.end}return i},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var i=new Date(e);if(this._isWorkTime(i,t))return i;if(i=this.$gantt.date[t+"_start"](i),r=="any"||!r){var n=this._getClosestWorkTimeFuture(i,t),a=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-a)?i=n:i=a}else r=="past"?i=this._getClosestWorkTimePast(i,t):i=this._getClosestWorkTimeFuture(i,t);return i},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var i=new Date(e),n=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),a=!0),r=this._getWorkHours(i));var s=this._getTimeOfDayStamp(i);if(a&&(s=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n);return a||(r>0?(i=this.calculateEndDate(i,r,t),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,r,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),n=this._getWorkHours(i),a=this._findClosestTimeInDay(i,r,n)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var i=this._getUnitOrder(t),n=this.units[i-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(n&&!this._isWorkTime(a,n)&&(r>0?a=this._getClosestWorkTimeFuture(a,n):a=this._getClosestWorkTimePast(a,n),this._isWorkTime(a,t)));){if(o++,o>s)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var i in e.dates);var n=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=n:Array.isArray(o)&&(a=this._checkWorkHours(o))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var je={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var i in e){r=i;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var i=t[r];if(e[r]){var n=i[e[r]];if(n)return n}}return null}};function my(){function e(n){return n.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(n,a){return a.mergeCalendars(n.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function i(n,a){var s=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(n,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:i}}var gy=my();function Uc(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=je.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}Uc.prototype={_calendars:{},_convertWorkTimeSettings:function(e){let t=e.days;if(typeof t=="object"&&!Array.isArray(t)&&t!==null){let r={};if(t?.weekdays)for(let i=0;i<7;i++)r[i]=t.weekdays[i];t?.dates&&Object.entries(t.dates).forEach(([i,n])=>{r[new Date(i).valueOf()]=n}),Object.entries(r).forEach(([i,n])=>{n instanceof Array||(r[i]=!!n)}),e={...e,dates:r}}else if(t&&!e.dates){e.dates=e.dates||{};for(let r=0;r<t.length;r++)e.dates[r]=t[r],t[r]instanceof Array||(e.dates[r]=!!t[r])}return delete e.days,e},mergeCalendars:function(){var e=[],t=arguments;if(Array.isArray(t[0]))e=t[0].slice();else for(var r=0;r<arguments.length;r++)e.push(arguments[r]);var i=new Wc,n;return e.forEach((function(a){n?n=this._createCalendarFromConfig(i.merge(n,a)):n=a}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new Dn(this.$gantt,Mc(this.$gantt));t.id=String(mn());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var i in r.customWeeks)r.customWeeks[i]=this._convertWorkTimeSettings(r.customWeeks[i]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Dt(e.getConfig()):e.worktime?t=Dt(e.worktime):t=Dt(e);var r=Dt(this.defaults.fulltime.worktime);return _e(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,i,n;if(this._legacyConfig===!1?n=t.resource_property:n=je.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=gy.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=je.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=je.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(n&&e[n]&&t.resource_calendars[e[n]])var r=this.getResourceCalendar(e[n]);if(i&&(r=this.getCalendar(i)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,i=r.resource_calendars,n=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=je.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][t]){n=i[a][t];break}}else var n=i[t];if(n)return this.getCalendar(n)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var i=this._getOwnCalendar(r),n=!!t.getState().group_mode;if(!i&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););n&&!i&&e.$effective_calendar&&(i=this.getCalendar(e.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||mn(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],i=this.createCalendar(r);i.id=t,this.addCalendar(i)}},defaults:{global:{id:"global",worktime:{hours:[8,12,13,17],days:[0,1,1,1,1,1,0]}},fulltime:{id:"fulltime",worktime:{hours:[0,24],days:[1,1,1,1,1,1,1]}}},createDefaultCalendars:function(){var e=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(e.worktimes)},isCalendar:function(e){var t=[e.isWorkTime,e.setWorkTime,e.getWorkHours,e.unsetWorkTime,e.getClosestWorkTime,e.calculateDuration,e.hasDuration,e.calculateEndDate];return t.every(function(r){return r instanceof Function})}};function Tn(e,t){this.argumentsHelper=t,this.$gantt=e}Tn.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(t){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return t.date},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit,n=e.step;return this._calculateDuration(t,r,i,n)},_calculateDuration:function(e,t,r,i){var n=this.$gantt.date,a={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},s=0;if(a[r])s=Math.round((t-e)/(i*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=n.add(o,i,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(n.add(o,i,r)-o))}return Math.round(s)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,i=e.unit;return i?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Tn},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,i=e.unit,n=e.step;return this.$gantt.date.add(t,n*r,i)}};function Bc(e){this.$gantt=e.$gantt,this.argumentsHelper=Mc(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Tn(this.$gantt,this.argumentsHelper)}Bc.prototype={_getCalendar:function(e){var t;if(!this.$gantt.config.work_time)t=this.$disabledCalendar;else{var r=this.calendarManager;e.task?t=r.getTaskCalendar(e.task):e.id?t=r.getTaskCalendar(e):e.calendar&&(t=e.calendar),t||(t=r.getTaskCalendar())}return t},getWorkHours:function(e){e=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getWorkHours(e.date)},setWorkTime:function(e,t){return e=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.setWorkTime(e)},unsetWorkTime:function(e,t){return e=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),t||(t=this.calendarManager.getCalendar()),t.unsetWorkTime(e)},isWorkTime:function(e,t,r,i){var n=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(n),i.isWorkTime(n)},getClosestWorkTime:function(e){e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var t=this._getCalendar(e);return t.getClosestWorkTime(e)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.calculateDuration(e)},hasDuration:function(){var e=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),t=this._getCalendar(e);return t.hasDuration(e)},calculateEndDate:function(t){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),r=this._getCalendar(t);return r.calculateEndDate(t)}};var vy=function(e,t){return{getWorkHours:function(r){return t.getWorkHours(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){t.unsetWorkTime(r)},isWorkTime:function(r,i,n){return t.isWorkTime(r,i,n)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,i,n){return t.calculateDuration(r,i,n)},_hasDuration:function(r,i,n){return t.hasDuration(r,i,n)},calculateEndDate:function(r,i,n,a){return t.calculateEndDate(r,i,n,a)},mergeCalendars:ft(e.mergeCalendars,e),createCalendar:ft(e.createCalendar,e),addCalendar:ft(e.addCalendar,e),getCalendar:ft(e.getCalendar,e),getCalendars:ft(e.getCalendars,e),getResourceCalendar:ft(e.getResourceCalendar,e),getTaskCalendar:ft(e.getTaskCalendar,e),deleteCalendar:ft(e.deleteCalendar,e)}},Ay={create:vy};function Hc(e){var t=new Uc(e),r=new Bc(t),i=Ay.create(t,r);_e(e,i)}var jc={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{}};function Vc(e={}){let t=e.config||{},r={config:Object.assign({duration_unit:"hour",duration_step:1,work_time:!1,worktimes:{},work_days:null,inherit_calendar:!1,calendar_property:"calendar_id",resource_property:"resource_id",resource_calendars:{},dynamic_resource_calendars:!1,start_on_monday:!0,server_utc:!0,csp:"auto",show_errors:!1},t),locale:e.locale||jc,templates:e.templates||{},getTask:e.getTask||function(i){return null},isTaskExists:e.isTaskExists||function(i){return!1},isSummaryTask:e.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,n){let a=e.onEvent;return a&&a(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Oc,mixin:_e,copy:Dt,assert:function(i,n){if(!i){if(e.throwOnAssert)throw new Error("[calendar] "+n);e.silent!==!0&&console.error("[calendar]",n)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(i){return i},r.date=Fc(r),r.date.init(),Hc(r),r}function Cy(e={}){let t=Vc(e);return{addCalendar:function(r){return t.addCalendar(r)},deleteCalendar:function(r){return t.deleteCalendar(r)},getCalendar:function(r){return t.getCalendar(r)},getCalendars:function(){return t.getCalendars()},mergeCalendars:function(){return t.mergeCalendars.apply(t,arguments)},getTaskCalendar:function(r){return t.getTaskCalendar(r)},getResourceCalendar:function(r){return t.getResourceCalendar(r)},setWorkTime:function(r){return t.setWorkTime(r)},unsetWorkTime:function(r){return t.unsetWorkTime(r)},isWorkTime:function(){return t.isWorkTime.apply(t,arguments)},getClosestWorkTime:function(){return t.getClosestWorkTime.apply(t,arguments)},getWorkHours:function(){return t.getWorkHours.apply(t,arguments)},calculateDuration:function(){return t.calculateDuration.apply(t,arguments)},calculateEndDate:function(){return t.calculateEndDate.apply(t,arguments)},_internals:t}}var Yc={createCalendar:Cy};var cw=3600*1e3;function zc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Iy}=Yc,Ve="__replay_default__";function Sy(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(a=>Number.isNaN(a)))return e;let r=t[0],i=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${i+1}:00`]:e}var Kc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},$c="__main_global__",ky={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Gc(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function Dy(e){let t={};if(Array.isArray(e.days))for(let i=0;i<e.days.length;i+=1)t[i]=e.days[i];if(e.dates)for(let[i,n]of Object.entries(e.dates))t[i]=n;let r={hours:Sy(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function qc(e){let t=Iy({config:{work_time:!0}});t.addCalendar({id:Ve,worktime:Kc}),t.addCalendar({id:$c,worktime:ky});let r=new Set(e.filter(d=>!Gc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Gc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Dy(d.worktime):Kc});let n=wc(t),a=n.getCalendar(Ve),s=n.getCalendar($c);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([Ve]);for(let d of i)o.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let h=a;return o.has(u)?h=n.getCalendar(d)??a:r.has(u)&&(h=s),c.set(u,h),h}}}}function Jc(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let i=e.getParent(r.id);return!i||e.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(t){return Ty(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],i=e.getActivity(t);for(;i;){let n=i.parentId;if(n===null)break;let a=e.getActivity(n);if(!a)break;r.push(String(n)),i=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,progress:Number(n?.progress??0),ponderator:Number(n?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,workHours:Number(n?.workHours??0),progress:Number(n?.progress??0),realWorkHours:Number(n?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,usedCost:Number(n?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(i=>{let n=e.getActivity(i);return{id:i,cost:Number(n?.cost??0)}})}}}function Ty(e,t){let r=[],i=new pt;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let a of e.getChildren(n))i.enqueue(a)}return r}var Yr=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let i=this._journal;i&&(i.before.has(t)||i.before.set(t,te(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:"insert",activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:"remove",activityId:t,before:te(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:"link-add",linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:"link-remove",linkId:t,before:Xc(r)})}noteCorrelativeBefore(t,r){let i=this._journal;!i||i.correlativeBefore.has(t)||i.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let i=this._journal;if(!i)return;let n=te(r);i.scheduledBefore.has(t)||i.scheduledBefore.set(t,n),i.before.has(t)||i.before.set(t,n),i.dirty.add(t)}noteLinkField(t,r){let i=this._journal;!i||i.linkFieldCaptured.has(t)||(i.linkFieldCaptured.add(t),i.ops.push({kind:"link-field",linkId:t,before:Xc(r)}))}};function Xc(e){return{...e}}var Kr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Zc(t);return this.reader.getCalendar(r??Ve)}getClosestWorkTime(t){let r=`${Pn(t.task)}|${t.dir}|${t.date.getTime()}`;return _n(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:at.HOUR}))}calculateEndDate(t){let r=`${Pn(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return _n(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Pn(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return _n(this._cache.duration,r,()=>this.resolveCalendar(t.task).calculateDuration(t.startDate,t.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function _n(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var _y="__default__";function Zc(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Pn(e){return Zc(e)??_y}var $r=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let i=this.activities.get(t)?.parentId,n=0,a=this.activities.size;for(;i&&!w(i);){if(i===r)return!0;if(++n>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||w(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(w(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(w(r.parentId)){this._roots.push(r.id);continue}let i=String(r.parentId),n=this._childrenByParent.get(i)??[];n.push(r.id),this._childrenByParent.set(i,n)}let t=(r,i)=>{let n=this.activities.get(r),a=this.activities.get(i);return n&&a?qe(n,a):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Gr=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var Pe=class{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Yr;_viewState=new Gr;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;constructor(t,r=()=>null){this._buildOrderComparator=r;for(let i of t.activities)this._activities.set(i.id,i);for(let i of t.links)this._links.set(String(i.id),i),this._indexLink(i);this._calendar=new Kr(qc(t.calendars)),this._flags=Ey(t),this._hierarchy=new $r(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Xn(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,i]of this._activities)t(i,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t)}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??Qc}getIncomingLinkIds(t){return this._incoming.get(String(t))??Qc}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}setActivityField(t,r,i){let n=this.getActivity(t);n&&(this._writeCapture.note(String(t),n),n[r]=i,r===b.PARENT&&this._hierarchy.markDirty(),En(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,i){let n=this.getActivity(t);if(n){if(!Object.hasOwn(n,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),n),Reflect.set(n,r,Lc(r,i)),r===b.PARENT&&this._hierarchy.markDirty(),En(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let i=this.getActivity(t);if(!i)return;this._writeCapture.note(String(t),i);let n=!1;for(let a of Object.keys(r))Reflect.set(i,a,Reflect.get(r,a)),a===b.PARENT&&(n=!0),En(a)&&(this._cache.visualOrderIds=null);n&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r),this._links.set(String(t.id),{...t}),this._indexLink(t)}_indexLink(t){el(this._outgoing,String(t.source),t.id),el(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),tl(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),tl(i,t.id))}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkFieldDynamic(t,r,i){if(!Py(r))return;let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),Reflect.set(n,r,i))}setLinkProplannerId(t,r){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i.proplannerId=r)}removeLink(t){let r=this.getLink(t);r&&(this._writeCapture.noteLinkRemove(String(t),r),this._links.delete(String(t)),this._deindexLink(r))}addActivity(t){this._writeCapture.noteInsert(String(t.id)),this._activities.set(t.id,t),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(t.parentId,t.id)}removeActivity(t){let r=this.getActivity(t);r&&this._writeCapture.noteRemove(String(t),r);let i=String(t);(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&(this._captureViewStateOnce(),this._viewState.forget(i)),this._activities.delete(t),this._lastStartDate.has(String(t))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(t))),this._outgoing.delete(String(t)),this._incoming.delete(String(t)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(t,r){this._writeCapture.noteCorrelativeBefore(t,r)}noteScheduledBefore(t,r){this._writeCapture.noteScheduledBefore(t,r)}restoreFromCapture(){let t=this._writeCapture.peek();if(!t)return;let{ops:r,before:i,correlativeBefore:n,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,i]of t){let n=this._activities.get(r);n&&(n.correlativeId=i)}}_undoLinkAdds(t){for(let r of t)r.kind==="link-add"&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind==="insert"&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind==="remove"&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind==="link-remove"&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t)r.kind==="link-field"&&this._links.has(r.linkId)&&this._links.set(r.linkId,r.before)}_restoreActivityFields(t){for(let[r,i]of t){let n=this._activities.get(r);n&&this._restoreScalarFields(n,i)}}_restoreScalarFields(t,r){for(let i of Object.keys(t))Object.hasOwn(r,i)||Reflect.deleteProperty(t,i);for(let i of Object.keys(r))Reflect.set(t,i,Reflect.get(r,i))}_attachLink(t){this._links.set(String(t.id),{...t}),this._indexLink(t)}_detachLink(t){let r=this.getLink(t);r&&(this._links.delete(String(t)),this._deindexLink(r))}},Qc=[];function Py(e){return e===Ri.LAG||e===Ri.TYPE}function En(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function tl(e,t){return e.filter(r=>String(r)!==String(t))}function el(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Ey(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function rl(e,t){let r=e.getActivity(t);return r?et(r):null}function il(e){return e.getAllActivities().map(et)}function nl(e){return e.getAllIds().map(String)}function al(e,t){e.forEachActivity((r,i)=>t(i))}function sl(e,t){let r=t==="0"?Rn(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(et(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function Rn(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{w(n.parentId)&&i.push(a)}),i}return lt(r,e)}function ol(e){return e.checkedIds().map(String)}function cl(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=w(i.parentId)}),r}return e.getChildren(t).length>0}function ll(e,t){let r=e.getLink(t);return r?kt(r):null}function dl(e){return e.getAllLinks().map(t=>kt(t))}function zr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Ry(e){return e.reduce((t,r)=>zr(r)<zr(t)?r:t)}function by(e){return e.reduce((t,r)=>zr(r)>zr(t)?r:t)}function Ly(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function ul(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Ly(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Ry(i),endHour:by(n)}}function fl(e,t){return{calendars:e.calendarReader,hierarchy:Jc(e),activityReader:zc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function pl(e){return He(e)}function ml(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>({...i,after:null}));return et({...e,activities:t,links:r})}function bn(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function gl(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!=="created")continue;let a=e.getActivity(String(n.id));a&&r.set(String(n.id),J(a))}for(let n of t.links){if(n.kind!=="created")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function vl(e){return e.kind!=="inline-edit"||!Be.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function hl(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind==="updated"&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function Al(e,t){if(!hl(e)||!hl(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Cl(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},a=i.fields??{},s={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...i,fields:s}]};return bn(o)}function Il(e){return e.kind==="persistence-acknowledge"?"clear-on-success":e.kind==="sir-sync"||e.kind==="activity-lookahead-sync"||e.kind==="baseline-apply"||e.kind==="ponderator-criterion-set"||e.kind==="status-criteria-set"||e.kind==="selection-toggle"||e.kind==="selection-replace"||e.kind==="visibility-set"||e.kind==="filter-set"||e.kind==="sort-set"?"skip":"record"}function Ln(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&P.CUSTOM_ID in t.fields)return!0;return!1}function wn(e,t,r){let i=[],n=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);i.push({id:o,kind:"updated",fields:yl(s.fields,r),after:c?J(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?J(c):null})}else i.push({id:o,kind:"deleted",after:null});else if(r==="before")i.push({id:o,kind:"deleted",after:null});else{let c=e.getActivity(o);i.push({id:o,kind:"created",after:c?J(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);n.push({id:o,kind:"updated",fields:yl(s.fields,r),after:c?kt(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);n.push({id:o,kind:"created",after:c?kt(c):null})}else n.push({id:o,kind:"deleted",after:null});else if(r==="before")n.push({id:o,kind:"deleted",after:null});else{let c=e.getLink(o);n.push({id:o,kind:"created",after:c?kt(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?wy(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function yl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:et(i.after),after:et(i.before)}:{before:et(i.before),after:et(i.after)}]))}function wy(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function On(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Sl(e,t){Dl(e,t,"before")}function kl(e,t){Dl(e,t,"after")}function Dl(e,t,r){let i=t.changeSet;for(let n of i.activities)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))tt(e,n.id,a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${n.id}`);e.addActivity(J(a))}else e.removeActivity(String(n.id));else if(r==="before")e.removeActivity(String(n.id));else{let a=t.afterSnap?.get(String(n.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${n.id}`);e.addActivity(J(a))}for(let n of i.links)if(n.kind==="updated"){if(!n.fields)continue;for(let[a,s]of Object.entries(n.fields))Xs(e,String(n.id),a,r==="before"?s.before:s.after)}else if(n.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(n.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${n.id}`);e.addLink(a)}else e.removeLink(String(n.id));else if(r==="before")e.removeLink(String(n.id));else{let a=t.afterLinks?.get(String(n.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${n.id}`);e.addLink(a)}for(let n of i.viewState??[])n.checked&&e.setChecked(n.activityId,r==="before"?n.checked.before:n.checked.after),n.visible&&e.setVisible(n.activityId,r==="before"?n.visible.before:n.visible.after)}var Oy=100,xy=600,qr=class{constructor(t=Oy){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=xy&&n!==void 0&&Al(n,t)?this.undoStack[this.undoStack.length-1]=Cl(n,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=r,this._lastTime=i,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()??null}takeRedo(){return this.redoStack.pop()??null}pushRedo(t){this.redoStack.push(t)}pushUndo(t){this.undoStack.push(t)}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}};var Ny=["parentId","correlativeId"];function _l(e,t){let r=new Set,i=n=>{let a=t(n);r.add(a===null?"0":String(a))};for(let n of e.activities){let a=String(n.id);if(n.kind==="created"){i(a);continue}if(n.kind==="deleted"){let c=n.fields;c&&"parentId"in c&&r.add(Tl(c.parentId?.before));continue}let s=n.fields;!s||!Ny.some(c=>c in s)||(i(a),"parentId"in s&&r.add(Tl(s.parentId?.before)))}return r}function Tl(e){return e==null?"0":String(e)}function Fy(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function My(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Pl(e){return{id:String(e.id),worktime:My(e.worktime)}}function Jr(e,t,r,i=[]){let n=t.map(Fy),a=[...r.map(Pl),...i.map(Pl)];return{activities:[...e],links:n,calendars:a}}var El=["id","proplannerId","parentId","name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","assignedDefaultCalendar","dateOrigin","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","correlativeId","uniqueCorrelativeId","customId","subcontractId","isLookahead","newActivityIds","hasNewActivities","pendingRequestIds","responsableIds","tagIds"],Rl=new Set(["startDate","endDate","constraintDate","dateOrigin"]),bl=new Set(["newActivityIds","pendingRequestIds","responsableIds","tagIds"]);function Ll(e){let t=El.map(r=>[r,Wy(r,e[r])]);return Object.fromEntries(t)}function Wy(e,t){return Rl.has(e)?t instanceof Date?new Date(t):null:bl.has(e)?Array.isArray(t)?[...t]:[]:t}function wl(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of El)if(!Uy(r,e[r],t[r]))return!0;return!1}function Uy(e,t,r){return Rl.has(e)?By(t,r):bl.has(e)?Hy(t,r):(t??null)===(r??null)}function By(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function Hy(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],i=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==i.length?!1:r.every((n,a)=>n===i[a])}var Xr=class{initialized=!1;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.activitiesAtLastSave.set(String(r.id),Ll(r))}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{lag:r.lag,type:r.type})}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let i=this.activitiesAtLastSave.get(String(r.id));return i?wl(r,i):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let i=this.linksAtLastSave.get(String(r.id));return i?r.lag!==i.lag||r.type!==i.type:!0}):[]}clear(){this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Ol=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var xn=[!1,!0,!0,!0,!0,!0,!1],xl=new Set(["1","true"]),Nn="DURATION",Nl="asap",Fl={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo","AS SOON AS POSSIBLE":"asap","AS LATE AS POSSIBLE":"alap","START NO EARLIER THAN":"snet","START NO LATER THAN":"snlt","FINISH NO EARLIER THAN":"fnet","FINISH NO LATER THAN":"fnlt","MUST START ON":"mso","MUST FINISH ON":"mfo"};function Ml(e,t){let r=[],i=e.map(a=>{let s=Jy(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Xy(i);let n=new Set(i.map(a=>a.id));return Zy(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function jy(e){return e===0}function Vy(e,t){if(!e)return null;let r=Fl[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Nl):r}function Yy(e,t){let r=Vy(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?Lt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function Ky(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function $y(e){if(e==null||e==="")return[];if(Array.isArray(e))return e.map(String);if(typeof e!="string")return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.map(String):[]}catch{return[]}}function Gy(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Fn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Gy(r)&&t.push(String(r.id));return t}function zy(e){return e==="0"?null:String(e)}function qy(e,t){return Array.isArray(e)?e.map(r=>Wr(r,t)).filter(r=>r!==null):[]}function Jy(e,t){let r=Ky(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=Yy(e,t.reporter),o=e.type==="milestone",c=Lt(e.start_date),l=o?c:Lt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:zy(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:we(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:jy(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:Lt(e.date_origin),progress:n,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:e.custom_id,subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:$y(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Fn(e.pendingRequests),responsableIds:Fn(e.responsables),tagIds:Fn(e.tags),baselinePoints:qy(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:we(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function Xy(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function Zy(e,t,r){for(let i of e)i.parentId!==null&&(t.has(i.parentId)||(r.warn(`[parseFromBackend] activity "${i.id}" references unknown parent "${i.parentId}" \u2014 re-parenting to root (null)`),i.parentId=null))}function Hl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>em(c,i)),o=(r??[]).map(c=>rm(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:tm(s)}}function tm(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function jl(e,t){let r=cm(e.working_days),{days:i,hours:n}=om(e,r),a=im(t.exceptionsSource,t.exceptionRange),s={days:i,hours:n};return a&&(s.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:s}}function em(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return jl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function rm(e,t){return jl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function im(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=nm(i.from_date,i.to_date,t);if(n.length===0)continue;let a=am(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function nm(e,t,r){let i=Wl(e),n=Wl(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],s=r?Math.max(i,r.start):i,o=r?Math.min(n,r.end):n;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function Wl(e){if(typeof e!="string")return null;let t=Ol.exec(e.trim());if(!t)return null;let r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(i)&&Number.isFinite(n)?Date.UTC(r,i-1,n):null}function am(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=sm(t);if(r.length>0)return r}}var Ul=/^\d{1,2}:\d{2}$/;function sm(e){let t=[];for(let r of e){let i=Kl(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let o=i.startsCsv.trim(),c=i.endsCsv.trim();!Zr(o)&&!Zr(c)&&Ul.test(o)&&Ul.test(c)&&t.push(`${o}-${c}`);continue}let s=Yl(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Vl),t}function Bl(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[i,n]=r.split(":");return(Number(i)||0)*60+(Number(n)||0)}function Vl(e,t){return Bl(e)-Bl(t)}function om(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Yl(l,d);for(let f=0;f<7;f+=1){let h=u[f],m=r[f];h&&m&&m.push(h)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=Kl(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(Vl);let o=r.find((l,d)=>!!t[d]&&l.length>0)??[];return{days:t.map((l,d)=>{if(!l)return!1;let u=r[d];return u&&u.length>0?u:o}),hours:o}}function Yl(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(o=>o.trim()),n=t.split(",").map(o=>o.trim());if(!(i.length===n.length&&i.length>0&&i.length<=7))return r;let s=[...r];for(let o=0;o<i.length;o+=1){let c=i[o],l=n[o];Zr(c)||Zr(l)||(s[o]=`${c}-${l}`)}return s}function Kl(e){if(typeof e!="string")return null;let t=e.indexOf("-");return t<=0?null:{startsCsv:e.slice(0,t),endsCsv:e.slice(t+1)}}function cm(e){if(typeof e!="string")return[...xn];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...xn]:t.map(r=>xl.has(r))}var lm=new Set(["false","null"]);function Zr(e){return!e||lm.has(e)}function dm(e){return e==="0"||e==="1"||e==="2"||e==="3"}function um(e){if(typeof e!="string")return null;let t=ps(e);return t||(dm(e)?e:null)}function Gl(e,t){let r=[];for(let i of e)try{r.push(fm(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return pm(r)}function fm(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let s=um(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:i,source:n,target:a,type:s,lag:ht(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function pm(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||$l(r)>$l(n))&&t.set(i,r)}return[...t.values()]}function $l(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function hm(e){if(typeof e!="string")return Nn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Nn}}function ym(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function mm(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function zl(e){let t=ym(e),r=mm(e),i=e.update_duration_for_primavera_for_end_date===!0;return{id:String(e.id),name:e.name,hoursPerDay:e.hoursPerDay,hoursPerWeek:e.hoursPerWeek,dateFormat:e.dateFormat,projectId:e.projectId,companyId:e.companyId,...t!==void 0?{customIdPrefix:t}:{},...r!==void 0?{customIdIncrement:r}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:hm(e.activity_creter),statusCriteria:yi}}function Qr(e,t=ue){let r=zl(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=Hl(e.calendars,e.sector.calendars,e.baseCalendars,gm(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=Ml(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=Gl(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function gm(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let s=new Date(a.start_date).getTime(),o=new Date(a.end_date).getTime();Number.isFinite(s)&&(t=Math.min(t,s)),Number.isFinite(o)&&(r=Math.max(r,o))}if(!Number.isFinite(t)||!Number.isFinite(r))return null;let i=new Date(t),n=new Date(r);return i.setFullYear(i.getFullYear()-1),n.setFullYear(n.getFullYear()+1),{start:i.getTime(),end:n.getTime()}}function ql(e={}){let t=e.seed??0,r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function Jl(e={}){let t=e.seed??Date.now(),r=i=>{i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}return{next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)}}}function Xl(e={}){let t=e.seed??0,r=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>t&&(t=i)};if(e.knownIds)for(let i of e.knownIds){if(i==null)continue;let n=typeof i=="number"?i:Number(i);r(n)}return{next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)}}}function Zl(e){return!!e&&typeof e=="string"&&e.trim().length>0}function ti(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ei(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Ql(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function td(e,t){return!t&&Zl(e)}function ed(e,t){return t&&Zl(e)}function Ke(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Ye(e){if(!Ke(e))return 0n;try{return BigInt(e)}catch{return 0n}}function vm(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!Ke(t))return r;let i=t.length;return r.padStart(i,"0")}function gt(e,t){let r=Ye(e),i=Ye(t),n=r+i;return vm(n,e)}function ri(e,t){let r=Ye(e),i=Ye(t);return r<i?-1:r>i?1:0}function ii(e,t){return ri(e,t)<=0?e:t}function ni(e,t){return ri(e,t)>=0?e:t}function rd(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ii(t,r))}function id(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ni(t,r))}function nd(e){return{prefix:e,baseSuffix:null}}function ad(e,t){let r=ei(e);return{prefix:ti(e),baseSuffix:gt(r,t)}}function sd(e){return{prefix:e,baseSuffix:null}}function od(e,t){return td(e,t)?"parentConversion":ed(e,t)?"pasteReference":"noContext"}function Am(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var ai=class{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[i,n]of t)n===null?this.prefixMap.delete(i):this.prefixMap.set(i,n);for(let i of[...r].reverse())i.hadId?this.processedIds.add(i.customId):this.processedIds.delete(i.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:r}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(r)){let i=this.prefixMap.get(r);this._journalPrefixBefore.set(r,i?Am(i):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let r=this.prefixMap.get(t);if(!r?.boundsDirty)return;r.boundsDirty=!1;let i=Array.from(r.usedSuffixes);r.min=rd(i),r.max=id(i),r.quantity=i.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return ti(t)}extractSuffix(t){return ei(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let i=this.prefixMap.get(t);i.usedSuffixes.has(r)||(i.usedSuffixes.add(r),i.min=ii(r,i.min),i.max=ni(r,i.max),i.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let i=this.getNextAvailableSuffix(t);r.next=i??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!r&&!i)return{prefix:r,suffix:i};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let n=this.prefixMap.get(r);n.usedSuffixes.has(i)||(n.usedSuffixes.add(i),n.min=ii(i,n.min),n.max=ni(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:gt(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(t),{prefix:r,suffix:i}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:i}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:i};this._noteCustomIdBefore(t);let n=this.prefixMap.get(r);return n.usedSuffixes.has(i)&&(n.usedSuffixes.delete(i),n.quantity-=1,n.usedSuffixes.size===0?this.prefixMap.delete(r):n.boundsDirty=!0),this.processedIds.delete(t),{prefix:r,suffix:i}}trackCustomIdChange(t,r){let i=this.releaseCustomId(t),n=this.registerCustomId(r);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:n.prefix,newSuffix:n.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${gt(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&Ke(r)?r:this.suffixIncrement;return`${t}${i}`.length>20?null:i}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),i=this.suffixIncrement;for(;ri(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=gt(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,r);let i=this.prefixMap.get(t),n=this.suffixIncrement;if(!r||!Ke(r)){let o=gt(i.max,n);return`${t}${o}`.length>20?null:o}let a=r;for(let o=0;o<100;o++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=gt(a,n)}let s=gt(i.max,n);return`${t}${s}`.length>20?null:s}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),a=0;for(;n.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,gt(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let i=`${t}${r}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of r){if(this.processedIds.has(i))continue;let{prefix:n,suffix:a}=this.analyzeCustomId(i);(n||a)&&(this._updatePrefixStats(n,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=Ql(r),a=od(n,i),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){this._ensureFreshBounds(s);let f=this.prefixMap.get(s).max;c=gt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:o,d=this.getNextAvailableSuffix(s,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${s}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return nd(this.defaultPrefix);case"pasteReference":return ad(r,this.suffixIncrement);default:return sd(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),s=gt(a,this.suffixIncrement),o=this.getNextAvailableSuffix(n,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${o}`;return this._exceedsMaxLength(c)&&(c=this._generateDefaultCustomId()),this.registerCustomId(c),c}}let r=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(r),r}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(t){return this.prefixMap.has(t)}isCustomIdInUse(t,r=null){if(!t||typeof t!="string"||!t.trim())return!1;let i=t.trim();return r&&i===r.trim()?!1:this.processedIds.has(i)}};var Cm=1,Im=-1;function Sm(e,t){return!e&&!t?null:e&&t?0:e?Cm:Im}function cd(e){return e==null}function ld(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function km(e,t,r){return e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="number"&&typeof t=="number"?e-t:typeof e=="boolean"&&typeof t=="boolean"?Number(e)-Number(t):Array.isArray(e)&&Array.isArray(t)?e.length-t.length:String(e).localeCompare(String(t),r,{sensitivity:"base",numeric:!0})}function Dm(e,t){let r=xt(e.field);return r===null?null:(i,n)=>{let a=r.extract(i,t),s=r.extract(n,t),o=Sm(cd(a),cd(s));if(o!==null)return o;let c=r.valueKind==="enum"?ld(a,r.order)-ld(s,r.order):km(a,s,t.locale);return e.direction==="desc"?-c:c}}function dd(e,t){let r=e.rules.map(i=>Dm(i,t)).filter(i=>i!==null);return r.length===0?null:(i,n)=>{for(let a of r){let s=a(i,n);if(s!==0)return s}return 0}}function ud(e){let t=[];e.forEachActivity((r,i)=>{r.type==="project"&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,b.TYPE,de),Tm(e,r)}function Tm(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let i=new Date(r.startDate);i.setUTCHours(0,0,0,0);let n=e.getClosestWorkTime({date:i,dir:X.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,b.START_DATE,n),e.setActivityField(t,b.END_DATE,a)}function si(e){let t=[],r=[];e.forEachActivity((n,a)=>{n.parentId===null&&t.push(String(a))});let i=n=>{let a=e.getActivity(n);if(!a)return 0;let s=[...e.getChildren(n)],o=s.length===0?dt(a.workHours,a.progress):s.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,b.REAL_WORK_HOURS,o),r.push(n),o};for(let n of t)i(n);return r}async function fd(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(ct(t),r.updateDurationForPrimaveraEndDate&&Pm(t),Em(t),si(t),n){a&&(wt(t,a),St(t,r.statusCriteria));return}let s=await i.schedule({});Le(t,s),Rm(t),_m(t),await pe(t,void 0,!1),a&&(wt(t,a),St(t,r.statusCriteria))}function _m(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}))})}function Pm(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Em(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type==="milestone"&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=Rt(t.constraintDate,n,r))})}function Rm(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=Rt(t.constraintDate,i,r))})}var _t={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function pd(e){let t=e.clock??null,r=t?Oe(t()):null,i=e.reporter??ue,n=Qr({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),a=n.sector;a.statusCriteria=Ze(e.statusCriteria);let s=n.calendars,o=n.baseCalendars??[],c=Jr(n.activities,n.links,n.calendars,o),l=k=>dd(k,ce(a.hoursPerDay)),d=new Pe(c,l);d.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let u=new fr(d,i);ud(d);let f=ql({knownIds:n.activities.map(k=>k.id)}),h=Jl({knownIds:n.links.map(k=>k.id)}),m=Xl({knownIds:n.activities.map(k=>k.uniqueCorrelativeId)}),v=new ai({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(v.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let k=o.find(D=>D.baseDefault)?.id??null;Ur(d,e.baselinePoints,r,i,k)}let A=fd({state:d,sector:a,scheduler:u,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:d,scheduler:u,activityIdGen:f,linkIdGen:h,uidGen:m,customIdTracker:v,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:A}}var oi=class{_status=_t.READY;coreRuntime;_undo=new qr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=pd(t);this.coreRuntime={state:r.state,scheduler:r.scheduler,sector:r.sector,activityIdGenerator:r.activityIdGen,linkIdGenerator:r.linkIdGen,uniqueCorrelativeIdGenerator:r.uidGen,customIdTracker:r.customIdTracker,clock:r.clock,calendars:new Map(r.calendars.map(n=>[n.id,n])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==_t.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(async()=>{let n=await this._runCriticalPathAndCapture();return this._criticalPathRevision=this._scheduleRevision,n}));let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return et(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),rl(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),il(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),sl(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ll(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),dl(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?et(i[r]):null}getAllIds(){return this.assertReady(),nl(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),al(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),Rn(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),ol(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getActiveFilter(){return this.assertReady(),this.coreRuntime.state.getActiveFilter()}getActiveOrder(){return this.assertReady(),this.coreRuntime.state.getActiveOrder()}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),cl(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?et(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>et(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>et(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),ul(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities()).map(et)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}async dispatch(t,r={}){return this._enqueue(()=>this._dispatchInner(t,r))}async _dispatchInner(t,r={}){this.assertReady();let i=fl(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=Il(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a;try{a=await bc(t,r,{adapter:this.coreRuntime.state,ctx:i,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(s=>s.baseDefault)?.id??null,now:this.coreRuntime.clock?Oe(this.coreRuntime.clock()):null}),a.ok||this._rollback()}catch(s){throw this._rollback(),s}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(a.ok&&n==="record"&&On(a.changes)){let s=gl(this.coreRuntime.state,a.changes);this._undo.record(bn(ml(a.changes),a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),vl(t),Date.now())}return a.ok&&n==="clear-on-success"&&(this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities()),this._saveTracker.snapshotLinks(this.getAllLinksView()),this._undo.clear()),a=this._withReappliedViewState(t,a),a.ok?(No(t)&&On(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),bm(a)):a}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||!xo(t))return r;let i=this._reapplyViewState(r.changes);return i===null?r:{...r,changes:i}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),i=this._reapplyActiveOrder(r??t);return this._emitTouchedBranchOrder(i??r??t)??i??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state;if(r.getActiveOrder()!==null)return null;let i=_l(t,a=>r.getParentId(a));if(i.size===0)return null;let n=[...i].map(a=>({parentId:a,childIds:lt(a,r)})).filter(a=>a.childIds.length>1);return n.length===0?null:{...t,order:n}}_reapplyActiveOrder(t){let r=this.coreRuntime.state;return r.getActiveOrder()===null?null:(r.invalidateDerivedOrder(),{...t,order:Je(r)})}_reapplyActiveFilter(t){let r=this.coreRuntime.state.getActiveFilter();if(r===null)return null;let i=this.coreRuntime.state,n=ze({activities:i.getAllActivities(),parentOf:s=>i.getParentId(s),filter:r,context:ce(this.coreRuntime.sector.hoursPerDay)}),a=oe(i,n);return a.length===0?null:{...t,viewState:[...t.viewState??[],...a]}}_recordScheduleMutation(t){this._scheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===_t.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},i=new Pe(Jr(this.coreRuntime.state.getAllActivities().map(o=>J(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==_t.DESTROYED&&this._scheduleRevision===t,a=(async()=>{let o=await tn(i,this.coreRuntime.sector.hoursPerDay,n);if(!n())return null;let c=o??new Map;return this._enqueue(async()=>{if(!n())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let l;try{for(let[d,u]of c)this.coreRuntime.state.setActivityFields(d,u);l=await j(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(d){throw this._rollback(),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:l}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let s=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(s,s),a}async _runCriticalPathAndCapture(){if(this._status===_t.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Er(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=await j(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:t}}_recomputeAfterHistoryRestore(){let t=this.coreRuntime.state;if(Hr(t),si(t),Gt(t),this.coreRuntime.clock){let r=Oe(this.coreRuntime.clock());wt(t,r);let i=!1;t.forEachActivity(n=>{i||=it(n)!==null}),i&&Kt(t,r,this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null),St(t,this.coreRuntime.sector.statusCriteria)}}undo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeUndo();if(!r)return null;Sl(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),Ln(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(r),this._undo.resetCoalesce();let i=wn(this.coreRuntime.state,r,"before");return this._reapplyViewState(i)??i});return t.then(r=>{r&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",i)})},()=>{}),t}redo(){let t=this._enqueue(async()=>{this.assertReady();let r=this._undo.takeRedo();if(!r)return null;kl(this.coreRuntime.state,r),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),Ln(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=wn(this.coreRuntime.state,r,"after");return this._reapplyViewState(i)??i});return t.then(r=>{r&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",i)})},()=>{}),t}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=_t.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Xr;assertReady(){if(this._status===_t.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===_t.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction()}catch(t){throw this._status=_t.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",t),t}}};function bm(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}function hd(e,t){let r=new Map(e.map(i=>[String(i.id),i]));return t.filter(i=>{let n=r.get(String(i.id));return n?n.lag!==i.lag||n.type!==i.type:!1})}var yd=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var md={asap:"AS SOON AS POSSIBLE",alap:"AS LATE AS POSSIBLE",snet:"START NO EARLIER THAN",snlt:"START NO LATER THAN",fnet:"FINISH NO EARLIER THAN",fnlt:"FINISH NO LATER THAN",mso:"MUST START ON",mfo:"MUST FINISH ON"};var gd=8;var K={PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},Lm={[K.PERSISTENCE_ACKNOWLEDGE]:!0,[K.BASELINE_APPLY]:!0,[K.PONDERATOR_CRITERION_SET]:!0,[K.STATUS_CRITERIA_SET]:!0,[K.INLINE_EDIT]:!0,[K.DATES_BATCH]:!0,[K.BULK_EDIT]:!0,[K.LINK_CREATE]:!0,[K.LINK_UPDATE]:!0,[K.LINK_DELETE]:!0,[K.LINKS_BATCH]:!0,[K.ACTIVITY_CREATE]:!0,[K.ACTIVITY_DELETE]:!0,[K.ACTIVITY_MOVE]:!0,[K.ACTIVITY_INDENT]:!0,[K.ACTIVITY_OUTDENT]:!0,[K.ACTIVITY_SET_PROGRESS]:!0,[K.ACTIVITY_PASTE]:!0,[K.SELECTION_TOGGLE]:!0,[K.SELECTION_REPLACE]:!0,[K.VISIBILITY_SET]:!0,[K.FILTER_SET]:!0,[K.SORT_SET]:!0,[K.SIR_SYNC]:!0,[K.ACTIVITY_LOOKAHEAD_SYNC]:!0},vd=Object.keys(Lm);var Ad={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return _d(wm);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map