@outbuild-company/schedule-core 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var ui=Object.defineProperty;var Sd=Object.getOwnPropertyDescriptor;var kd=Object.getOwnPropertyNames;var Dd=Object.prototype.hasOwnProperty;var Td=(e,t)=>{for(var r in t)ui(e,r,{get:t[r],enumerable:!0})},_d=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of kd(t))!Dd.call(e,n)&&n!==r&&ui(e,n,{get:()=>t[n],enumerable:!(i=Sd(t,n))||i.enumerable});return e};var Pd=e=>_d(ui({},"__esModule",{value:!0}),e);var xm={};Td(xm,{ACTIVITY_TYPE:()=>tr,CALENDAR_UNIT:()=>st,COLUMN:()=>P,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>gd,CREATION_KIND:()=>Cd,DEFAULT_HOURS_PER_DAY:()=>vd,DISPATCH_ACTION_KIND:()=>$,DISPATCH_ACTION_KINDS:()=>Ad,DISPATCH_TRACK_EVENT:()=>vt,LINK_CODE_TO_TYPE:()=>Xt,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>ps,NEW_ACTIVITY_DEFAULTS:()=>Nr,REJECTION_REASON:()=>E,ROOT_PARENT_ID:()=>F,ScheduleCore:()=>ci,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>yd,computeExpectedProgress:()=>xi,expectedProgressFromBaseline:()=>Ie,getActiveBaseline:()=>nt,getUnsavedActivities:()=>md,isRootParent:()=>L,normalizeParentKey:()=>Pt,parseFromBackend:()=>ti,willRunCriticalPath:()=>yl,yieldToBrowser:()=>Z});var yt=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 Hn(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=Ed(c,n).filter(s),f=u.filter(m=>!a(m)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let m of f)r?d.add(m):d.delete(m);return p||Rd({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:bd(l,d),parentBlocked:p}}function Ed(e,t){let r=[],i=new yt;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 Rd(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(k=>!a(k)),m=f.length>0&&f.every(k=>o.has(k))&&!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 bd(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 jn=(e,t)=>{let r=e.getActivity(t);return r!=null&&se(r)},Vn=(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 Yn(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=>jn(r,o),s=Hn({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:Vn(e,r,s.changed)}}function Kn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!jn(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:Vn(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 $n(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 Ld=["Waiting","Done","Doing","Overdue","Advancement"],wd=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function fi(e,t){return e===null||t<=0?null:e/t}function Od(e,t){let r=t.getTime()-e.getTime();return Math.floor(r/864e5)+1}var xd={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)=>fi(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>Od(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)=>fi(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>fi(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:Ld,extract:e=>e.status},constraintType:{valueKind:"enum",order:wd,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 Nt(e){return xd[e]??null}function Nd(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function Fd(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 Md(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 Wd(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function Ud(e,t,r){let n=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function Bd(e,t,r){let i=e!==null&&t.has(String(e));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function Gn(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function zn(e,t,r){let i=Nt(t.field);if(i===null)return!1;let n=i.extract(e,r),{operator:a}=t;return i.valueKind==="string"?Fd(n,String(t.value),a):i.valueKind==="number"?Md(n,Number(t.value),a):i.valueKind==="date"?Wd(n,Nd(t.value),a):i.valueKind==="id-array"?Ud(n,Gn(t.value),a):Bd(n,Gn(t.value),a)}function Hd(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(i=>zn(e,i,r)):t.criteria.every(i=>zn(e,i,r))}function jd(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 Vd(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=Hd(c,i,n),d=a===void 0||jd(c,a);l&&d&&(s.add(String(c.id)),o.push(c.id))}for(let c of o)Vd(c,r,s);return s}function ce(e){return{hoursPerDay:e,locale:"en"}}var Yd={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 qn(e){let t=Nt(e.field);return t===null?"unknown_field":Yd[t.valueKind].has(e.operator)?Kd(e,t.valueKind):"unknown_operator"}function Kd(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"?$d(r)?null:"invalid_value":null}function $d(e){return e instanceof Date?!0:typeof e=="string"||typeof e=="number"?!Number.isNaN(new Date(e).getTime()):!1}function Jn(e){return e.criteria.length===0&&e.dateRange===void 0}function Gd(e,t,r){let i=e.getAllActivities();return Jn(t)?new Set(i.map(n=>String(n.id))):ze({activities:i,parentOf:n=>e.getParentId(n),filter:t,context:ce(r)})}function Xn(e,t){let{adapter:r,hoursPerDay:i}=t;for(let c of e.criteria){let l=qn(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(Jn(n)?null:n);let a=Gd(r,n,i),s=oe(r,a);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:s}}}var F="0";function L(e){return e==null||e===0||e==="0"}function Pt(e){return L(e)?"0":String(e)}var pi=Number.MAX_SAFE_INTEGER;function ut(e,t){let r=yi(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 Qn(e){let t=[],r=n=>{t.push(n);let a=ut(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=ut("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function ta(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=ea(i),a=ut(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&&!zd(t,c))return c}return null}function hi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=ea(r);return ut(i,t).findIndex(a=>String(a)===String(e))}function yi(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=Zn(e),i=Zn(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Zn(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}function ea(e){let t=e.parentId;return t===null?"0":t}function zd(e,t){return e.has(t)?!0:e.has(String(t))}function Je(e){let t=[],r=i=>{let n=ut(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let a of n)r(a)};return r("0"),t}function qd(e){return Nt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function ra(e,t){let{adapter:r}=t;for(let a of e.rules){let s=qd(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 ia="text";var na="description";var aa="duration";var sa="progress";var oa="cost";var ca="used_cost";var la="hhWorkTime";var da="start_date";var ua="end_date";var fa="constraint_type";var pa="constraint_date";var ha="calendar_id";var ya="custom_id";var ma="subcontractId";var ga="responsables";var va="tags";var Aa="custom_predecessors";var Ca="custom_sucessors";var Ia="real_work";var Sa="real_cost";var ka="expected_progress";var Da="expected_progress_base";var Ta="start_base";var _a="end_base";var Pa="duration_base";var Ea="cost_base";var Ra="work_base";var ba="calendarDuration";var La="is_critical",wa="earlyStart",Oa="earlyFinish",xa="lateStart",Na="lateFinish",Fa="freeSlack",Ma="totalSlack";var Wa="correlative_id";var Ua="unique_correlative_id";var Ba="ponderator";var X={FUTURE:"future",PAST:"past"},st={HOUR:"hour",DAY:"day"},Ft={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Xe="status";var mi="Baseline";function Ze(e){return e==="Actual"?"Actual":mi}var Jd={TEXT:ia,DESCRIPTION:na,DURATION:aa,PROGRESS:sa,COST:oa,USED_COST:ca,HH_WORK_TIME:la,START_DATE:da,END_DATE:ua,CONSTRAINT_TYPE:fa,CONSTRAINT_DATE:pa,CALENDAR_ID:ha,CUSTOM_ID:ya,SUBCONTRACT_ID:ma,RESPONSABLES:ga,TAGS:va,CUSTOM_PREDECESSORS:Aa,CUSTOM_SUCESSORS:Ca},Xd={REAL_WORK:Ia,REAL_COST:Sa,EXPECTED_PROGRESS:ka,EXPECTED_PROGRESS_BASE:Da,START_BASE:Ta,END_BASE:_a,DURATION_BASE:Pa,COST_BASE:Ea,WORK_BASE:Ra,CALENDAR_DURATION:ba,IS_CRITICAL:La,EARLY_START:wa,EARLY_FINISH:Oa,LATE_START:xa,LATE_FINISH:Na,FREE_SLACK:Fa,TOTAL_SLACK:Ma,CORRELATIVE_ID:Wa,UNIQUE_CORRELATIVE_ID:Ua,PONDERATOR:Ba,STATUS:Xe},P={...Jd,...Xd};function Ha(e,t){throw new Error(t)}function ja(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Zd={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 Ya(e,t,r){if(!t)return{violated:!1};let i=Zd[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Qd=new Set(["mso","snet","snlt"]);function Re(e,t,r){return Qd.has(e)?t:r}function Ka(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var tu={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())),Va=(e,t)=>new Date(e.getTime()+t*864e5),eu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function gi(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=tu[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Qe(i),dir:X.FUTURE,task:e});if(eu(n,i))return i.getTime()!==Qe(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Va(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:Va(a,1),dir:X.PAST,task:e})}function $a(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=gi(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 Ga(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function vi(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"},za={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ai=typeof window>"u",ru=!Ai&&typeof MessageChannel<"u";function Z(){return ru?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<za.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 Ai||await Z(),e()?{aborted:!1}:{aborted:!0}}function rr(e,t){let{inDegree:r,successors:i}=iu(e,t),n=nu(r),a=au(n,r,i),s=a.length<e.length,o=s?su(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function iu(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 nu(e){let t=new yt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function au(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 su(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 qa(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Ci={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 Ii(e){return e==="project"||e==="task"||e==="milestone"}function Et(e,t){return t||Ii(e)&&Ci[e].alwaysSummary}function Jt(e){return e==="milestone"}function Mt(e){return Ii(e)&&Ci[e].promotesToProjectOnFirstChild}var Si="project",de="task";function be(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Ja(e,t){let r=t.getActivity(e);return r?Et(r.type,t.getChildren(e).length>0):!1}function Xa(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 ts(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 ou(e){let t=new Map;for(let r of e)Za(t,String(r.source),r),Za(t,String(r.target),r);return t}function Za(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function cu(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let s of e)lu(s,n,t,r,i)||a.push(s);return a.length>0?a:e}function lu(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(du(c,a,s,t,r,n))return!0;return!1}function du(e,t,r,i,n,a){if(uu(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=fu(e,t);if(!i.has(String(o)))return!1;let c=n.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&pu(e,r,c))}function uu(e){return e.source===e.target}function fu(e,t){return String(e.source)===t?e.target:e.source}function pu(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 es(e,t){let r=[],i=ou(e),n=0;for(let a of e){let s=Ja(a.source,t),o=Ja(a.target,t);if(hu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Qa(a.source,s,t,i,!0),l=Qa(a.target,o,t,i,!1);n=Iu(r,c,l,a,t,n,i)}return r}function hu(e,t,r,i){return r&&Xa(e.source,e.target,i)||t&&Xa(e.target,e.source,i)}function Qa(e,t,r,i,n){return t?cu(ts(e,r),r,i,n):[e]}function yu(e,t,r){let i=ts(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 yu(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function mu(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function gu(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 vu(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function Au(e,t,r,i,n){if(vu(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Cu(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?-mu(i,a,t):0,summarySourceId:e.type===W.START_TO_START&&n?e.source:void 0}}function Iu(e,t,r,i,n,a,s){let o=Cu(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:m}=o,k=a;for(let C of t){let I=f?gu(C,c,l,n):0;for(let T of r){if(String(C)===String(T))continue;let _=Au(T,d,c,n,s);e.push(Su(i,C,T,k,I,p,u+_,m,_!==0&&p===0?i.target:void 0)),k+=1}}return k}function Su(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 es(t,r)}};function ku(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 Du(e,t,r){let i=new Set,n=new Map,a=new yt;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 rs(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=ku(t),n=Du(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 is(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 Tu(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 _u(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 ns(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=is(e,t,r),l=Tu(r,e,i)??n,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return _u(e,t,r,i,o||c);let p=o?t:e,m=i.getClosestWorkTime({date:e.endDate,dir:"future",task:p});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 k=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:k,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}function as(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=is(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 ss(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===K.ASAP||a===K.ALAP)continue;let s=$a(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=vi(e.startDate,i):Ga(n,i)?a=n:a=vi(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function os(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case K.MSO:case K.MFO:return new Date(i);case K.SNET:case K.FNET:return i>t?new Date(i):t;case K.SNLT:case K.FNLT:return i<t?new Date(i):t;default:return t}}function Pu(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function cs(e,t,r){return ki(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ki(e,t,r){return t.dragWithMultiple&&Pu(e,r)}async function ds(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 p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.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 p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Eu(p,r))continue;let m=s.get(String(u))??[],k=null,C=null,I=!1;for(let g of m){let A=r.getActivity(g.source);if(!A)continue;let D=o(g.source),R=D.startDate.getTime()!==A.startDate.getTime()||D.endDate.getTime()!==A.endDate.getTime(),x={...A,startDate:D.startDate,endDate:D.endDate},O=cs(x,c,l),j={...x,startDate:O.startDate,endDate:O.endDate},Y=ki(g.source,c,l)?{...g,lag:0}:g,it=ns(j,p,Y,r);(!k||it.successorStart>k)&&(k=it.successorStart,C=String(g.id),I=g._summaryTargetId!==void 0&&!R)}k!==null&&I&&k<p.startDate&&(k=new Date(p.startDate));let _=a.get(u),v=_?{..._}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},h=v.earliestStart||v.latestStart||v.earliestEnd||v.latestEnd;if(!(!k&&!h)){if(k){let g=k;p.type===tr.MILESTONE&&(g=os(p,k)),v.drivingLinkId=C,v.startDate=g,v.endDate=r.calculateEndDate({startDate:g,durationHours:p.durationHours,task:p}),v.earliestSchedulingStart=g,v.earliestSchedulingEnd=v.endDate}else p.constraintType===K.MSO?v.earliestStart&&(v.startDate=v.earliestStart,v.endDate=v.earliestEnd??r.calculateEndDate({startDate:v.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&v.latestStart&&(v.startDate=v.latestStart,v.endDate=v.latestEnd??r.calculateEndDate({startDate:v.latestStart,durationHours:p.durationHours,task:p}));sr(p,v,r),a.set(u,v)}}return a}function Eu(e,t){return Et(e.type,t.getChildren(e.id).length>0)}async function us(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let C of o)C.constraintType===K.ALAP&&l.push(C.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let C of t){let I=String(C.source);d.has(I)||d.set(I,[]),d.get(I).push(C);let T=String(C.target);u.has(T)||u.set(T,[]),u.get(T).push(C)}let f=C=>{let I=s.get(C);if(I)return{startDate:I.startDate,endDate:I.endDate};let T=i.getActivity(C);return T?{startDate:T.startDate,endDate:T.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||L(C.parentId)?i.getProjectEnd():f(C.parentId).endDate,m=(C,I)=>{let T=C,_=0;for(;T&&!L(T)&&_++<c+1;){if(String(T)===String(I))return!0;let v=i.getActivity(T);if(!v||!v.parentId)break;T=v.parentId}return!1},k=performance.now();for(let C of e){let I=await er(k,a);if(I.aborted)return s;k=I.newSliceStart;let T=i.getActivity(C);if(!T||T.constraintType!==K.ALAP||!T.autoScheduling||T.progress===100||Et(T.type,i.getChildren(C).length>0))continue;let _=p(T);if(!_)continue;let v=_,h=null,g=!1,A=d.get(String(C))??[];for(let Ct of A){if((Ct.lag??0)<0)continue;let ae=i.getActivity(Ct.target);if(!ae||ae.autoScheduling===!1)continue;let Bn=f(Ct.target),Id={...ae,startDate:Bn.startDate,endDate:Bn.endDate},$e=as(Id,T,Ct,i);$e<v&&(v=$e),(h===null||$e<h)&&(h=$e,g=T.parentId&&!L(T.parentId)?m(Ct.target,T.parentId):!1)}if(h!==null)if(g)v=h;else{let Ct=f(C).endDate,ae=Ct.getTime()>_.getTime()?Ct:_;v=h<ae?h:ae}else v>_&&(v=_);let R=(u.get(String(C))??[]).some(Ct=>Ct.type===W.FINISH_TO_START||Ct.type===W.FINISH_TO_FINISH),x=new Date(Date.UTC(v.getUTCFullYear(),v.getUTCMonth(),v.getUTCDate())),O=()=>i.getClosestWorkTime({date:x,dir:"past",task:T}),j=i.getClosestWorkTime({date:v,dir:"future",task:T}).getTime()===v.getTime(),Y;T.durationHours===0&&h===null?Y=R&&j?O():i.getClosestWorkTime({date:v,dir:"past",task:T}):T.durationHours===0?R?Y=O():Y=i.getClosestWorkTime({date:v,dir:"future",task:T}):Y=i.getClosestWorkTime({date:v,dir:"future",task:T});let it=i.calculateEndDate({startDate:Y,durationHours:-T.durationHours,task:T}),Ee=s.get(C),lt=Ee?{...Ee}:{activityId:C,startDate:it,endDate:Y,drivingLinkId:null,kind:"alap",conflict:!1};lt.startDate=it,lt.endDate=Y,lt.drivingLinkId=null,lt.kind="alap";let li=lt.earliestSchedulingStart??null;lt.earliestSchedulingStart=null,lt.earliestSchedulingEnd=null;let di=li!==null&&li.getTime()>it.getTime()?li:it;lt.latestSchedulingStart=di,lt.latestSchedulingEnd=di===it?Y:i.calculateEndDate({startDate:di,durationHours:T.durationHours,task:T}),sr(T,lt,i),s.set(C,lt)}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 fs(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 Ru(n,i,r)}function Ru(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new yt;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 Wt(e,t){switch(e.kind){case"create":return bu(e,t);case"update":return Lu(e,t);case"delete":return wu(e,t)}}function bu(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(fs(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Ou)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function Lu(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 wu(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 Ou(){return or===null&&(or=Date.now()),or+=1,String(or)}var ps={[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},hs="fs";function ys(e){if(e in Xt)return Xt[e]}var ms=";",gs=/^(\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(ms)){if(n.length===0)continue;let a=xu(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function xu(e){let t=e.toLowerCase(),r=gs.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?Xt[n]:Xt[hs],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 mt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var vs={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:st.HOUR}):t.isWorkTime(e,st.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function Di(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 Ti=vs;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=ja(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Wu(this.adapter);let a=Ut("schedule.total"),s=Ut("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Rt(s);let l=c;if((await le(i)).aborted)return{...n,cancelled:!0};let d=Ut("schedule.scoping"),u=this.adapter.getAllIds(),f=Uu(t,l,this.adapter),p=f.links,m=f.idSet;Rt(d);let k=Ut("schedule.topologicalSort"),C=Hu(this.topoCache,u,l,m);if(Rt(k),C.hasCycles)return Rt(a),{...n,cycles:[C.cycleNodes]};if((await le(i)).aborted)return{...n,cancelled:!0};let I=Ut("schedule.processConstraints"),T=new Map;if(ss(C.ordered,this.adapter,T),Rt(I),(await le(i)).aborted)return{...n,cancelled:!0};let _=Ut("schedule.asapPass"),v=await ds(C.ordered,p,this.adapter,t,i,T);if(Rt(_),(await le(i)).aborted)return{...n,cancelled:!0};let h=Ut("schedule.alapPass"),g=await us(C.reversed,p,v,this.adapter,t,i);if(Rt(h),(await le(i)).aborted)return{...n,cancelled:!0};let A=Ut("schedule.diff"),D=[];for(let[R,x]of g){let O=this.adapter.getActivity(R);if(!O)continue;let j=O.startDate.getTime()!==x.startDate.getTime(),Y=O.endDate.getTime()!==x.endDate.getTime();(j||Y)&&D.push(R)}return Rt(A),Rt(a),{plans:g,updatedIds:D,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},Fu=!1;function Mu(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Fu}function Ut(e){return{name:e,startedAt:performance.now()}}function Wu(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Rt(e){if(!Mu())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Uu(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=rs(i,t);return Bu(n,t,r)}function Bu(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===K.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 Hu(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=qa(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function As(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}=Di(c,n,o.type),f=Ti.computeLagBetweenTasks(d,u,a);f!==o.lag&&Wt({kind:"update",linkId:o.id,lag:f},{port:t})}}function Cs(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 ft(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function pe(e,t,r=!0,i={}){let n=t?Vu(e,t):Gu(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await ju(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function hr(e,t){Is(e,t,"skip")}async function ju(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 Z()}function Vu(e,t){let r=new Set;for(let a of t)Yu(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Ss(i,e);return ks(i,n)}function Yu(e,t,r){let i=t.getParentId(e);for(;i&&!L(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function Ku(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+=$u(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=Ku(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 $u(e,t){return t?Number(e.realWorkHours)||0:ft(e.workHours,e.progress)}function Gu(e){let t=zu(e),r=Ss(t,e);return ks(t,r)}function zu(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ss(e,t){let r=new Map;for(let i of e)r.set(i,qu(i,t));return r}function qu(e,t){let r=0,i=e;for(;i&&!L(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ks(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ds={updateActivityDuration:Cs,updateTaskTiming:Xu("updateTaskTiming"),adjustLinkLagOnTaskMove:As,recordLastStartDate:Ju};function Ju(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Bt(e,t,r,i){for(let n of t){let a=n in Ds?Ds[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 Xu(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 N(e){return{ok:!1,reason:e}}function U(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function B(){return{allowed:!0}}function G(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 Ts={targetField:"name",canEdit(){return B()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return U()},transform(e,t){return M({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var _s={targetField:"description",canEdit(){return B()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(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??K.ASAP}var yr=100;function he(e){return e.progress>=yr}function et(e,t){return Et(e.type,t.hasChildren(e.id))}function Ps(e){return e.progress>0}function Es(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(p=>p.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(p=>p.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 Zu(e,t){let r=Zt(t);for(;!e.isWorkTime(r,st.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Zt(r);return r}function _i(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:st.HOUR})}function Pi(e,t){let r=Zu(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:st.HOUR})}var mr=new Set(["snet","snlt","mso"]),Ei=new Set(["fnet","fnlt","mfo"]),Ht=new Set(["asap","alap"]),gr="snet";function bt(e,t,r){if(!mr.has(r)&&!Ei.has(r))return e;let i=mr.has(r)?_i(t,e):Pi(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var Lt=()=>({constraintType:gr});var jt=e=>({constraintDate:e}),Rs=e=>({constraintDate:e});var bs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ls={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 Ya(e,t,r)}function ge(e,t,r){return Ka(e,t,r)}var Os={targetField:"durationHours",canEdit(e,t){return he(e)?G("completed","cant_edit_completed_activity"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?N("not_a_number"):w(r.inputUnit==="hours"?i:we(i,r.hoursPerDay))},validate(e,t,r){return ws(r)?tt(Ls.NEGATIVE_DURATION):Qu(t,r)?tt("unchanged"):U()},transform(e,t,r){if(ws(t))return M({},{autoSchedule:!1,postProcessors:[]});let i=tf(e,t,r),n=ef(e,t,r,i.violated);return{...M(n,{autoSchedule:!0,postProcessors:[bs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ge(i.constraintType,i.constraintDate,xs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ws(e){return Math.sign(e)===-1}function Qu(e,t){return e===t}function tf(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 ef(e,t,r,i=!1){let n={};i&&Object.assign(n,Lt(),jt(e.startDate));let a=be(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=xs(e,t,r);return s&&Object.assign(n,ye(s)),n}function xs(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ve=e=>({realWorkHours:e});var rf=0,nf=yr,Ns=0,Fs={targetField:"progress",canEdit(e,t){return Es(e)?G("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return af(r)?tt("out_of_range"):U()},transform(e,t,r){let i=sf(t),n=of(t),a=df(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ve(a.get(e.id)??0)},o=n?cf(e,t,i,r.hierarchy,a):[],c=n?ff(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?hf(e,t):void 0;return M(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function af(e){return e<rf||e>nf}function sf(e){return e===Ns}function of(e){return e===yr||e===Ns}function cf(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:lf(t,r,n.get(s)??0)}))}function lf(e,t,r){return{progress:e,autoScheduling:t,...ve(r)}}function df(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):ft(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):ft(e.workHours,t);return i.set(e.id,a),i}function uf(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 ff(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=[...uf(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of n){let o=pf(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function pf(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 hf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Ms={targetField:"cost",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):B()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return U()},transform(e,t,r){let i=yf(e,t,r.hierarchy);return M({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_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.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 Ws={targetField:"usedCost",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):B()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return U()},transform(e,t,r){let i=mf(e,t,r.hierarchy);return M({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function mf(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 Us={targetField:"workHours",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(){return U()},transform(e,t,r,i){let n=Bs(t,e.progress),a=String(i).trim()===""?[]:gf(e,t,n,r.hierarchy);return M({workHours:t,...ve(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Bs(e,t){return ft(e,t)}function gf(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??Bs(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 Ri(e,t){return e.getTime()<t.getTime()}function Ae(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Ar=e=>({durationHours:e});var Hs={targetField:"startDate",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):Ps(e)?G("has_progress","cant_edit_activity_with_progress"):B()},parseInput(e,t,r){return Ae(e)?w(Zt(e,"UTC")):N("invalid_date")},validate(e,t,r,i){if(vr(t,r))return tt("unchanged");let n=vf(e,r,i);return n||U()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return M({startDate:t,...Lt(),...jt(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=_i(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):{},...Lt(),...jt(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Af(e,n,i)}},trackEvent:"activity_start_date_entry"};function vf(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=Zt(i);return t.getTime()<n.getTime()?tt("before_parent_start"):null}function Af(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 Cf=99.999,Vs={targetField:"endDate",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):If(e)?G("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,st.DAY)?w(Pi(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:st.HOUR})):w(i)},validate(e,t,r,i){if(vr(e.endDate,r))return tt("unchanged");if(Sf(r,e))return tt("before_date_origin");if(kf(r,e))return tt("before_start_date");let n=Df(r,e,i);return n||U()},transform(e,t,r){let i=Tf(e,t),n=_f(e,t,r,!!i);return{...M(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function If(e){return e.progress>=Cf}function Sf(e,t){return t.dateOrigin?Ri(e,t.dateOrigin):!1}function kf(e,t){return Ri(e,t.startDate)}function Df(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,st.DAY)?null:tt("not_working_day"):null}function Tf(e,t){if(It(e)===K.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 _f(e,t,r,i=!1){let n={};Jt(e.type)&&!i&&js(e)?Object.assign(n,jt(e.startDate)):(i||js(e))&&Object.assign(n,Lt(),jt(e.startDate));let o=Pf(e,t,r),c=be(e.durationHours,o);return c&&(n.type=c),Object.assign(n,Ar(o)),n.endDate=t,n}function js(e){return Ht.has(It(e))}function Pf(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Ef=new Set(Object.values(K)),Ys={targetField:"constraintType",canEdit(e,t){return he(e)?G("completed","cant_edit_completed_activity"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){let t=String(e).toLowerCase();return Rf(t)?w(t):N("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let i=bf(e,t,r);return M(i,{autoSchedule:!0})}};function Rf(e){return Ef.has(e)}function bf(e,t,r){let i=wf(e,t);return{constraintType:t,...Rs(Lf(e,t,i,r))}}function Lf(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?bt(r,n,t):r}function wf(e,t){return Ht.has(t)?null:mr.has(t)?e.startDate:Ei.has(t)?e.endDate:e.constraintDate}var Ks={targetField:"constraintDate",canEdit(e,t){return he(e)?G("completed","cant_edit_completed_activity"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){return Ae(e)?w(e):N("invalid_date")},validate(){return U()},transform(e,t,r){let i=$s(e)?gr:It(e),n=r.calendars.getCalendar(e.calendarId),a=n?bt(t,n,i):t,s=Of(e,a);return M(s,{autoSchedule:!0})}};function Of(e,t){return{constraintDate:t,...$s(e)?Lt():{}}}function $s(e){return Ht.has(It(e))||!e.constraintType}var Gs={targetField:"calendarId",canEdit(){return B()},parseInput(e){let t=String(e).trim();return xf(t)?N("empty_calendar"):w(t)},validate(e,t,r,i){return Nf(e.calendarId,r)?tt("unchanged"):i.calendars.getCalendar(r)?U():tt("unknown_calendar")},transform(e,t,r){return M(Ff(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function xf(e){return e===""}function Nf(e,t){return e===t}function Ff(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Mf(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 Mf(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var zs={targetField:"customId",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):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"):w(t)},validate(){return U()},transform(e,t){return M({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var qs={targetField:"subcontractId",canEdit(){return B()},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)?N("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?N("not_an_integer"):w(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 Js={targetField:"responsableIds",canEdit(){return B()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Cr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(xe).filter(i=>i!==null);return M({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Xs={targetField:"tagIds",canEdit(){return B()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Cr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(xe).filter(i=>i!==null);return M({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Wf=new Map([[P.TEXT,Ts],[P.DESCRIPTION,_s],[P.DURATION,Os],[P.PROGRESS,Fs],[P.COST,Ms],[P.USED_COST,Ws],[P.HH_WORK_TIME,Us],[P.START_DATE,Hs],[P.END_DATE,Vs],[P.CONSTRAINT_TYPE,Ys],[P.CONSTRAINT_DATE,Ks],[P.CALENDAR_ID,Gs],[P.CUSTOM_ID,zs],[P.SUBCONTRACT_ID,qs],[P.RESPONSABLES,Js],[P.TAGS,Xs]]);function Vt(e){return Wf.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"},bi={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 Uf=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Zs=new Set(Uf);function rt(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Qs(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:Bf(e.baselineSnapshot),criticalPath:Hf(e.criticalPath)}}function Tt(e){return e===null?null:new Date(e)}function Bf(e){return e===null?null:{...e,startDate:Tt(e.startDate),endDate:Tt(e.endDate)}}function Hf(e){return e===null?null:{...e,earlyStart:Tt(e.earlyStart),earlyFinish:Tt(e.earlyFinish),lateStart:Tt(e.lateStart),lateFinish:Tt(e.lateFinish)}}function Q(e){return structuredClone(e)}var ro=200;function Yt(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%ro===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 Kt(e,t,r){to(e,t,r.patch);for(let i of r.cascadeMutations??[])to(e,i.activityId,i.fields)}function to(e,t,r){for(let[i,n]of Object.entries(r)){if(!Zs.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);rt(e,t,i,n)}}async function io(e,t,r,i){let n=[],a=0;for(let s of r){a+=1,a%ro===0&&await Z();let o=jf(e,t,s,i);o&&n.push(o)}return n}function jf(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 Vf(r,i.get(r),n);let s=wi(a,n);return Yf(s,i,r,n),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(n)}}function Vf(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function Yf(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 wi(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)||!Li(i[s],n[s]))&&(r[s]={before:eo(i[s]),after:eo(n[s])});return r}function eo(e){return e===null||typeof e!="object"?e:Q(e)}function Li(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)=>Li(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)&&Li(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 Oi(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 Kf=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function wt(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(Kf);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 $f=e=>e.type==="project",Gf=(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:wt(String(s));return Ie(a(e.startDate),a(e.endDate),t,n)};function zf(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(!$f(o)){let d=Gf(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),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}function Ot(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),zf(r,t,e)}function nt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var qf=e=>e.type==="project",Jf=e=>nt(e),Xf=(e,t,r,i)=>{let n=Jf(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 xi(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(!qf(c)){let u=Xf(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),m=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*m}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function $t(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)=>rt(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),xi(n,t,i,r)}var no=e=>Math.round(e*100)/100;function Zf(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Qf(e,t){let r=no(e),i=no(t);return r>99.99?Ft.DONE:i>r?Ft.OVERDUE:e>0&&r>i?Ft.ADVANCEMENT:e===0&&t===0?Ft.WAITING:e>0&&r<i?Ft.DOING:Ft.WAITING}function St(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=Qf(a,Zf(i,t));i.status!==s&&(rt(e,n,Xe,s),r.push(n))}),r}function Ni(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:()=>Ni(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}Ni.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var gt=Ni;function tp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Dr(e){return tp(e)&&!isNaN(e.getTime())}function S(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 pt(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 ep=e=>e?e.$level===1:!1,rp=e=>e.type==="project",ip=e=>e.$level!==0,np=e=>e.type==="task",ap=e=>e.type==="task"||e.type==="milestone",ot={byFirstLevel:ep,filterByParentType:rp,avoidSubproject:ip,byTaskType:np,byTaskTypeAndMilestone:ap};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 ao(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=sp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=op({gantt:t,subprojectsWithNoLinks:a}),o=cp({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:lp,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function sp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ot.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function op(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=ot.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function cp(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 lp(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 so({gantt:e,linkProperty:t,direction:r}){try{let i=dp(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return up(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function dp(e,t){return e.getTaskByTime().filter(ot.avoidSubproject).filter(ot.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function up(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 oo({gantt:e,direction:t,linkProperty:r}){try{let i=fp(e),n=new Set,a=new Set,s=new Set;t==="backward"&&yp(i).forEach(d=>{n.add(d.id)});let o=pp(i,t,r),c=hp(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 fp(e){return e.getTaskByTime().filter(ot.filterByParentType).filter(ot.avoidSubproject)}function pp(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 hp(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function yp(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function co({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=mp(r),o=gp(r),c=a[s];if(!Array.isArray(c))return;vp(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function mp(e){return e==="forward"?"$source":"$target"}function gp(e){return e==="forward"?"target":"source"}function vp(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Ne={identifySecondLevelActivities:ao,identifyInitialActivities:so,identifyParentsWithAndWithoutLinks:oo,identifyForbiddenActivities:co};function Tr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Fi({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===H.FS&&t===0?pt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Fe(r,e,i,n)}function lo({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:S(r,n,e,i),ef:n}}function uo({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=S(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 pt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Mi=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=uo({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=lo({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=Fi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=S(this.activityCalendar,i,t,this.activity);t>0&&(n=Fe(n,"ss",this.activityCalendar,this.activity));let a=S(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=Fi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=S(this.activityCalendar,i,t,this.activity),a=S(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=pt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=S(this.activityCalendar,i,t,this.activity),a=S(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=S(this.activityCalendar,r,t,this.activity),n=S(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Fe(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},fo=Mi;var Wi=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:S(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=S(this.activityCalendar,r,n,this.activity),s=S(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=S(this.activityCalendar,o,n,this.activity),s=S(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=S(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=S(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=S(this.activityCalendar,c,n,this.activity),o=S(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=S(this.activityCalendar,o,i,this.activity),a=S(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=S(this.activityCalendar,r,i,this.activity),s=S(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=S(this.activityCalendar,c,i,this.activity),s=S(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:S(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=gt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),pt({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),gt.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},po=Wi;function ho(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=Ap(t),l=null;if(s==="forward"){let d=Cp(o,i,n,a);l=new fo(d,t,a),l=l.calculate()}else{let d=Ip(o,i,n,a);l=new po({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function Ap(e){return{duration:e.duration,calendarId:e.calendar_id}}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);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 Ip(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 go(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Sp(t.id,r))return null;let a=kp(t.id,i),s=Dp(a,r);return s.length===0?null:Tp(s,n)}function Sp(e,t){return t.has(e)}function kp(e,t){let r=t.get(e);return r?r.childrens:[]}function Dp(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Tp(e,t){if(t==="forward"){let r=yo(e,"es"),i=mo(e,"ef");return{es:r,ef:i}}else{let r=yo(e,"ls"),i=mo(e,"lf");return{ls:r,lf:i}}}function yo(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function mo(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Ui={parentWithLinks:ho,parentWithNoLinks:go};var Bi=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=Ui.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=Ui.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)})}},vo=Bi;var Hi=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(ot.byFirstLevel).filter(ot.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}}},Ao=Hi;var ji=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(ot.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 Ao({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:gt(i.start_date).clone(),lf:gt(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=gt(t.start_date).clone(),n=gt(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=S(r,n,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(i=t.constraint_date,n=S(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=S(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 vo({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()}},Gt=ji;function _p(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=S(r,n,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=S(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=S(r,n,e.duration,e)}else if(t===y.MFO){let n=new Date(e.constraint_date);i.es=S(r,n,-e.duration,e),i.ef=n}return i}var _r=_p;var Vi=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=pt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[H.FF,H.SF].includes(a)?(l=S(s,o,i,this.referenceActivity),c=S(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=S(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=S(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 pt({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},Co=Vi;var Me=class extends Co{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Gt(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=S(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 Yi=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=Yi;var Ki=(e,t)=>()=>t()===e;var $i=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Pp=16,We=async e=>performance.now()-e>Pp?(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 Gi=class extends Gt{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 p=_r(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[y.MSO,y.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let m=i.end_date;a===y.MFO&&(m=Math.max(p.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)}},Io=Gi;var zi=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=S(s,o,r,this.activity),u=S(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=gt(r).clone();return S(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=gt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),pt({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),gt.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=S(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=S(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=S(i,l,a,this.activity),c=S(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=S(i,r,a,this.activity),o=S(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=S(i,c,a,this.activity),o=S(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=S(i,r,n,this.activity),o=S(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=S(i,l,n,this.activity),o=S(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=S(i,r,n),s=S(i,o,a,this.activity),{ls:o,lf:s}):(o=S(i,r,n,this.activity),s=S(i,o,a,this.activity),{ls:o,lf:s})}},So=zi;var qi=class extends So{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 Gt(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=S(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:S(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))}},ko=qi;function Ep(e,t,r){let i={ls:null,lf:null};return r===y.MSO&&(i.ls=t.constraint_date,i.lf=S(e,i.ls,t.duration,t)),r===y.MFO&&(i.lf=t.constraint_date,i.ls=S(e,i.lf,-t.duration,t)),i}var Do=Ep;var Ji=class extends Gt{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 ko({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=Do(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=S(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=S(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=S(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=S(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=S(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=S(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:S(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}},To=Ji;function _o(){return null}var Po=({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 Xi=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)})}},Eo=Xi;var Zi=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)}},Ro=Zi;var bo=e=>({totalFloat:new Eo(e.totalFloat).getTotalFloat(),freeFloat:new Ro(e.freeFloat).getFreeFloat()});var Qi=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=Po({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=bo(u);o.set(l,f),c.set(l,p),s=await We(s)}return{totalFloatMap:o,freeFloatMap:c}};var tn=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=Ki(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||_o(),$i(this.gantt))return!1;let o=new Io(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new To(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 Qi({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}}}},Lo=tn;var Rp=e=>e==="fnet"||e==="fnlt"||e==="mfo",bp=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Lp(e,t){let r=e.constraintDate;if(!r||!Rp(e.constraintType))return r;let i=bp(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()?gi(e,t):r}function wp(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 Op(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 xp(e){let t=Op(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:Lp(i,e)})}),r}function Np(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 Fp(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 wo(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=wp(u);return r.set(l,f),f},n=Fp(e);await Z();let a=xp(e);await Z();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await Z();let o=Np(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 Mp=1e3;function Wp(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 en(e,t,r=()=>!0){if(!r())return null;let i=await wo(e,t);if(!r())return null;let n=new Lo(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>=Mp&&(l=0,await Z(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,Wp(d,f,s))}return r()?c:null}async function Er(e,t,r=()=>!0){let i=await en(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 zt(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=nt(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 Oo=new Set;var xo=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]),Up=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"]),Bp=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Fo(e){return!Bp.has(e.kind)}var Hp=new Set;function jp(e){return e.kind==="inline-edit"?Be.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Be.has(t.column)):!1}function rn(e,t){return!(Up.has(e.kind)||t.has(e.kind)||jp(e))}function Mo(e){return rn(e,Hp)}function He(e){return rn(e,Oo)}function Wo(e){return rn(e,xo)}function nn(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 Vp(e){return Wo(e)&&nn(e)}var No=new Set([P.PROGRESS,P.HH_WORK_TIME,P.DURATION,P.COST,P.USED_COST,P.REAL_COST]);function Yp(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?No.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>No.has(t.column)):!1}var at={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 Uo(e,t,r){let i=new Set;t.ran&&i.add(at.AUTOSCHEDULE),i.add(at.PARENT_BOUNDS),Yp(e)&&i.add(at.PARENT_PROGRESS),nn(e)&&i.add(at.REAL_WORK);let n=!r.skipAutoSchedule;return n&&Wo(e)&&i.add(at.EXPECTED_PROGRESS),n&&Vp(e)&&i.add(at.REAL_COST),n&&He(e)&&!r.skipCriticalPath&&i.add(at.CRITICAL_PATH),i}async function z(e,t){let r=Kp(t);r.has(at.AUTOSCHEDULE)&&await qp(e.adapter,t);let i=r.has(at.AUTOSCHEDULE)?await $p(e,t.autoscheduleFrom):zp();return await Jp(e.adapter,t,i.scheduledIds,r),await Xp(e,r,t.now),i}function Kp(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,i=new Set(Uo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&i.add(at.PARENT_PROGRESS),i}async function $p(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=Gp(e.adapter,i.updatedIds);return Le(e.adapter,i),n}function Gp(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 zp(){return{scheduledIds:[]}}async function qp(e,t){let r=t.collectDirty?t.collectDirty([]):Oi(t.recomputeParentsFrom,[]);r.size!==0&&await pe(e,r,!1)}async function Jp(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Oi(t.recomputeParentsFrom,r);await pe(e,n,i.has(at.PARENT_PROGRESS),{recomputeRealWork:i.has(at.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function Xp(e,t,r){t.has(at.EXPECTED_PROGRESS)&&r!==null&&(Zp(e.adapter)&&$t(e.adapter,r,e.defaultBaseCalendarId??null),Ot(e.adapter,r),St(e.adapter,e.sector.statusCriteria)),t.has(at.REAL_COST)&&zt(e.adapter),t.has(at.CRITICAL_PATH)&&await Er(e.adapter,e.sector.hoursPerDay)}function Zp(e){let t=!1;return e.forEachActivity(r=>{nt(r)&&(t=!0)}),t}var Qp=new Set([P.CONSTRAINT_TYPE,P.CONSTRAINT_DATE]),th=new Set(["mso","mfo"]);function Rr(e){return Qp.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||Ht.has(a)||th.has(a))return!1;let s=an(n.startDate),o=an(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=eh(t,a,String(n.calendarId??""),i),l=an(n.constraintDate);return rh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function eh(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?bt(e,n,t):e}function an(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 rh(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 z(e,Bo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=i(s,o);a=a||c}if(a){let s=await z(e,Bo(t));n=nh(n,s.scheduledIds)}return He(t.action)&&await z(e,ih(t)),{scheduledIds:n}}function Bo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function ih(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function nh(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function ah(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 sn(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&&!ah(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 V(e,t){let r=oh(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let d=lh(n);ch(e,n,d,i,r)}let a=t.sirDetection==="before-diff"?sn(i,e,r):[],s=sh(t.correlativeShifts,r),o=await io(e,i,r,s),c=t.sirDetection==="after-diff"?sn(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 sh(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 oh(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 ch(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(wi(s,o)).length!==0&&(i.set(a,s),n.add(a))}}function lh(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 Ho(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=Vt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);dh(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 D=i.getActivity(e.activityId),R=D?D.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 p=o.transform(c,d.value,n,d.raw),m=Yt(e.activityId,p),k=await q(i,m),C=Se(i,String(e.activityId)),I=c.constraintDate;Kt(i,e.activityId,p),Bt(e.activityId,p.postProcessors??[],i,k.get(String(e.activityId))??null);let T=ke(C,i,String(e.activityId));if(e.column===P.CUSTOM_ID){let D=k.get(String(e.activityId)),R=D?D.customId:null,x=typeof R=="string"?R:null,O=typeof d.value=="string"?d.value:null;x!==O&&r.customIdTracker.trackCustomIdChange(x,O)}let _=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:D=>Sr(e.activityId,m,D),now:r.now,options:t}),v=Rr(e.column),{scheduledIds:h}=await(v?wr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:_(),revertTargets:br(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:I}],revert:(D,R)=>Lr(D,R,i,n.calendars)}):z({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},_())),g=(p.trackingEvents??[]).map(D=>({name:D.name,properties:D.properties??{}})),A=Ce(e.activityId,p.constraintWarning);return{ok:!0,changes:await V(i,{source:e,beforeSnap:k,touchedIds:m,scheduledIds:h,sirDetection:"before-diff",links:T,trackingEvents:g,...A?{warnings:[A]}:{},hoursPerDay:s.hoursPerDay})}}function dh(e){return e===P.DURATION||e===b.AUTO_SCHEDULING}function uh(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 fh(e,t,r,i){return e.map((n,a)=>{let s=n.kind==="create"?i?.get(a):void 0,o=Wt(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 ph(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function jo(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 on([vh(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Vo(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>yh(s,i)),a=hh(e.operations);return on(n,e,t,r,a)}function hh(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 yh(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:mt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:mt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function on(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let{activityIds:l,links:d}=uh(e,a),u=await q(a,l),f=fh(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 p=mh(f,d,a),{scheduledIds:m}=await z({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),k=Or(f,d,a);return{ok:!0,linkVerdicts:f.map((C,I)=>C.rejected===null?{operationIndex:I,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:I,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:ph(d),changes:await V(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:m,links:k,hoursPerDay:o.hoursPerDay})}}function mh(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=gh(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function gh(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 vh(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:mt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:mt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Yo(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:mt(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 k=i.getLink(m);k&&f.push(k)}let p=s?dr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):ur({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return on(p.operations,e,t,r)}var vt={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 dt(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(Go);let r=[];Ko(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),Ah(a,n)}n+=1;let s=yi(String(a.id),e);s.sort(Go),Ko(r,s)}return i}function Ko(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function $o(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}var Go=(e,t)=>$o(e)-$o(t);function Ah(e,t){e.correlativeId=t}function ln(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=cn(l,b.WORK_HOURS),u=Ch(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||L(o))break;r=o}}function zo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||L(i)||ln(i,t)}function cn(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ch(e,t,r,i){return i.hasChildren(e)?cn(t,b.REAL_WORK_HOURS):ft(r,cn(t,b.PROGRESS))}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.USED_COST))}t.setActivityField(r,b.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function qo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||L(i)||dn(i,t)}function Ih(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function un(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+=Sh(c,b.COST))}t.setActivityField(r,b.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Jo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||L(i)||un(i,t)}function Sh(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}),Xo="New Master Plan",Zo="New Activity";var kh=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Qo=new Set(kh);function Dh(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"||!Qo.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function tc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=Dh(e.activityOverrides??{}),n=e.numTasksInGantt===0?Xo:Zo,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=Th(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 Th(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function _h(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&&Mt(t.type):Ph(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=Si,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:_h(t)}}function Ph(e){return Mt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Fr(e,t,r,i){let n=t,a=n==="0",s=fn(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=ct(c),d=s.map(ct).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=ct(c),d=s.map(ct).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(ct))+1}var re=Number.MAX_SAFE_INTEGER,ec=Number.MAX_SAFE_INTEGER-1;function ct(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:re}function fn(e,t){let r=[];return e.forEachActivity(i=>{Pt(i.parentId)===t&&r.push(i)}),r}function rc(e,t,r){let i=e,n=qt(e,r);for(;n!=null&&t.has(n);)i=n,n=qt(n,r);return i}function Mr(e,t,r){let i=new Set([e]),n=Pt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=Pt(r.getActivity(n)?.parentId)}return!1}function qt(e,t){let r=t.getActivity(e);if(!r)return null;let i=Pt(r.parentId),n=ut(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function ic(e,t,r,i){let n=ut(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(ct);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 pn(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=Eh(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=bh(e.activityId,i,o),m=c.next(),k={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Fh(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:m,activityOverrides:e.overrides??{}},I=tc(k,{getActivity:g=>i.getActivity(g),calculateEndDate:g=>i.calculateEndDate(g),getClosestWorkTime:g=>i.getClosestWorkTime(g)}).newTask;I.realWorkHours=ft(I.workHours,I.progress),wh(I,e,t,u,d,r);let T=Fr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);I.correlativeId=T;let _=new Set([p]);d&&_.add(d.id);let v=d!==null&&i.getChildren(d.id).length===0,h=r.skipBeforeSnap?new Map:await q(i,_);return i.addActivity(I),Oh(e,p,d,i,v),zo(p,i),qo(p,i),Jo(p,i),xh(i,p,h,_,r),{ok:!0,newId:p,parent:d,newActivity:I,beforeSnap:h,initialTouched:_}}function Eh(e,t){let r=L(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=Rh(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function Rh(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 bh(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function Lh(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function wh(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=Lh(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??i,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Oh(e,t,r,i,n){if(!r)return;let a=De({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:s=>i.getActivity(s)??null});if(a){for(let[s,o]of Object.entries(a.fields))rt(i,a.parentId,s,o);a.promotionSnapshot&&i.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function xh(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=dt(e);n.skipBeforeSnap||kr(e,a,new Set([String(t)]),r,i)}async function Nh(e,t,r,i,n){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:vt.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),V(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:i,trackingEvents:[l],hoursPerDay:n})}async function nc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=await pn(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 z({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 Nh(i,e,s,d,a.hoursPerDay)}}function Fh(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 Mh(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=fn(t,r).sort((a,s)=>ct(a)-ct(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function Wh(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function ac(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=Mh(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 I of e.activities){let T=l.get(I.originalParentId),_,v,h;T!==void 0?_=T:(_=s.parentId,u===void 0?(v=s.firstAfter,h=s.firstBefore):v=u);let g=await pn({kind:"activity-create",parentId:_,afterSiblingId:v,beforeSiblingId:h,...I.activityId?{activityId:I.activityId}:{},overrides:Wh(I.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.referenceActivityId});if(!g.ok)return g;if(I.baselineSnapshot!==void 0){let A=I.baselineSnapshot;i.setActivityField(g.newId,"baselineSnapshot",A?{...A,startDate:A.startDate?new Date(A.startDate):null,endDate:A.endDate?new Date(A.endDate):null}:null)}l.set(I.originalId,g.newId),d.push(g.newId),T===void 0&&(u=g.newId)}let f=dt(i),p=new Set(d.map(String));kr(i,f,p,o,c);for(let I of d)c.add(String(I));let m=[];for(let I of e.links){let T=l.get(I.source),_=l.get(I.target);if(T===void 0||_===void 0)continue;let v={kind:"create",source:T,target:_,type:I.type,lag:mt(I.lag,a.hoursPerDay)},h=Wt(v,{port:i,newLinkId:I.linkId?()=>I.linkId:r.linkIdGen.next});m.push({op:v,finalLinkId:h.applied?h.linkId:null,rejected:h.applied?null:h.rejected??"link_op_rejected"})}let{scheduledIds:k}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),C=Or(m,new Map,i);return{ok:!0,changes:await V(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:k,links:C,hoursPerDay:a.hoursPerDay})}}function sc(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 oc(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 xt(e,t){ln(e,t),dn(e,t),un(e,t)}function cc(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 lc(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 Uh(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 Bh(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=Uh(e.promotionSnapshot)??(i?{type:de,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Bh(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 dc(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 uc=200;async function fc(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 A of e.activityIds)if(!i.getActivity(A))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let o=cc(e.activityIds,i),c=lc(o,i),l=new Set;for(let A of e.activityIds){let D=i.getActivity(A);if(!D)continue;let R=D.parentId;if(L(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 A of c){let D=i.getLink(A);D&&f.set(A,{...D})}let p=new Set,m=0;for(let A of o){m+=1,m%uc===0&&await Z();let D=i.getActivity(A);if(!D)continue;let R=L(D.parentId)?null:i.getActivity(String(D.parentId)),x=R?.hasNewActivities===!0&&R.newActivityIds.some(j=>String(j)===String(A));(D.isNewActivity===!0||x)&&p.add(A);let O=D.customId;typeof O=="string"&&O.length>0&&a.releaseCustomId(O)}for(let A of c)i.removeLink(A);let k=jh(i,o),C=0;for(let A of o)C+=1,C%uc===0&&await Z(),i.removeActivity(A);for(let A of l){let D=i.getActivity(A);if(!D)continue;Hh(D,p,i);let R=i.getChildren(A),x=Te({parent:D,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(A),computeEndDate:(O,j)=>i.calculateEndDate({startDate:O,durationHours:j,task:D}),idsRemoved:o});if(!x){hr(A,i);continue}for(let[O,j]of Object.entries(x.fields))rt(i,A,O,j);if(D.customId==null||D.customId===""){let O=qt(A,i),j=O?i.getActivity(O)?.customId:null,Y=a.generateCustomIdForRestoredChild(typeof j=="string"&&j?j:null);i.setActivityField(A,b.CUSTOM_ID,Y)}}for(let A of l)xt(A,i);let I=dt(i),{scheduledIds:T}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),_={name:vt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(_.properties.event_source=e.eventSource);let v=new Map;for(let[A,D]of f)v.set(A,D);let h=new Map;for(let A of o){let D=u.get(String(A));D&&h.set(String(A),D)}let g=await V(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:T,sirDetection:"after-diff",links:Vh(f),trackingEvents:[_],hoursPerDay:s.hoursPerDay,correlativeShifts:I});return{ok:!0,changes:k.length>0?{...g,viewState:k}:g,__beforeSnap:h,__beforeLinks:v}}function Hh(e,t,r){let i=dc({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))rt(r,i.parentId,n,a)}function jh(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 Vh(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 Wr(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)||(pc(s,a,t)||pc(a,s,t))&&i.push(String(n.id))}return i}function pc(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||L(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function hc(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=L(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 h=i.getActivity(c);if(!h)return{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND};if((h.parentId===null?"0":String(h.parentId))!==e.parentId)return{ok:!1,reason:E.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Pt(l),u=String(e.parentId),f=d!==u,p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let m=await q(i,p);f&&i.setActivityField(e.activityId,b.PARENT,u);let k=Fr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,b.CORRELATIVE_ID,k),f){if(!o){let h=i.getActivity(e.parentId);if(h){let g=h.customId,A=Mt(h.type)&&i.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,D=De({parentId:e.parentId,newChildId:e.activityId,getParent:R=>i.getActivity(R)??null,isCurrentlyLeaf:A,promotionSource:"reparent"});if(D){for(let[R,x]of Object.entries(D.fields))rt(i,D.parentId,R,x);D.promotionSnapshot&&i.setPromotionSnapshot(D.parentId,D.promotionSnapshot),D.fields.customId===null&&xr(g,r.customIdTracker)}}}if(d!=="0"){let h=i.getActivity(d);if(h){let g=i.getChildren(d),A=Te({parent:h,remainingChildIds:g.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(D,R)=>i.calculateEndDate({startDate:D,durationHours:R,task:h}),idsRemoved:new Set([e.activityId])});if(A){for(let[j,Y]of Object.entries(A.fields))rt(i,d,j,Y);let D=qt(d,i),R=D?i.getActivity(D)?.customId:null,x=typeof R=="string"&&R?R:null,O=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(d,b.CUSTOM_ID,O)}}}}f&&(d!=="0"&&xt(d,i),o||xt(e.parentId,i));let C=dt(i);for(let h of C){if(p.add(h.activityId),m.has(h.activityId))continue;let g=i.getActivity(h.activityId);if(!g)continue;let A=J(g);h.before!==void 0&&(A.correlativeId=h.before),m.set(h.activityId,A)}let I=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:T}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...I],now:r.now,options:t,recomputeParentProgress:f}),_=f?Wr([e.activityId],i):[],v={name:vt.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&&(v.properties.event_source=e.eventSource),{ok:!0,changes:await V(i,{source:e,beforeSnap:m,touchedIds:p,scheduledIds:T,sirDetection:"before-diff",trackingEvents:[v],hoursPerDay:a.hoursPerDay})}}async function yc(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,f=new Set(s),p=[...e.activityIds].sort((h,g)=>{let A=i.getActivity(h),D=i.getActivity(g),R=A?ct(A):re,x=D?ct(D):re;return R-x});for(let h of p){if(!i.getActivity(h)){c.push({activityId:h,reason:E.ACTIVITY_NOT_FOUND}),f.delete(h);continue}if(Mr(h,u,i))continue;let A=ta(h,f,i);if(A==null){c.push({activityId:h,reason:E.INDENT_NO_ELIGIBLE_SIBLING}),f.delete(h);continue}let D=i.getActivity(h)?.parentId,R=L(D)?"0":String(D);d.push({activityId:h,newParentId:A,oldParentId:R}),u.add(h),o.add(h),o.add(A),R!=="0"&&o.add(R)}let m=await q(i,o);for(let{activityId:h,newParentId:g}of d)i.setActivityField(h,b.PARENT,g),i.setActivityField(h,b.CORRELATIVE_ID,ec),l.push(h);let k=new Set;for(let{activityId:h,newParentId:g}of d){if(k.has(g))continue;k.add(g);let A=i.getActivity(g);if(!A)continue;let D=A.customId,R=Mt(A.type)&&i.getChildren(g).filter(j=>!l.includes(j)).length===0,x=A.hasNewActivities&&A.newActivityIds.some(j=>String(j)===String(h)),O=De({parentId:g,newChildId:h,getParent:j=>i.getActivity(j)??null,isCurrentlyLeaf:R,promotionSource:"reparent"});if(O){for(let[j,Y]of Object.entries(O.fields))rt(i,O.parentId,j,Y);O.promotionSnapshot&&i.setPromotionSnapshot(O.parentId,O.promotionSnapshot),x||(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(D,r.customIdTracker)}let C=new Set;for(let h of d)h.oldParentId!=="0"&&C.add(h.oldParentId),C.add(h.newParentId);for(let h of C)xt(h,i);let I=dt(i);for(let h of I){if(o.add(h.activityId),m.has(h.activityId))continue;let g=i.getActivity(h.activityId);if(!g)continue;let A=J(g);h.before!==void 0&&(A.correlativeId=h.before),m.set(h.activityId,A)}let{scheduledIds:T}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),_=Wr(l,i),v={name:vt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(h=>({activity_id:h.activityId,reason:h.reason})),invalid_link_ids:_}};return e.eventSource!==void 0&&(v.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let g=c.find(A=>String(A.activityId)===String(h));return g?{activityId:String(h),ok:!1,reason:g.reason}:{activityId:String(h),ok:!0}}),changes:await V(i,{source:e,beforeSnap:m,touchedIds:o,scheduledIds:T,trackingEvents:[v],hoursPerDay:a.hoursPerDay})}}async function mc(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 h of e.activityIds){let g=h;i.getActivity(g)&&(o.set(g,hi(g,i)),c.set(g,rc(g,s,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],m=new Set,k=[...e.activityIds].sort((h,g)=>{let A=i.getActivity(h),D=i.getActivity(g),R=A?ct(A):re,x=D?ct(D):re;return R-x});for(let h of k){let g=h,A=i.getActivity(g);if(!A){d.push({activityId:g,reason:E.ACTIVITY_NOT_FOUND});continue}if(Mr(g,m,i))continue;let D=A.parentId;if(L(D)){d.push({activityId:g,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let R=String(D),x=i.getActivity(R);if(!x){d.push({activityId:g,reason:E.ACTIVITY_NOT_FOUND});continue}let O=x.parentId;if(L(O)){d.push({activityId:g,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let j=String(O),Y=hi(R,i)+1,it=c.get(g);if(it!=null&&s.has(it)){let Ee=o.get(it)??-1,lt=o.get(g)??-1;Ee>=0&&lt>=0&&(Y+=lt-Ee)}p.push({activityId:g,grandparentKey:j,oldParentKey:R,targetIndexInGrandparent:Y}),m.add(g),l.add(String(g)),l.add(String(R)),j!=="0"&&l.add(String(j)),f.add(R)}let C=await q(i,l);for(let h of p){i.setActivityField(h.activityId,b.PARENT,h.grandparentKey);let g=ic(i,h.grandparentKey,h.targetIndexInGrandparent,h.activityId);i.setActivityField(h.activityId,b.CORRELATIVE_ID,g),u.push(h.activityId)}for(let h of f){let g=i.getActivity(h);if(!g)continue;let A=i.getChildren(h),D=Te({parent:g,remainingChildIds:A.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(h),computeEndDate:(Y,it)=>i.calculateEndDate({startDate:Y,durationHours:it,task:g}),idsRemoved:new Set(p.filter(Y=>Y.oldParentKey===h).map(Y=>Y.activityId))});if(!D){hr(h,i);continue}for(let[Y,it]of Object.entries(D.fields))rt(i,h,Y,it);let R=qt(h,i),x=R?i.getActivity(R)?.customId:null,O=typeof x=="string"&&x?x:null,j=r.customIdTracker.generateCustomIdForRestoredChild(O);i.setActivityField(h,b.CUSTOM_ID,j)}let I=new Set;for(let h of f)I.add(String(h));for(let h of p)h.grandparentKey!=="0"&&I.add(String(h.grandparentKey));for(let h of I)xt(h,i);let T=dt(i);for(let h of T){if(l.add(h.activityId),C.has(h.activityId))continue;let g=i.getActivity(h.activityId);if(!g)continue;let A=J(g);h.before!==void 0&&(A.correlativeId=h.before),C.set(h.activityId,A)}let{scheduledIds:_}=await z({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}),v={name:vt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(h=>({activity_id:String(h.activityId),reason:h.reason}))}};return e.eventSource!==void 0&&(v.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let g=d.find(A=>String(A.activityId)===String(h));return g?{activityId:String(h),ok:!1,reason:g.reason}:{activityId:String(h),ok:!0}}),changes:await V(i,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:_,trackingEvents:[v],hoursPerDay:a.hoursPerDay})}}async function gc(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=Vt(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=Yt(e.activityId,l),u=await q(i,d);Kt(i,e.activityId,l),Bt(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await z({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}),p=(l.trackingEvents??[]).map(m=>({name:m.name,properties:m.properties??{}}));return{ok:!0,changes:await V(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function vc(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 k=Yh(m,r);if(s.push(k.verdict),!k.verdict.ok||!k.changes)continue;let C=Yt(m.activityId,k.changes);Kh(o,C,r);for(let v of C)c.add(v);let I=Se(i,m.activityId),T=Ir(i,String(m.activityId));Kt(i,m.activityId,k.changes),Bt(m.activityId,k.changes.postProcessors??[],i,T),d.push(...ke(I,i,m.activityId)),f||=!!k.changes.needsAutoSchedule;for(let v of k.changes.trackingEvents??[])l.push({name:v.name,properties:v.properties??{}});let _=Ce(m.activityId,k.changes.constraintWarning);_&&u.push(_)}let{scheduledIds:p}=await z({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 V(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Yh(e,t){let{ctx:r}=t,i=e.activityId,n=Vt(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 Kh(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 hn=P.CUSTOM_ID;async function Ac(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=[],p=[],m=[],k=!1;for(let _ of e.edits){let v=$h(_,r);if(o.push(v.verdict),!v.verdict.ok||!v.changes)continue;let h=Ce(_.activityId,v.changes.constraintWarning);h&&m.push(h);let g=Yt(_.activityId,v.changes);Jh(c,g,r);for(let O of g)u.add(O);qh(l,_,c),br(_.column)&&d.add(String(_.activityId));let A=Se(i,_.activityId),D=Ir(i,String(_.activityId)),R=Gh(_,r),x=v.changes;Kt(i,_.activityId,x),Bt(_.activityId,v.changes.postProcessors??[],i,D),zh(_,R,r),p.push(...ke(A,i,_.activityId)),k||=!!v.changes.needsAutoSchedule;for(let O of v.changes.trackingEvents??[])f.push({name:O.name,properties:O.properties??{}})}let C={action:e,autoscheduleFrom:k?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},I=l.size>0,{scheduledIds:T}=await(I?wr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([_])=>!d.has(_)).map(([_,v])=>({activityId:_,priorConstraintDate:v})),revert:(_,v)=>Lr(_,v,i,r.ctx.calendars)}):z({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},C));return{ok:!0,verdicts:o,changes:await V(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:T,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:m,hoursPerDay:a.hoursPerDay})}}function $h(e,t){let{ctx:r}=t,i=e.activityId,n=Vt(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===hn&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,p=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),p))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 Gh(e,t){if(e.column!==hn)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function zh(e,t,r){if(e.column!==hn)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 qh(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 Jh(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 Xh(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 Cc(e,t,r,i){let n=new Set,a=new Set;for(let s of e)Xh(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));Cc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},n),Cc(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);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}for(let c of i){let l=t.adapter.getLink(c.id);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function Sc(e){return typeof e=="string"&&e.length>0?wt(e):e instanceof Date?e:null}function yn(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 Ur(e,t){let r=yn(e.duration),i=yn(e.cost),n=yn(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:Sc(e.start_date),endDate:Sc(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 kc(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=>Ur(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 Zh(e){let t=nt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Dc(e){let t=[];return e.forEachActivity((r,i)=>{let n=Zh(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 Br(e,t,r,i,n=null){let a=new Set;for(let s of kc(e,t,i))a.add(s);if(r)for(let s of $t(e,r,n))a.add(s);for(let s of Dc(e))a.add(s);for(let s of zt(e))a.add(s);return[...a]}function Tc(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=Qh(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(nt(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 Qh(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=nt(i);if(!n)return 0;if(t==="COST")return Hr(n.cost);if(t==="HH")return Hr(n.workHours);let a=i.type;return a==="project"?_c(e,r):a==="milestone"?0:Hr(n.durationDays)}function _c(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=nt(n);if(!a)continue;let s=n.type;s==="project"?r+=_c(String(i),t):s!=="milestone"&&(r+=Hr(a.durationDays))}return r}function Hr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Pc(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,P.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&Tc(String(i),e,t)})}function jr(e){for(let t of ty(e))ry(t,e)}function ty(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,ey(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function ey(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ry(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 Vr(e,t){Pc(t,e.adapter),jr(e.adapter),e.now&&($t(e.adapter,e.now,e.defaultBaseCalendarId??null),Ot(e.adapter,e.now)),zt(e.adapter),e.now&&St(e.adapter,e.sector.statusCriteria)}function Ec(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 Rc(e,t){let r=await q(t.adapter,new Set(t.adapter.getAllIds())),i=Ec(t),n=Br(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Ec(t)!==i&&Vr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await V(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function iy(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function bc(e,t){iy(e.criterion);let r=new Set(t.adapter.getAllIds()),i=await q(t.adapter,r);return Vr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await V(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Lc(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 V(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function wc(e,t,r){return e.kind==="persistence-acknowledge"?Ic(e,r):e.kind==="baseline-apply"?Rc(e,r):e.kind==="ponderator-criterion-set"?bc(e,r):e.kind==="status-criteria-set"?Lc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?jo(e,t,r):e.kind==="links-batch"?Vo(e,t,r):e.kind==="activity-create"?nc(e,t,r):e.kind==="activity-paste"?ac(e,t,r):e.kind==="activity-delete"?fc(e,t,r):e.kind==="activity-move"?hc(e,t,r):e.kind==="activity-indent"?yc(e,t,r):e.kind==="activity-outdent"?mc(e,t,r):e.kind==="activity-set-progress"?gc(e,t,r):e.kind==="dates-batch"?vc(e,t,r):e.kind==="bulk-edit"?Ac(e,t,r):e.kind==="selection-toggle"?Yn(e,mn(r)):e.kind==="selection-replace"?Kn(e,mn(r)):e.kind==="visibility-set"?$n(e,mn(r)):e.kind==="filter-set"?Xn(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?ra(e,{adapter:r.adapter}):e.kind==="sir-sync"?sc(e,r):e.kind==="activity-lookahead-sync"?oc(e,r):e.kind==="inline-edit"&&(e.column===P.CUSTOM_PREDECESSORS||e.column===P.CUSTOM_SUCESSORS)?Yo(e,t,r):e.kind!=="inline-edit"?Ha(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Ho(e,t,r)}function mn(e){return{adapter:e.adapter}}var ny=new Set(["startDate","endDate","constraintDate"]);function Oc(e,t){return ny.has(e)&&typeof t=="string"?new Date(t):t}function xc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?ay(n,r):null}}}function ay(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 sy(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 oy={}.constructor.toString();function cy(e){var t=e.constructor.toString();return t!==oy}function ly(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 sy(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Dt(e[t]);break;default:if(cy(e))r=Object.create(e);else{if(ly(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 Nc(e){return typeof e<"u"}var Yr;function gn(){return Yr||(Yr=new Date().valueOf()),Yr++,Yr}function ht(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var uy=(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)},fy=(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)},Fc={date_to_str:uy,str_to_date:fy},py=(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}}),hy=(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])},Mc={date_to_str:py,str_to_date:hy};function Wc(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=Fc;return a()&&(l=Mc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=Fc;return a()&&(l=Mc),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),p=1+Math.floor(f/7);return p},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 vn(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function An(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 Cn(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 yy(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 Uc=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 vn)return t;var r;if(t.date?r=new vn(t.date,t.unit,t.task,null,t.calendar):r=new vn(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 An)return r;var i;if(ie(r)?i=new An(r):i=new An(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=yy,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 Cn)return a;var s;if(ie(a)?s=new Cn(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new Cn(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 Bc(){}Bc.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 p in d.dates){let m=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&m)),Array.isArray(f)){let k=Array.isArray(m)?m:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,k))}}}};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 In=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}},Sn=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={}}},kn=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 my(){return typeof Map<"u"?new In:new Sn}var Dn=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 Tn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=my(),this._largeUnitsCache=new kn(this),this._dateDurationCache=new Dn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Tn.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 p=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(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&&p?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var m=this._getUnitOrder(r),k=this.units[m-1];k&&!this._isWorkTime(a,k)&&(c=this._getClosestWorkTimeFuture(a,k))}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=ht(this._getMinutesPerDay,this):o=ht(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),p=d+f+u;return p},_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),p=d+f+u;return Math.round(p)},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 Tn))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(ht(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(ht(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 p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_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 p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_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 p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,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 p=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&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var k=!1,C=null,I=null,T=c.length-1;T>=0;T--)if(c[T].start<m-1&&c[T].end>=m-1){k=!0,C=c[T],I=c[T-1];break}if(k)if(m===C.end&&p>=C.durationMinutes)n+=C.durationMinutes,i=this.$gantt.date.add(i,-C.durationMinutes,"minute");else if(!a&&p<=m/60-C.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=m/60-C.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=m/60-C.startMinute,I?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,I.end)):i=this.$gantt.date.day_start(i));else{var _=this._getMinutesPerHour(i);_<=p?(n+=_,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,p),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var v=this._getClosestWorkTimePast(i,"hour");if(v.valueOf()===i.valueOf()){var v=this.$gantt.date.add(i,-1,"day"),h=this._getWorkHours(v);if(h.length){var g=h[h.length-1];v.setUTCSeconds(g.durationSeconds)}}i=v}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var A=t-n;s=this._subtractMinutesUntilHourStart(i,A),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 p=!1,m=null,k=0;k<o.length;k++)if(o[k].start<=f&&o[k].end>f){p=!0,m=o[k];break}if(p)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 C=this._getMinutesPerHour(i);C<=u?(n+=C,l?i=this.$gantt.date.add(i,C,"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 I=t-n;a=this._addMinutesUntilHourEnd(i,I),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 gy(){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 vy=gy();function Hc(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))}Hc.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 Bc,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 Tn(this.$gantt,Uc(this.$gantt));t.id=String(gn());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=vy.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||gn(),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 _n(e,t){this.argumentsHelper=t,this.$gantt=e}_n.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 _n},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 jc(e){this.$gantt=e.$gantt,this.argumentsHelper=Uc(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new _n(this.$gantt,this.argumentsHelper)}jc.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 Ay=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:ht(e.mergeCalendars,e),createCalendar:ht(e.createCalendar,e),addCalendar:ht(e.addCalendar,e),getCalendar:ht(e.getCalendar,e),getCalendars:ht(e.getCalendars,e),getResourceCalendar:ht(e.getResourceCalendar,e),getTaskCalendar:ht(e.getTaskCalendar,e),deleteCalendar:ht(e.deleteCalendar,e)}},Cy={create:Ay};function Vc(e){var t=new Hc(e),r=new jc(t),i=Cy.create(t,r);_e(e,i)}var Yc={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 Kc(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||Yc,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:Nc,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=Wc(r),r.date.init(),Vc(r),r}function Iy(e={}){let t=Kc(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 $c={createCalendar:Iy};var dw=3600*1e3;function Jc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Sy}=$c,Ve="__replay_default__";function ky(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 Gc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},zc="__main_global__",Dy={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function qc(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 Ty(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:ky(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Xc(e){let t=Sy({config:{work_time:!0}});t.addCalendar({id:Ve,worktime:Gc}),t.addCalendar({id:zc,worktime:Dy});let r=new Set(e.filter(d=>!qc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>qc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Ty(d.worktime):Gc});let n=xc(t),a=n.getCalendar(Ve),s=n.getCalendar(zc);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 p=a;return o.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function Zc(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 _y(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 _y(e,t){let r=[],i=new yt;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 Kr=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:Qc(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:Qc(r)}))}};function Qc(e){return{...e}}var $r=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=tl(t);return this.reader.getCalendar(r??Ve)}getClosestWorkTime(t){let r=`${En(t.task)}|${t.dir}|${t.date.getTime()}`;return Pn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:st.HOUR}))}calculateEndDate(t){let r=`${En(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Pn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${En(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Pn(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 Pn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var Py="__default__";function tl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function En(e){return tl(e)??Py}var Gr=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&&!L(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||L(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(L(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(L(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 zr=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 Kr;_viewState=new zr;_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 $r(Xc(t.calendars)),this._flags=Ry(t),this._hierarchy=new Gr(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=Qn(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))??el}getIncomingLinkIds(t){return this._incoming.get(String(t))??el}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(),Rn(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,Oc(r,i)),r===b.PARENT&&this._hierarchy.markDirty(),Rn(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),Rn(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){il(this._outgoing,String(t.source),t.id),il(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),rl(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),rl(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(!Ey(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))}},el=[];function Ey(e){return e===bi.LAG||e===bi.TYPE}function Rn(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function rl(e,t){return e.filter(r=>String(r)!==String(t))}function il(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Ry(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 nl(e,t){let r=e.getActivity(t);return r?Q(r):null}function al(e){return e.getAllActivities().map(Q)}function sl(e){return e.getAllIds().map(String)}function ol(e,t){e.forEachActivity((r,i)=>t(i))}function cl(e,t){let r=t==="0"?bn(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(Q(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function bn(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{L(n.parentId)&&i.push(a)}),i}return ut(r,e)}function ll(e){return e.checkedIds().map(String)}function dl(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=L(i.parentId)}),r}return e.getChildren(t).length>0}function ul(e,t){let r=e.getLink(t);return r?kt(r):null}function fl(e){return e.getAllLinks().map(t=>kt(t))}function qr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function by(e){return e.reduce((t,r)=>qr(r)<qr(t)?r:t)}function Ly(e){return e.reduce((t,r)=>qr(r)>qr(t)?r:t)}function wy(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function pl(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=wy(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:by(i),endHour:Ly(n)}}function hl(e,t){return{calendars:e.calendarReader,hierarchy:Zc(e),activityReader:Jc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function yl(e){return He(e)}function vl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>({...i,after:null}));return Q({...e,activities:t,links:r})}function Ln(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function Al(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 Cl(e){return e.kind!=="inline-edit"||!Be.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function ml(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 Il(e,t){if(!ml(e)||!ml(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Sl(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 Ln(o)}function kl(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 wn(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 On(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:gl(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:gl(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"?Oy(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function gl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:Q(i.after),after:Q(i.before)}:{before:Q(i.before),after:Q(i.after)}]))}function Oy(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 xn(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Dl(e,t){_l(e,t,"before")}function Tl(e,t){_l(e,t,"after")}function _l(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))rt(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))Qs(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 xy=100,Ny=600,Jr=class{constructor(t=xy){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<=Ny&&n!==void 0&&Il(n,t)?this.undoStack[this.undoStack.length-1]=Sl(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 Fy=["parentId","correlativeId"];function El(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(Pl(c.parentId?.before));continue}let s=n.fields;!s||!Fy.some(c=>c in s)||(i(a),"parentId"in s&&r.add(Pl(s.parentId?.before)))}return r}function Pl(e){return e==null?"0":String(e)}function My(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Wy(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Rl(e){return{id:String(e.id),worktime:Wy(e.worktime)}}function Xr(e,t,r,i=[]){let n=t.map(My),a=[...r.map(Rl),...i.map(Rl)];return{activities:[...e],links:n,calendars:a}}var bl=["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","responsableIds","tagIds"],Ll=new Set(["startDate","endDate","constraintDate","dateOrigin"]),wl=new Set(["newActivityIds","responsableIds","tagIds"]);function Ol(e){let t=bl.map(r=>[r,Uy(r,e[r])]);return Object.fromEntries(t)}function Uy(e,t){return Ll.has(e)?t instanceof Date?new Date(t):null:wl.has(e)?Array.isArray(t)?[...t]:[]:t}function Nn(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of bl)if(!By(r,e[r],t[r]))return!0;return!1}function By(e,t,r){return Ll.has(e)?Hy(t,r):wl.has(e)?jy(t,r):(t??null)===(r??null)}function Hy(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function jy(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 Zr=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),{persistable:Ol(r),deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}})}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}hasUnsavedChanges(t,r){return this.initialized?this.deletedActivities(t).length>0||this.deletedLinks(r).length>0||t.some(n=>{if(n.proplannerId==null)return!0;let a=this.activitiesAtLastSave.get(String(n.id));return!a||Nn(n,a.persistable)})?!0:r.some(n=>{if(n.proplannerId==null)return!0;let a=this.linksAtLastSave.get(String(n.id));return!a||n.lag!==a.lag||n.type!==a.type}):!1}deletedActivities(t){if(!this.initialized)return[];let r=new Set(t.map(n=>String(n.id))),i=[];for(let[n,a]of this.activitiesAtLastSave)r.has(n)||i.push({...a.deletedSnapshot});return i}deletedLinks(t){if(!this.initialized)return[];let r=new Set(t.map(i=>String(i.id)));return Array.from(this.linksAtLastSave.entries(),([i,n])=>r.has(i)?null:{...n}).filter(i=>i!==null)}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?Nn(r,i.persistable):!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 xl=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Fn=[!1,!0,!0,!0,!0,!0,!1],Nl=new Set(["1","true"]),Mn="DURATION",Fl="asap",Ml={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 Wl(e,t){let r=[],i=e.map(a=>{let s=Xy(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Qy(i);let n=new Set(i.map(a=>a.id));return tm(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function Vy(e){return e===0}function Yy(e,t){if(!e)return null;let r=Ml[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Fl):r}function Ky(e,t){let r=Yy(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?wt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function $y(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function Gy(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 zy(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Wn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)zy(r)&&t.push(String(r.id));return t}function qy(e){return e==="0"?null:String(e)}function Jy(e,t){return Array.isArray(e)?e.map(r=>Ur(r,t)).filter(r=>r!==null):[]}function Xy(e,t){let r=$y(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=Ky(e,t.reporter),o=e.type==="milestone",c=wt(e.start_date),l=o?c:wt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:qy(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:Vy(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:wt(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:Zy(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Gy(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Wn(e.pendingRequests),responsableIds:Wn(e.responsables),tagIds:Wn(e.tags),baselinePoints:Jy(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 Zy(e){return e.has_childs?null:e.custom_id}function Qy(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function tm(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 jl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>im(c,i)),o=(r??[]).map(c=>nm(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:rm(s)}}function rm(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Vl(e,t){let r=dm(e.working_days),{days:i,hours:n}=lm(e,r),a=am(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 im(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return Vl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function nm(e,t){return Vl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function am(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=sm(i.from_date,i.to_date,t);if(n.length===0)continue;let a=om(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function sm(e,t,r){let i=Ul(e),n=Ul(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 Ul(e){if(typeof e!="string")return null;let t=xl.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 om(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=cm(t);if(r.length>0)return r}}var Bl=/^\d{1,2}:\d{2}$/;function cm(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();!Qr(o)&&!Qr(c)&&Bl.test(o)&&Bl.test(c)&&t.push(`${o}-${c}`);continue}let s=Kl(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Yl),t}function Hl(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 Yl(e,t){return Hl(e)-Hl(t)}function lm(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Kl(l,d);for(let f=0;f<7;f+=1){let p=u[f],m=r[f];p&&m&&m.push(p)}},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(Yl);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 Kl(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];Qr(c)||Qr(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 dm(e){if(typeof e!="string")return[...Fn];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Fn]:t.map(r=>Nl.has(r))}var um=new Set(["false","null"]);function Qr(e){return!e||um.has(e)}function fm(e){return e==="0"||e==="1"||e==="2"||e==="3"}function pm(e){if(typeof e!="string")return null;let t=ys(e);return t||(fm(e)?e:null)}function zl(e,t){let r=[];for(let i of e)try{r.push(hm(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return ym(r)}function hm(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=pm(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:mt(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function ym(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||Gl(r)>Gl(n))&&t.set(i,r)}return[...t.values()]}function Gl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function mm(e){if(typeof e!="string")return Mn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Mn}}function gm(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function vm(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ql(e){let t=gm(e),r=vm(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:mm(e.activity_creter),statusCriteria:mi}}function ti(e,t=ue){let r=ql(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=jl(e.calendars,e.sector.calendars,e.baseCalendars,Am(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=Wl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=zl(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Am(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 Jl(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 Xl(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 Zl(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 Ql(e){return!!e&&typeof e=="string"&&e.trim().length>0}function ei(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ri(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function td(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function ed(e,t){return!t&&Ql(e)}function rd(e,t){return t&&Ql(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 Cm(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 At(e,t){let r=Ye(e),i=Ye(t),n=r+i;return Cm(n,e)}function ii(e,t){let r=Ye(e),i=Ye(t);return r<i?-1:r>i?1:0}function ni(e,t){return ii(e,t)<=0?e:t}function ai(e,t){return ii(e,t)>=0?e:t}function id(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ni(t,r))}function nd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ai(t,r))}function ad(e){return{prefix:e,baseSuffix:null}}function sd(e,t){let r=ri(e);return{prefix:ei(e),baseSuffix:At(r,t)}}function od(e){return{prefix:e,baseSuffix:null}}function cd(e,t){return ed(e,t)?"parentConversion":rd(e,t)?"pasteReference":"noContext"}function Im(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var si=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?Im(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=id(i),r.max=nd(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 ei(t)}extractSuffix(t){return ri(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=ni(r,i.min),i.max=ai(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=ni(i,n.min),n.max=ai(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:At(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}${At(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(;ii(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=At(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=At(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=At(a,n)}let s=At(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,At(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=td(r),a=cd(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=At(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 ad(this.defaultPrefix);case"pasteReference":return sd(r,this.suffixIncrement);default:return od(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=At(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 Sm=1,km=-1;function Dm(e,t){return!e&&!t?null:e&&t?0:e?Sm:km}function ld(e){return e==null}function dd(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Tm(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 _m(e,t){let r=Nt(e.field);return r===null?null:(i,n)=>{let a=r.extract(i,t),s=r.extract(n,t),o=Dm(ld(a),ld(s));if(o!==null)return o;let c=r.valueKind==="enum"?dd(a,r.order)-dd(s,r.order):Tm(a,s,t.locale);return e.direction==="desc"?-c:c}}function ud(e,t){let r=e.rules.map(i=>_m(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 fd(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),Pm(e,r)}function Pm(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 oi(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?ft(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 pd(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(dt(t),r.updateDurationForPrimaveraEndDate&&Rm(t),bm(t),oi(t),n){a&&(Ot(t,a),St(t,r.statusCriteria));return}let s=await i.schedule({});Le(t,s),Lm(t),Em(t),await pe(t,void 0,!1),a&&(Ot(t,a),St(t,r.statusCriteria))}function Em(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 Rm(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function bm(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=bt(t.constraintDate,n,r))})}function Lm(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=bt(t.constraintDate,i,r))})}var _t={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function hd(e){let t=e.clock??null,r=t?Oe(t()):null,i=e.reporter??ue,n=ti({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=Xr(n.activities,n.links,n.calendars,o),l=I=>ud(I,ce(a.hoursPerDay)),d=new Pe(c,l);d.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let u=new fr(d,i);fd(d);let f=Jl({knownIds:n.activities.map(I=>I.id)}),p=Xl({knownIds:n.links.map(I=>I.id)}),m=Zl({knownIds:n.activities.map(I=>I.uniqueCorrelativeId)}),k=new si({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(k.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let I=o.find(T=>T.baseDefault)?.id??null;Br(d,e.baselinePoints,r,i,I)}let C=pd({state:d,sector:a,scheduler:u,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:d,scheduler:u,activityIdGen:f,linkIdGen:p,uidGen:m,customIdTracker:k,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:C}}var ci=class{_status=_t.READY;coreRuntime;_undo=new Jr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=hd(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 Q(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),nl(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),al(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),cl(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ul(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),fl(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?Q(i[r]):null}getAllIds(){return this.assertReady(),sl(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),ol(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),bn(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),ll(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(),dl(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?Q(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>Q(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>Q(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),pl(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(Q)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(this.coreRuntime.state.getAllActivities()).map(Q)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(this.getAllLinksView()).map(Q)}_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=hl(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=kl(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a;try{a=await wc(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"&&xn(a.changes)){let s=Al(this.coreRuntime.state,a.changes);this._undo.record(Ln(vl(a.changes),a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),Cl(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?(Mo(t)&&xn(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),wm(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||!Fo(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=El(t,a=>r.getParentId(a));if(i.size===0)return null;let n=[...i].map(a=>({parentId:a,childIds:ut(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(Xr(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 en(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 V(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 V(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(jr(t),oi(t),zt(t),this.coreRuntime.clock){let r=Oe(this.coreRuntime.clock());Ot(t,r);let i=!1;t.forEachActivity(n=>{i||=nt(n)!==null}),i&&$t(t,r,this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null),St(t,this.coreRuntime.sector.statusCriteria)}}undo(t={}){let r=this._enqueue(async()=>{this.assertReady();let i=this._undo.takeUndo();if(!i)return null;Dl(this.coreRuntime.state,i),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),wn(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=On(this.coreRuntime.state,i,"before");return this._reapplyViewState(n)??n});return r.then(i=>{i&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",n)})},()=>{}),r}redo(t={}){let r=this._enqueue(async()=>{this.assertReady();let i=this._undo.takeRedo();if(!i)return null;Tl(this.coreRuntime.state,i),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),wn(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(i),this._undo.resetCoalesce();let n=On(this.coreRuntime.state,i,"after");return this._reapplyViewState(n)??n});return r.then(i=>{i&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",n)})},()=>{}),r}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 Zr;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 wm(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}function yd(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 md=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var gd={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 vd=8;var $={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"},Om={[$.PERSISTENCE_ACKNOWLEDGE]:!0,[$.BASELINE_APPLY]:!0,[$.PONDERATOR_CRITERION_SET]:!0,[$.STATUS_CRITERIA_SET]:!0,[$.INLINE_EDIT]:!0,[$.DATES_BATCH]:!0,[$.BULK_EDIT]:!0,[$.LINK_CREATE]:!0,[$.LINK_UPDATE]:!0,[$.LINK_DELETE]:!0,[$.LINKS_BATCH]:!0,[$.ACTIVITY_CREATE]:!0,[$.ACTIVITY_DELETE]:!0,[$.ACTIVITY_MOVE]:!0,[$.ACTIVITY_INDENT]:!0,[$.ACTIVITY_OUTDENT]:!0,[$.ACTIVITY_SET_PROGRESS]:!0,[$.ACTIVITY_PASTE]:!0,[$.SELECTION_TOGGLE]:!0,[$.SELECTION_REPLACE]:!0,[$.VISIBILITY_SET]:!0,[$.FILTER_SET]:!0,[$.SORT_SET]:!0,[$.SIR_SYNC]:!0,[$.ACTIVITY_LOOKAHEAD_SYNC]:!0},Ad=Object.keys(Om);var Cd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Pd(xm);})();
1
+ "use strict";var ScheduleCore=(()=>{var ui=Object.defineProperty;var Sd=Object.getOwnPropertyDescriptor;var kd=Object.getOwnPropertyNames;var Dd=Object.prototype.hasOwnProperty;var Td=(e,t)=>{for(var r in t)ui(e,r,{get:t[r],enumerable:!0})},_d=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of kd(t))!Dd.call(e,n)&&n!==r&&ui(e,n,{get:()=>t[n],enumerable:!(i=Sd(t,n))||i.enumerable});return e};var Pd=e=>_d(ui({},"__esModule",{value:!0}),e);var xm={};Td(xm,{ACTIVITY_TYPE:()=>tr,CALENDAR_UNIT:()=>st,COLUMN:()=>P,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>gd,CREATION_KIND:()=>Cd,DEFAULT_HOURS_PER_DAY:()=>vd,DISPATCH_ACTION_KIND:()=>$,DISPATCH_ACTION_KINDS:()=>Ad,DISPATCH_TRACK_EVENT:()=>vt,LINK_CODE_TO_TYPE:()=>Xt,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>ps,NEW_ACTIVITY_DEFAULTS:()=>Nr,REJECTION_REASON:()=>E,ROOT_PARENT_ID:()=>F,ScheduleCore:()=>ci,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>yd,computeExpectedProgress:()=>xi,expectedProgressFromBaseline:()=>Ie,getActiveBaseline:()=>nt,getUnsavedActivities:()=>md,isRootParent:()=>L,normalizeParentKey:()=>Pt,parseFromBackend:()=>ti,willRunCriticalPath:()=>yl,yieldToBrowser:()=>Z});var yt=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 Hn(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=Ed(c,n).filter(s),f=u.filter(m=>!a(m)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let m of f)r?d.add(m):d.delete(m);return p||Rd({id:c,isChecked:r,autoCheckParents:o,hierarchy:n,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:bd(l,d),parentBlocked:p}}function Ed(e,t){let r=[],i=new yt;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 Rd(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(k=>!a(k)),m=f.length>0&&f.every(k=>o.has(k))&&!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 bd(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 jn=(e,t)=>{let r=e.getActivity(t);return r!=null&&se(r)},Vn=(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 Yn(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=>jn(r,o),s=Hn({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:Vn(e,r,s.changed)}}function Kn(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!jn(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:Vn(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 $n(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 Ld=["Waiting","Done","Doing","Overdue","Advancement"],wd=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function fi(e,t){return e===null||t<=0?null:e/t}function Od(e,t){let r=t.getTime()-e.getTime();return Math.floor(r/864e5)+1}var xd={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)=>fi(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>Od(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)=>fi(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>fi(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:Ld,extract:e=>e.status},constraintType:{valueKind:"enum",order:wd,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 Nt(e){return xd[e]??null}function Nd(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function Fd(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 Md(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 Wd(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function Ud(e,t,r){let n=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function Bd(e,t,r){let i=e!==null&&t.has(String(e));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function Gn(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function zn(e,t,r){let i=Nt(t.field);if(i===null)return!1;let n=i.extract(e,r),{operator:a}=t;return i.valueKind==="string"?Fd(n,String(t.value),a):i.valueKind==="number"?Md(n,Number(t.value),a):i.valueKind==="date"?Wd(n,Nd(t.value),a):i.valueKind==="id-array"?Ud(n,Gn(t.value),a):Bd(n,Gn(t.value),a)}function Hd(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(i=>zn(e,i,r)):t.criteria.every(i=>zn(e,i,r))}function jd(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 Vd(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=Hd(c,i,n),d=a===void 0||jd(c,a);l&&d&&(s.add(String(c.id)),o.push(c.id))}for(let c of o)Vd(c,r,s);return s}function ce(e){return{hoursPerDay:e,locale:"en"}}var Yd={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 qn(e){let t=Nt(e.field);return t===null?"unknown_field":Yd[t.valueKind].has(e.operator)?Kd(e,t.valueKind):"unknown_operator"}function Kd(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"?$d(r)?null:"invalid_value":null}function $d(e){return e instanceof Date?!0:typeof e=="string"||typeof e=="number"?!Number.isNaN(new Date(e).getTime()):!1}function Jn(e){return e.criteria.length===0&&e.dateRange===void 0}function Gd(e,t,r){let i=e.getAllActivities();return Jn(t)?new Set(i.map(n=>String(n.id))):ze({activities:i,parentOf:n=>e.getParentId(n),filter:t,context:ce(r)})}function Xn(e,t){let{adapter:r,hoursPerDay:i}=t;for(let c of e.criteria){let l=qn(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(Jn(n)?null:n);let a=Gd(r,n,i),s=oe(r,a);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:s}}}var F="0";function L(e){return e==null||e===0||e==="0"}function Pt(e){return L(e)?"0":String(e)}var pi=Number.MAX_SAFE_INTEGER;function ut(e,t){let r=yi(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 Qn(e){let t=[],r=n=>{t.push(n);let a=ut(String(n.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},i=ut("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function ta(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=ea(i),a=ut(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&&!zd(t,c))return c}return null}function hi(e,t){let r=t.getActivity(e);if(!r)return-1;let i=ea(r);return ut(i,t).findIndex(a=>String(a)===String(e))}function yi(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=Zn(e),i=Zn(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Zn(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}function ea(e){let t=e.parentId;return t===null?"0":t}function zd(e,t){return e.has(t)?!0:e.has(String(t))}function Je(e){let t=[],r=i=>{let n=ut(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let a of n)r(a)};return r("0"),t}function qd(e){return Nt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function ra(e,t){let{adapter:r}=t;for(let a of e.rules){let s=qd(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 ia="text";var na="description";var aa="duration";var sa="progress";var oa="cost";var ca="used_cost";var la="hhWorkTime";var da="start_date";var ua="end_date";var fa="constraint_type";var pa="constraint_date";var ha="calendar_id";var ya="custom_id";var ma="subcontractId";var ga="responsables";var va="tags";var Aa="custom_predecessors";var Ca="custom_sucessors";var Ia="real_work";var Sa="real_cost";var ka="expected_progress";var Da="expected_progress_base";var Ta="start_base";var _a="end_base";var Pa="duration_base";var Ea="cost_base";var Ra="work_base";var ba="calendarDuration";var La="is_critical",wa="earlyStart",Oa="earlyFinish",xa="lateStart",Na="lateFinish",Fa="freeSlack",Ma="totalSlack";var Wa="correlative_id";var Ua="unique_correlative_id";var Ba="ponderator";var X={FUTURE:"future",PAST:"past"},st={HOUR:"hour",DAY:"day"},Ft={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Xe="status";var mi="Baseline";function Ze(e){return e==="Actual"?"Actual":mi}var Jd={TEXT:ia,DESCRIPTION:na,DURATION:aa,PROGRESS:sa,COST:oa,USED_COST:ca,HH_WORK_TIME:la,START_DATE:da,END_DATE:ua,CONSTRAINT_TYPE:fa,CONSTRAINT_DATE:pa,CALENDAR_ID:ha,CUSTOM_ID:ya,SUBCONTRACT_ID:ma,RESPONSABLES:ga,TAGS:va,CUSTOM_PREDECESSORS:Aa,CUSTOM_SUCESSORS:Ca},Xd={REAL_WORK:Ia,REAL_COST:Sa,EXPECTED_PROGRESS:ka,EXPECTED_PROGRESS_BASE:Da,START_BASE:Ta,END_BASE:_a,DURATION_BASE:Pa,COST_BASE:Ea,WORK_BASE:Ra,CALENDAR_DURATION:ba,IS_CRITICAL:La,EARLY_START:wa,EARLY_FINISH:Oa,LATE_START:xa,LATE_FINISH:Na,FREE_SLACK:Fa,TOTAL_SLACK:Ma,CORRELATIVE_ID:Wa,UNIQUE_CORRELATIVE_ID:Ua,PONDERATOR:Ba,STATUS:Xe},P={...Jd,...Xd};function Ha(e,t){throw new Error(t)}function ja(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Zd={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 Ya(e,t,r){if(!t)return{violated:!1};let i=Zd[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Qd=new Set(["mso","snet","snlt"]);function Re(e,t,r){return Qd.has(e)?t:r}function Ka(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var tu={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())),Va=(e,t)=>new Date(e.getTime()+t*864e5),eu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function gi(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=tu[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Qe(i),dir:X.FUTURE,task:e});if(eu(n,i))return i.getTime()!==Qe(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Va(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:Va(a,1),dir:X.PAST,task:e})}function $a(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=gi(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 Ga(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function vi(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"},za={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Ai=typeof window>"u",ru=!Ai&&typeof MessageChannel<"u";function Z(){return ru?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<za.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 Ai||await Z(),e()?{aborted:!1}:{aborted:!0}}function rr(e,t){let{inDegree:r,successors:i}=iu(e,t),n=nu(r),a=au(n,r,i),s=a.length<e.length,o=s?su(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function iu(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 nu(e){let t=new yt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function au(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 su(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 qa(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Ci={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 Ii(e){return e==="project"||e==="task"||e==="milestone"}function Et(e,t){return t||Ii(e)&&Ci[e].alwaysSummary}function Jt(e){return e==="milestone"}function Mt(e){return Ii(e)&&Ci[e].promotesToProjectOnFirstChild}var Si="project",de="task";function be(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Ja(e,t){let r=t.getActivity(e);return r?Et(r.type,t.getChildren(e).length>0):!1}function Xa(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 ts(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 ou(e){let t=new Map;for(let r of e)Za(t,String(r.source),r),Za(t,String(r.target),r);return t}function Za(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function cu(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let s of e)lu(s,n,t,r,i)||a.push(s);return a.length>0?a:e}function lu(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(du(c,a,s,t,r,n))return!0;return!1}function du(e,t,r,i,n,a){if(uu(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=fu(e,t);if(!i.has(String(o)))return!1;let c=n.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&pu(e,r,c))}function uu(e){return e.source===e.target}function fu(e,t){return String(e.source)===t?e.target:e.source}function pu(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 es(e,t){let r=[],i=ou(e),n=0;for(let a of e){let s=Ja(a.source,t),o=Ja(a.target,t);if(hu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Qa(a.source,s,t,i,!0),l=Qa(a.target,o,t,i,!1);n=Iu(r,c,l,a,t,n,i)}return r}function hu(e,t,r,i){return r&&Xa(e.source,e.target,i)||t&&Xa(e.target,e.source,i)}function Qa(e,t,r,i,n){return t?cu(ts(e,r),r,i,n):[e]}function yu(e,t,r){let i=ts(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 yu(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function mu(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function gu(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 vu(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function Au(e,t,r,i,n){if(vu(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Cu(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?-mu(i,a,t):0,summarySourceId:e.type===W.START_TO_START&&n?e.source:void 0}}function Iu(e,t,r,i,n,a,s){let o=Cu(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:m}=o,k=a;for(let C of t){let I=f?gu(C,c,l,n):0;for(let T of r){if(String(C)===String(T))continue;let _=Au(T,d,c,n,s);e.push(Su(i,C,T,k,I,p,u+_,m,_!==0&&p===0?i.target:void 0)),k+=1}}return k}function Su(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 es(t,r)}};function ku(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 Du(e,t,r){let i=new Set,n=new Map,a=new yt;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 rs(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let i=ku(t),n=Du(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 is(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 Tu(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 _u(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 ns(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s,isFS:o,isFF:c}=is(e,t,r),l=Tu(r,e,i)??n,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return _u(e,t,r,i,o||c);let p=o?t:e,m=i.getClosestWorkTime({date:e.endDate,dir:"future",task:p});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 k=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:k,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}function as(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:s}=is(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 ss(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===K.ASAP||a===K.ALAP)continue;let s=$a(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=vi(e.startDate,i):Ga(n,i)?a=n:a=vi(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function os(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case K.MSO:case K.MFO:return new Date(i);case K.SNET:case K.FNET:return i>t?new Date(i):t;case K.SNLT:case K.FNLT:return i<t?new Date(i):t;default:return t}}function Pu(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function cs(e,t,r){return ki(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ki(e,t,r){return t.dragWithMultiple&&Pu(e,r)}async function ds(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 p=r.getActivity(u);return p?{startDate:p.startDate,endDate:p.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 p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Eu(p,r))continue;let m=s.get(String(u))??[],k=null,C=null,I=!1;for(let g of m){let v=r.getActivity(g.source);if(!v)continue;let D=o(g.source),R=D.startDate.getTime()!==v.startDate.getTime()||D.endDate.getTime()!==v.endDate.getTime(),x={...v,startDate:D.startDate,endDate:D.endDate},O=cs(x,c,l),j={...x,startDate:O.startDate,endDate:O.endDate},Y=ki(g.source,c,l)?{...g,lag:0}:g,it=ns(j,p,Y,r);(!k||it.successorStart>k)&&(k=it.successorStart,C=String(g.id),I=g._summaryTargetId!==void 0&&!R)}k!==null&&I&&k<p.startDate&&(k=new Date(p.startDate));let _=a.get(u),A=_?{..._}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},h=A.earliestStart||A.latestStart||A.earliestEnd||A.latestEnd;if(!(!k&&!h)){if(k){let g=k;p.type===tr.MILESTONE&&(g=os(p,k)),A.drivingLinkId=C,A.startDate=g,A.endDate=r.calculateEndDate({startDate:g,durationHours:p.durationHours,task:p}),A.earliestSchedulingStart=g,A.earliestSchedulingEnd=A.endDate}else p.constraintType===K.MSO?A.earliestStart&&(A.startDate=A.earliestStart,A.endDate=A.earliestEnd??r.calculateEndDate({startDate:A.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&A.latestStart&&(A.startDate=A.latestStart,A.endDate=A.latestEnd??r.calculateEndDate({startDate:A.latestStart,durationHours:p.durationHours,task:p}));sr(p,A,r),a.set(u,A)}}return a}function Eu(e,t){return Et(e.type,t.getChildren(e.id).length>0)}async function us(e,t,r,i,n,a){let s=new Map(r),o=i.getAllActivities(),c=o.length,l=[];for(let C of o)C.constraintType===K.ALAP&&l.push(C.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let C of t){let I=String(C.source);d.has(I)||d.set(I,[]),d.get(I).push(C);let T=String(C.target);u.has(T)||u.set(T,[]),u.get(T).push(C)}let f=C=>{let I=s.get(C);if(I)return{startDate:I.startDate,endDate:I.endDate};let T=i.getActivity(C);return T?{startDate:T.startDate,endDate:T.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||L(C.parentId)?i.getProjectEnd():f(C.parentId).endDate,m=(C,I)=>{let T=C,_=0;for(;T&&!L(T)&&_++<c+1;){if(String(T)===String(I))return!0;let A=i.getActivity(T);if(!A||!A.parentId)break;T=A.parentId}return!1},k=performance.now();for(let C of e){let I=await er(k,a);if(I.aborted)return s;k=I.newSliceStart;let T=i.getActivity(C);if(!T||T.constraintType!==K.ALAP||!T.autoScheduling||T.progress===100||Et(T.type,i.getChildren(C).length>0))continue;let _=p(T);if(!_)continue;let A=_,h=null,g=!1,v=d.get(String(C))??[];for(let Ct of v){if((Ct.lag??0)<0)continue;let ae=i.getActivity(Ct.target);if(!ae||ae.autoScheduling===!1)continue;let Bn=f(Ct.target),Id={...ae,startDate:Bn.startDate,endDate:Bn.endDate},$e=as(Id,T,Ct,i);$e<A&&(A=$e),(h===null||$e<h)&&(h=$e,g=T.parentId&&!L(T.parentId)?m(Ct.target,T.parentId):!1)}if(h!==null)if(g)A=h;else{let Ct=f(C).endDate,ae=Ct.getTime()>_.getTime()?Ct:_;A=h<ae?h:ae}else A>_&&(A=_);let R=(u.get(String(C))??[]).some(Ct=>Ct.type===W.FINISH_TO_START||Ct.type===W.FINISH_TO_FINISH),x=new Date(Date.UTC(A.getUTCFullYear(),A.getUTCMonth(),A.getUTCDate())),O=()=>i.getClosestWorkTime({date:x,dir:"past",task:T}),j=i.getClosestWorkTime({date:A,dir:"future",task:T}).getTime()===A.getTime(),Y;T.durationHours===0&&h===null?Y=R&&j?O():i.getClosestWorkTime({date:A,dir:"past",task:T}):T.durationHours===0?R?Y=O():Y=i.getClosestWorkTime({date:A,dir:"future",task:T}):Y=i.getClosestWorkTime({date:A,dir:"future",task:T});let it=i.calculateEndDate({startDate:Y,durationHours:-T.durationHours,task:T}),Ee=s.get(C),lt=Ee?{...Ee}:{activityId:C,startDate:it,endDate:Y,drivingLinkId:null,kind:"alap",conflict:!1};lt.startDate=it,lt.endDate=Y,lt.drivingLinkId=null,lt.kind="alap";let li=lt.earliestSchedulingStart??null;lt.earliestSchedulingStart=null,lt.earliestSchedulingEnd=null;let di=li!==null&&li.getTime()>it.getTime()?li:it;lt.latestSchedulingStart=di,lt.latestSchedulingEnd=di===it?Y:i.calculateEndDate({startDate:di,durationHours:T.durationHours,task:T}),sr(T,lt,i),s.set(C,lt)}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 fs(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 Ru(n,i,r)}function Ru(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new yt;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 Wt(e,t){switch(e.kind){case"create":return bu(e,t);case"update":return Lu(e,t);case"delete":return wu(e,t)}}function bu(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(fs(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Ou)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function Lu(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 wu(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 Ou(){return or===null&&(or=Date.now()),or+=1,String(or)}var ps={[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},hs="fs";function ys(e){if(e in Xt)return Xt[e]}var ms=";",gs=/^(\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(ms)){if(n.length===0)continue;let a=xu(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function xu(e){let t=e.toLowerCase(),r=gs.exec(t);if(!r)return null;let[,i,n,a,s]=r,o=n?Xt[n]:Xt[hs],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 mt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var vs={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:st.HOUR}):t.isWorkTime(e,st.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function Di(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 Ti=vs;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=ja(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Wu(this.adapter);let a=Ut("schedule.total"),s=Ut("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Rt(s);let l=c;if((await le(i)).aborted)return{...n,cancelled:!0};let d=Ut("schedule.scoping"),u=this.adapter.getAllIds(),f=Uu(t,l,this.adapter),p=f.links,m=f.idSet;Rt(d);let k=Ut("schedule.topologicalSort"),C=Hu(this.topoCache,u,l,m);if(Rt(k),C.hasCycles)return Rt(a),{...n,cycles:[C.cycleNodes]};if((await le(i)).aborted)return{...n,cancelled:!0};let I=Ut("schedule.processConstraints"),T=new Map;if(ss(C.ordered,this.adapter,T),Rt(I),(await le(i)).aborted)return{...n,cancelled:!0};let _=Ut("schedule.asapPass"),A=await ds(C.ordered,p,this.adapter,t,i,T);if(Rt(_),(await le(i)).aborted)return{...n,cancelled:!0};let h=Ut("schedule.alapPass"),g=await us(C.reversed,p,A,this.adapter,t,i);if(Rt(h),(await le(i)).aborted)return{...n,cancelled:!0};let v=Ut("schedule.diff"),D=[];for(let[R,x]of g){let O=this.adapter.getActivity(R);if(!O)continue;let j=O.startDate.getTime()!==x.startDate.getTime(),Y=O.endDate.getTime()!==x.endDate.getTime();(j||Y)&&D.push(R)}return Rt(v),Rt(a),{plans:g,updatedIds:D,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},Fu=!1;function Mu(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Fu}function Ut(e){return{name:e,startedAt:performance.now()}}function Wu(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Rt(e){if(!Mu())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Uu(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=rs(i,t);return Bu(n,t,r)}function Bu(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===K.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 Hu(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=qa(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function As(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}=Di(c,n,o.type),f=Ti.computeLagBetweenTasks(d,u,a);f!==o.lag&&Wt({kind:"update",linkId:o.id,lag:f},{port:t})}}function Cs(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 ft(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function pe(e,t,r=!0,i={}){let n=t?Vu(e,t):Gu(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await ju(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function hr(e,t){Is(e,t,"skip")}async function ju(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 Z()}function Vu(e,t){let r=new Set;for(let a of t)Yu(a,e,r);if(r.size===0)return[];let i=Array.from(r),n=Ss(i,e);return ks(i,n)}function Yu(e,t,r){let i=t.getParentId(e);for(;i&&!L(i);){if(r.has(i))return;r.add(i),i=t.getParentId(i)}}function Ku(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+=$u(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=Ku(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 $u(e,t){return t?Number(e.realWorkHours)||0:ft(e.workHours,e.progress)}function Gu(e){let t=zu(e),r=Ss(t,e);return ks(t,r)}function zu(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ss(e,t){let r=new Map;for(let i of e)r.set(i,qu(i,t));return r}function qu(e,t){let r=0,i=e;for(;i&&!L(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ks(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Ds={updateActivityDuration:Cs,updateTaskTiming:Xu("updateTaskTiming"),adjustLinkLagOnTaskMove:As,recordLastStartDate:Ju};function Ju(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Bt(e,t,r,i){for(let n of t){let a=n in Ds?Ds[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 Xu(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 N(e){return{ok:!1,reason:e}}function U(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function B(){return{allowed:!0}}function G(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 Ts={targetField:"name",canEdit(){return B()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return U()},transform(e,t){return M({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var _s={targetField:"description",canEdit(){return B()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(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??K.ASAP}var yr=100;function he(e){return e.progress>=yr}function et(e,t){return Et(e.type,t.hasChildren(e.id))}function Ps(e){return e.progress>0}function Es(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(p=>p.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(p=>p.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 Zu(e,t){let r=Zt(t);for(;!e.isWorkTime(r,st.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Zt(r);return r}function _i(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:st.HOUR})}function Pi(e,t){let r=Zu(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:st.HOUR})}var mr=new Set(["snet","snlt","mso"]),Ei=new Set(["fnet","fnlt","mfo"]),Ht=new Set(["asap","alap"]),gr="snet";function bt(e,t,r){if(!mr.has(r)&&!Ei.has(r))return e;let i=mr.has(r)?_i(t,e):Pi(t,e),n=new Date(e);return n.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),n}var Lt=()=>({constraintType:gr});var jt=e=>({constraintDate:e}),Rs=e=>({constraintDate:e});var bs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ls={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 Ya(e,t,r)}function ge(e,t,r){return Ka(e,t,r)}var Os={targetField:"durationHours",canEdit(e,t){return he(e)?G("completed","cant_edit_completed_activity"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isNaN(i)?N("not_a_number"):w(r.inputUnit==="hours"?i:we(i,r.hoursPerDay))},validate(e,t,r){return ws(r)?tt(Ls.NEGATIVE_DURATION):Qu(t,r)?tt("unchanged"):U()},transform(e,t,r){if(ws(t))return M({},{autoSchedule:!1,postProcessors:[]});let i=tf(e,t,r),n=ef(e,t,r,i.violated);return{...M(n,{autoSchedule:!0,postProcessors:[bs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:ge(i.constraintType,i.constraintDate,xs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ws(e){return Math.sign(e)===-1}function Qu(e,t){return e===t}function tf(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 ef(e,t,r,i=!1){let n={};i&&Object.assign(n,Lt(),jt(e.startDate));let a=be(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let s=xs(e,t,r);return s&&Object.assign(n,ye(s)),n}function xs(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var ve=e=>({realWorkHours:e});var rf=0,nf=yr,Ns=0,Fs={targetField:"progress",canEdit(e,t){return Es(e)?G("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return af(r)?tt("out_of_range"):U()},transform(e,t,r){let i=sf(t),n=of(t),a=df(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...ve(a.get(e.id)??0)},o=n?cf(e,t,i,r.hierarchy,a):[],c=n?ff(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=n?hf(e,t):void 0;return M(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function af(e){return e<rf||e>nf}function sf(e){return e===Ns}function of(e){return e===yr||e===Ns}function cf(e,t,r,i,n){return i.getDescendantIds(e.id).map(s=>({activityId:s,fields:lf(t,r,n.get(s)??0)}))}function lf(e,t,r){return{progress:e,autoScheduling:t,...ve(r)}}function df(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):ft(c.workHours,t);i.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?n(e.id):ft(e.workHours,t);return i.set(e.id,a),i}function uf(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 ff(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=[...uf(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of n){let o=pf(s,i,r);i.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function pf(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 hf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Ms={targetField:"cost",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):B()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return U()},transform(e,t,r){let i=yf(e,t,r.hierarchy);return M({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_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.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 Ws={targetField:"usedCost",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):B()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?N("not_a_number"):w(r)},validate(){return U()},transform(e,t,r){let i=mf(e,t,r.hierarchy);return M({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function mf(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 Us={targetField:"workHours",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(){return U()},transform(e,t,r,i){let n=Bs(t,e.progress),a=String(i).trim()===""?[]:gf(e,t,n,r.hierarchy);return M({workHours:t,...ve(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Bs(e,t){return ft(e,t)}function gf(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??Bs(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 Ri(e,t){return e.getTime()<t.getTime()}function Ae(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Ar=e=>({durationHours:e});var Hs={targetField:"startDate",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):Ps(e)?G("has_progress","cant_edit_activity_with_progress"):B()},parseInput(e,t,r){return Ae(e)?w(Zt(e,"UTC")):N("invalid_date")},validate(e,t,r,i){if(vr(t,r))return tt("unchanged");let n=vf(e,r,i);return n||U()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return M({startDate:t,...Lt(),...jt(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let n=_i(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):{},...Lt(),...jt(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Af(e,n,i)}},trackEvent:"activity_start_date_entry"};function vf(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=Zt(i);return t.getTime()<n.getTime()?tt("before_parent_start"):null}function Af(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 Cf=99.999,Vs={targetField:"endDate",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):If(e)?G("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,st.DAY)?w(Pi(n,i)):r.dateFormat.split(" ").length>1?w(i):w(n.getClosestWorkTime({direction:"past",date:i,unit:st.HOUR})):w(i)},validate(e,t,r,i){if(vr(e.endDate,r))return tt("unchanged");if(Sf(r,e))return tt("before_date_origin");if(kf(r,e))return tt("before_start_date");let n=Df(r,e,i);return n||U()},transform(e,t,r){let i=Tf(e,t),n=_f(e,t,r,!!i);return{...M(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function If(e){return e.progress>=Cf}function Sf(e,t){return t.dateOrigin?Ri(e,t.dateOrigin):!1}function kf(e,t){return Ri(e,t.startDate)}function Df(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,st.DAY)?null:tt("not_working_day"):null}function Tf(e,t){if(It(e)===K.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 _f(e,t,r,i=!1){let n={};Jt(e.type)&&!i&&js(e)?Object.assign(n,jt(e.startDate)):(i||js(e))&&Object.assign(n,Lt(),jt(e.startDate));let o=Pf(e,t,r),c=be(e.durationHours,o);return c&&(n.type=c),Object.assign(n,Ar(o)),n.endDate=t,n}function js(e){return Ht.has(It(e))}function Pf(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Ef=new Set(Object.values(K)),Ys={targetField:"constraintType",canEdit(e,t){return he(e)?G("completed","cant_edit_completed_activity"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){let t=String(e).toLowerCase();return Rf(t)?w(t):N("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let i=bf(e,t,r);return M(i,{autoSchedule:!0})}};function Rf(e){return Ef.has(e)}function bf(e,t,r){let i=wf(e,t);return{constraintType:t,...Rs(Lf(e,t,i,r))}}function Lf(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?bt(r,n,t):r}function wf(e,t){return Ht.has(t)?null:mr.has(t)?e.startDate:Ei.has(t)?e.endDate:e.constraintDate}var Ks={targetField:"constraintDate",canEdit(e,t){return he(e)?G("completed","cant_edit_completed_activity"):et(e,t)?G("summary","summary_column_value"):B()},parseInput(e){return Ae(e)?w(e):N("invalid_date")},validate(){return U()},transform(e,t,r){let i=$s(e)?gr:It(e),n=r.calendars.getCalendar(e.calendarId),a=n?bt(t,n,i):t,s=Of(e,a);return M(s,{autoSchedule:!0})}};function Of(e,t){return{constraintDate:t,...$s(e)?Lt():{}}}function $s(e){return Ht.has(It(e))||!e.constraintType}var Gs={targetField:"calendarId",canEdit(){return B()},parseInput(e){let t=String(e).trim();return xf(t)?N("empty_calendar"):w(t)},validate(e,t,r,i){return Nf(e.calendarId,r)?tt("unchanged"):i.calendars.getCalendar(r)?U():tt("unknown_calendar")},transform(e,t,r){return M(Ff(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function xf(e){return e===""}function Nf(e,t){return e===t}function Ff(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,s=a?Mf(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 Mf(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var zs={targetField:"customId",canEdit(e,t){return et(e,t)?G("summary","summary_column_value"):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"):w(t)},validate(){return U()},transform(e,t){return M({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var qs={targetField:"subcontractId",canEdit(){return B()},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)?N("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?N("not_an_integer"):w(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 Js={targetField:"responsableIds",canEdit(){return B()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Cr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(xe).filter(i=>i!==null);return M({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Xs={targetField:"tagIds",canEdit(){return B()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Cr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(xe).filter(i=>i!==null);return M({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Wf=new Map([[P.TEXT,Ts],[P.DESCRIPTION,_s],[P.DURATION,Os],[P.PROGRESS,Fs],[P.COST,Ms],[P.USED_COST,Ws],[P.HH_WORK_TIME,Us],[P.START_DATE,Hs],[P.END_DATE,Vs],[P.CONSTRAINT_TYPE,Ys],[P.CONSTRAINT_DATE,Ks],[P.CALENDAR_ID,Gs],[P.CUSTOM_ID,zs],[P.SUBCONTRACT_ID,qs],[P.RESPONSABLES,Js],[P.TAGS,Xs]]);function Vt(e){return Wf.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"},bi={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 Uf=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Zs=new Set(Uf);function rt(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Qs(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:Bf(e.baselineSnapshot),criticalPath:Hf(e.criticalPath)}}function Tt(e){return e===null?null:new Date(e)}function Bf(e){return e===null?null:{...e,startDate:Tt(e.startDate),endDate:Tt(e.endDate)}}function Hf(e){return e===null?null:{...e,earlyStart:Tt(e.earlyStart),earlyFinish:Tt(e.earlyFinish),lateStart:Tt(e.lateStart),lateFinish:Tt(e.lateFinish)}}function Q(e){return structuredClone(e)}var ro=200;function Yt(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%ro===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 Kt(e,t,r){to(e,t,r.patch);for(let i of r.cascadeMutations??[])to(e,i.activityId,i.fields)}function to(e,t,r){for(let[i,n]of Object.entries(r)){if(!Zs.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);rt(e,t,i,n)}}async function io(e,t,r,i){let n=[],a=0;for(let s of r){a+=1,a%ro===0&&await Z();let o=jf(e,t,s,i);o&&n.push(o)}return n}function jf(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 Vf(r,i.get(r),n);let s=wi(a,n);return Yf(s,i,r,n),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(n)}}function Vf(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function Yf(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 wi(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)||!Li(i[s],n[s]))&&(r[s]={before:eo(i[s]),after:eo(n[s])});return r}function eo(e){return e===null||typeof e!="object"?e:Q(e)}function Li(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)=>Li(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)&&Li(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 Oi(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 Kf=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function wt(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(Kf);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 $f=e=>e.type==="project",Gf=(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:wt(String(s));return Ie(a(e.startDate),a(e.endDate),t,n)};function zf(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(!$f(o)){let d=Gf(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),p=typeof f?.ponderator=="number"?f.ponderator:0;c+=u*p}let l=c/100;return n(s,l),l};for(let s of e)a(s);return i}function Ot(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),zf(r,t,e)}function nt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var qf=e=>e.type==="project",Jf=e=>nt(e),Xf=(e,t,r,i)=>{let n=Jf(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 xi(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(!qf(c)){let u=Xf(c,t,r,i);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),m=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*m}let d=l/100;return a(o,d),d};for(let o of e)s(o);return n}function $t(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)=>rt(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,s)=>{a.parentId===null&&n.push(s)}),xi(n,t,i,r)}var no=e=>Math.round(e*100)/100;function Zf(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Qf(e,t){let r=no(e),i=no(t);return r>99.99?Ft.DONE:i>r?Ft.OVERDUE:e>0&&r>i?Ft.ADVANCEMENT:e===0&&t===0?Ft.WAITING:e>0&&r<i?Ft.DOING:Ft.WAITING}function St(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,s=Qf(a,Zf(i,t));i.status!==s&&(rt(e,n,Xe,s),r.push(n))}),r}function Ni(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:()=>Ni(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}Ni.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var gt=Ni;function tp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Dr(e){return tp(e)&&!isNaN(e.getTime())}function S(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 pt(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 ep=e=>e?e.$level===1:!1,rp=e=>e.type==="project",ip=e=>e.$level!==0,np=e=>e.type==="task",ap=e=>e.type==="task"||e.type==="milestone",ot={byFirstLevel:ep,filterByParentType:rp,avoidSubproject:ip,byTaskType:np,byTaskTypeAndMilestone:ap};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 ao(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=sp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=op({gantt:t,subprojectsWithNoLinks:a}),o=cp({gantt:t,childrenIds:s,linkProperty:n,getArrayOfLinkedActivities:lp,calculations:i});return new Set(o.map(c=>c.id))}catch(a){throw a}}function sp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ot.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function op(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=ot.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>i.add(o));return[...i]}function cp(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 lp(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 so({gantt:e,linkProperty:t,direction:r}){try{let i=dp(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return up(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function dp(e,t){return e.getTaskByTime().filter(ot.avoidSubproject).filter(ot.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function up(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 oo({gantt:e,direction:t,linkProperty:r}){try{let i=fp(e),n=new Set,a=new Set,s=new Set;t==="backward"&&yp(i).forEach(d=>{n.add(d.id)});let o=pp(i,t,r),c=hp(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 fp(e){return e.getTaskByTime().filter(ot.filterByParentType).filter(ot.avoidSubproject)}function pp(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 hp(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function yp(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function co({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),s=mp(r),o=gp(r),c=a[s];if(!Array.isArray(c))return;vp(t,c,o).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function mp(e){return e==="forward"?"$source":"$target"}function gp(e){return e==="forward"?"target":"source"}function vp(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Ne={identifySecondLevelActivities:ao,identifyInitialActivities:so,identifyParentsWithAndWithoutLinks:oo,identifyForbiddenActivities:co};function Tr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Fi({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===H.FS&&t===0?pt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):Fe(r,e,i,n)}function lo({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:S(r,n,e,i),ef:n}}function uo({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=S(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 pt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Mi=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=uo({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=lo({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=Fi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=S(this.activityCalendar,i,t,this.activity);t>0&&(n=Fe(n,"ss",this.activityCalendar,this.activity));let a=S(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=Fi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=S(this.activityCalendar,i,t,this.activity),a=S(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=pt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=S(this.activityCalendar,i,t,this.activity),a=S(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=S(this.activityCalendar,r,t,this.activity),n=S(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=Fe(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},fo=Mi;var Wi=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:S(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=S(this.activityCalendar,r,n,this.activity),s=S(this.activityCalendar,a,i,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=S(this.activityCalendar,o,n,this.activity),s=S(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=S(this.activityCalendar,l,n,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=S(this.activityCalendar,s,i,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=S(this.activityCalendar,c,n,this.activity),o=S(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=S(this.activityCalendar,o,i,this.activity),a=S(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=S(this.activityCalendar,r,i,this.activity),s=S(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=S(this.activityCalendar,c,i,this.activity),s=S(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:S(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=gt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),pt({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),gt.isMoment(r)?r.hours()===s:i.getUTCHours()===s)}},po=Wi;function ho(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:s}=e,o=t[r],c=Ap(t),l=null;if(s==="forward"){let d=Cp(o,i,n,a);l=new fo(d,t,a),l=l.calculate()}else{let d=Ip(o,i,n,a);l=new po({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function Ap(e){return{duration:e.duration,calendarId:e.calendar_id}}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);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 Ip(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 go(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(Sp(t.id,r))return null;let a=kp(t.id,i),s=Dp(a,r);return s.length===0?null:Tp(s,n)}function Sp(e,t){return t.has(e)}function kp(e,t){let r=t.get(e);return r?r.childrens:[]}function Dp(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Tp(e,t){if(t==="forward"){let r=yo(e,"es"),i=mo(e,"ef");return{es:r,ef:i}}else{let r=yo(e,"ls"),i=mo(e,"lf");return{ls:r,lf:i}}}function yo(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function mo(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var Ui={parentWithLinks:ho,parentWithNoLinks:go};var Bi=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=Ui.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=Ui.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)})}},vo=Bi;var Hi=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(ot.byFirstLevel).filter(ot.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}}},Ao=Hi;var ji=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(ot.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 Ao({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:gt(i.start_date).clone(),lf:gt(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=gt(t.start_date).clone(),n=gt(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=S(r,n,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(i=t.constraint_date,n=S(r,i,a,t)),l.includes(o)&&(n=t.constraint_date,i=S(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 vo({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()}},Gt=ji;function _p(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=S(r,n,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=S(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=S(r,n,e.duration,e)}else if(t===y.MFO){let n=new Date(e.constraint_date);i.es=S(r,n,-e.duration,e),i.ef=n}return i}var _r=_p;var Vi=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=pt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[H.FF,H.SF].includes(a)?(l=S(s,o,i,this.referenceActivity),c=S(s,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=S(s,o,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=S(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 pt({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},Co=Vi;var Me=class extends Co{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Gt(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=S(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 Yi=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=Yi;var Ki=(e,t)=>()=>t()===e;var $i=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Pp=16,We=async e=>performance.now()-e>Pp?(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 Gi=class extends Gt{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 p=_r(i,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[y.MSO,y.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),i.progress===0)d=p.es,u=p.ef;else{let m=i.end_date;a===y.MFO&&(m=Math.max(p.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)}},Io=Gi;var zi=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=S(s,o,r,this.activity),u=S(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=gt(r).clone();return S(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=gt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),pt({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),gt.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=S(i,d,a,this.activity),o=this.getLastWorkingHour(o,i,"past"),c=S(i,o,n,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,i)),o=S(i,l,a,this.activity),c=S(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=S(i,r,a,this.activity),o=S(i,s,n,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),s=S(i,c,a,this.activity),o=S(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=S(i,r,n,this.activity),o=S(i,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,i,"future")),c=S(i,l,n,this.activity),o=S(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=S(i,r,n),s=S(i,o,a,this.activity),{ls:o,lf:s}):(o=S(i,r,n,this.activity),s=S(i,o,a,this.activity),{ls:o,lf:s})}},So=zi;var qi=class extends So{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 Gt(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=S(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:S(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))}},ko=qi;function Ep(e,t,r){let i={ls:null,lf:null};return r===y.MSO&&(i.ls=t.constraint_date,i.lf=S(e,i.ls,t.duration,t)),r===y.MFO&&(i.lf=t.constraint_date,i.ls=S(e,i.lf,-t.duration,t)),i}var Do=Ep;var Ji=class extends Gt{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 ko({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=Do(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=S(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=S(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);n=new Date(Math.min(l.getTime(),u.getTime())),a=S(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=S(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=S(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=S(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:n,lf:a}];o.push({ls:S(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}},To=Ji;function _o(){return null}var Po=({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 Xi=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)})}},Eo=Xi;var Zi=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)}},Ro=Zi;var bo=e=>({totalFloat:new Eo(e.totalFloat).getTotalFloat(),freeFloat:new Ro(e.freeFloat).getFreeFloat()});var Qi=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=Po({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=bo(u);o.set(l,f),c.set(l,p),s=await We(s)}return{totalFloatMap:o,freeFloatMap:c}};var tn=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=Ki(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let s=t||this.gantt;if(this.gantt=s||_o(),$i(this.gantt))return!1;let o=new Io(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new To(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 Qi({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}}}},Lo=tn;var Rp=e=>e==="fnet"||e==="fnlt"||e==="mfo",bp=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Lp(e,t){let r=e.constraintDate;if(!r||!Rp(e.constraintType))return r;let i=bp(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()?gi(e,t):r}function wp(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 Op(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 xp(e){let t=Op(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:Lp(i,e)})}),r}function Np(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 Fp(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 wo(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=wp(u);return r.set(l,f),f},n=Fp(e);await Z();let a=xp(e);await Z();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await Z();let o=Np(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 Mp=1e3;function Wp(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 en(e,t,r=()=>!0){if(!r())return null;let i=await wo(e,t);if(!r())return null;let n=new Lo(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>=Mp&&(l=0,await Z(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,Wp(d,f,s))}return r()?c:null}async function Er(e,t,r=()=>!0){let i=await en(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 zt(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=nt(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 Oo=new Set;var xo=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]),Up=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"]),Bp=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Fo(e){return!Bp.has(e.kind)}var Hp=new Set;function jp(e){return e.kind==="inline-edit"?Be.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Be.has(t.column)):!1}function rn(e,t){return!(Up.has(e.kind)||t.has(e.kind)||jp(e))}function Mo(e){return rn(e,Hp)}function He(e){return rn(e,Oo)}function Wo(e){return rn(e,xo)}function nn(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 Vp(e){return Wo(e)&&nn(e)}var No=new Set([P.PROGRESS,P.HH_WORK_TIME,P.DURATION,P.COST,P.USED_COST,P.REAL_COST]);function Yp(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?No.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>No.has(t.column)):!1}var at={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 Uo(e,t,r){let i=new Set;t.ran&&i.add(at.AUTOSCHEDULE),i.add(at.PARENT_BOUNDS),Yp(e)&&i.add(at.PARENT_PROGRESS),nn(e)&&i.add(at.REAL_WORK);let n=!r.skipAutoSchedule;return n&&Wo(e)&&i.add(at.EXPECTED_PROGRESS),n&&Vp(e)&&i.add(at.REAL_COST),n&&He(e)&&!r.skipCriticalPath&&i.add(at.CRITICAL_PATH),i}async function z(e,t){let r=Kp(t);r.has(at.AUTOSCHEDULE)&&await qp(e.adapter,t);let i=r.has(at.AUTOSCHEDULE)?await $p(e,t.autoscheduleFrom):zp();return await Jp(e.adapter,t,i.scheduledIds,r),await Xp(e,r,t.now),i}function Kp(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,i=new Set(Uo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&i.add(at.PARENT_PROGRESS),i}async function $p(e,t){let r=t==="roots"?{}:{triggerId:t},i=await e.scheduler.schedule(r),n=Gp(e.adapter,i.updatedIds);return Le(e.adapter,i),n}function Gp(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 zp(){return{scheduledIds:[]}}async function qp(e,t){let r=t.collectDirty?t.collectDirty([]):Oi(t.recomputeParentsFrom,[]);r.size!==0&&await pe(e,r,!1)}async function Jp(e,t,r,i){let n=t.collectDirty?t.collectDirty(r):Oi(t.recomputeParentsFrom,r);await pe(e,n,i.has(at.PARENT_PROGRESS),{recomputeRealWork:i.has(at.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function Xp(e,t,r){t.has(at.EXPECTED_PROGRESS)&&r!==null&&(Zp(e.adapter)&&$t(e.adapter,r,e.defaultBaseCalendarId??null),Ot(e.adapter,r),St(e.adapter,e.sector.statusCriteria)),t.has(at.REAL_COST)&&zt(e.adapter),t.has(at.CRITICAL_PATH)&&await Er(e.adapter,e.sector.hoursPerDay)}function Zp(e){let t=!1;return e.forEachActivity(r=>{nt(r)&&(t=!0)}),t}var Qp=new Set([P.CONSTRAINT_TYPE,P.CONSTRAINT_DATE]),th=new Set(["mso","mfo"]);function Rr(e){return Qp.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||Ht.has(a)||th.has(a))return!1;let s=an(n.startDate),o=an(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=eh(t,a,String(n.calendarId??""),i),l=an(n.constraintDate);return rh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function eh(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?bt(e,n,t):e}function an(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 rh(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 z(e,Bo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=i(s,o);a=a||c}if(a){let s=await z(e,Bo(t));n=nh(n,s.scheduledIds)}return He(t.action)&&await z(e,ih(t)),{scheduledIds:n}}function Bo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function ih(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function nh(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function ah(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 sn(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&&!ah(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 V(e,t){let r=oh(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let d=lh(n);ch(e,n,d,i,r)}let a=t.sirDetection==="before-diff"?sn(i,e,r):[],s=sh(t.correlativeShifts,r),o=await io(e,i,r,s),c=t.sirDetection==="after-diff"?sn(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 sh(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 oh(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 ch(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(wi(s,o)).length!==0&&(i.set(a,s),n.add(a))}}function lh(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 Ho(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:s}=r,o=Vt(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);dh(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 D=i.getActivity(e.activityId),R=D?D.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 p=o.transform(c,d.value,n,d.raw),m=Yt(e.activityId,p),k=await q(i,m),C=Se(i,String(e.activityId)),I=c.constraintDate;Kt(i,e.activityId,p),Bt(e.activityId,p.postProcessors??[],i,k.get(String(e.activityId))??null);let T=ke(C,i,String(e.activityId));if(e.column===P.CUSTOM_ID){let D=k.get(String(e.activityId)),R=D?D.customId:null,x=typeof R=="string"?R:null,O=typeof d.value=="string"?d.value:null;x!==O&&r.customIdTracker.trackCustomIdChange(x,O)}let _=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:D=>Sr(e.activityId,m,D),now:r.now,options:t}),A=Rr(e.column),{scheduledIds:h}=await(A?wr({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:_(),revertTargets:br(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:I}],revert:(D,R)=>Lr(D,R,i,n.calendars)}):z({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},_())),g=(p.trackingEvents??[]).map(D=>({name:D.name,properties:D.properties??{}})),v=Ce(e.activityId,p.constraintWarning);return{ok:!0,changes:await V(i,{source:e,beforeSnap:k,touchedIds:m,scheduledIds:h,sirDetection:"before-diff",links:T,trackingEvents:g,...v?{warnings:[v]}:{},hoursPerDay:s.hoursPerDay})}}function dh(e){return e===P.DURATION||e===b.AUTO_SCHEDULING}function uh(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 fh(e,t,r,i){return e.map((n,a)=>{let s=n.kind==="create"?i?.get(a):void 0,o=Wt(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 ph(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function jo(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 on([vh(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Vo(e,t,r){let{hoursPerDay:i}=r.sector,n=e.operations.map(s=>yh(s,i)),a=hh(e.operations);return on(n,e,t,r,a)}function hh(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 yh(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:mt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:mt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function on(e,t,r,i,n){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=i;s.invalidateAllCaches();let{activityIds:l,links:d}=uh(e,a),u=await q(a,l),f=fh(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 p=mh(f,d,a),{scheduledIds:m}=await z({adapter:a,scheduler:s,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),k=Or(f,d,a);return{ok:!0,linkVerdicts:f.map((C,I)=>C.rejected===null?{operationIndex:I,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:I,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:ph(d),changes:await V(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:m,links:k,hoursPerDay:o.hoursPerDay})}}function mh(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=gh(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function gh(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 vh(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:mt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:mt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Yo(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:mt(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 k=i.getLink(m);k&&f.push(k)}let p=s?dr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):ur({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return on(p.operations,e,t,r)}var vt={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 dt(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(Go);let r=[];Ko(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),Ah(a,n)}n+=1;let s=yi(String(a.id),e);s.sort(Go),Ko(r,s)}return i}function Ko(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function $o(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:pi}var Go=(e,t)=>$o(e)-$o(t);function Ah(e,t){e.correlativeId=t}function ln(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=cn(l,b.WORK_HOURS),u=Ch(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||L(o))break;r=o}}function zo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||L(i)||ln(i,t)}function cn(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ch(e,t,r,i){return i.hasChildren(e)?cn(t,b.REAL_WORK_HOURS):ft(r,cn(t,b.PROGRESS))}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.USED_COST))}t.setActivityField(r,b.USED_COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function qo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||L(i)||dn(i,t)}function Ih(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function un(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+=Sh(c,b.COST))}t.setActivityField(r,b.COST,n);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Jo(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||L(i)||un(i,t)}function Sh(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}),Xo="New Master Plan",Zo="New Activity";var kh=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Qo=new Set(kh);function Dh(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"||!Qo.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function tc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=Dh(e.activityOverrides??{}),n=e.numTasksInGantt===0?Xo:Zo,a=i.name??n,s=i.durationHours??e.sector.hoursPerDay,o=i.calendarId??e.sector.defaultCalendar,c=Th(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 Th(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function _h(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&&Mt(t.type):Ph(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=Si,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:_h(t)}}function Ph(e){return Mt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Fr(e,t,r,i){let n=t,a=n==="0",s=fn(e,n);if(i!==void 0){let c=s.find(l=>l.id===i);if(c){let l=ct(c),d=s.map(ct).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=ct(c),d=s.map(ct).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(ct))+1}var re=Number.MAX_SAFE_INTEGER,ec=Number.MAX_SAFE_INTEGER-1;function ct(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:re}function fn(e,t){let r=[];return e.forEachActivity(i=>{Pt(i.parentId)===t&&r.push(i)}),r}function rc(e,t,r){let i=e,n=qt(e,r);for(;n!=null&&t.has(n);)i=n,n=qt(n,r);return i}function Mr(e,t,r){let i=new Set([e]),n=Pt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=Pt(r.getActivity(n)?.parentId)}return!1}function qt(e,t){let r=t.getActivity(e);if(!r)return null;let i=Pt(r.parentId),n=ut(i,t),a=n.findIndex(s=>String(s)===String(e));return a<=0?null:n[a-1]??null}function ic(e,t,r,i){let n=ut(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(ct);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 pn(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;n.invalidateAllCaches();let l=Eh(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=bh(e.activityId,i,o),m=c.next(),k={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Fh(s)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:m,activityOverrides:e.overrides??{}},I=tc(k,{getActivity:v=>i.getActivity(v),calculateEndDate:v=>i.calculateEndDate(v),getClosestWorkTime:v=>i.getClosestWorkTime(v)}).newTask;I.realWorkHours=ft(I.workHours,I.progress),wh(I,e,t,u,d,r);let T=Fr(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);I.correlativeId=T;let _=new Set([p]);d&&_.add(d.id);let A=d!==null&&i.getChildren(d.id).length===0,h=A?d?.customId:null,g=r.skipBeforeSnap?new Map:await q(i,_);return i.addActivity(I),Oh(e,p,d,i,A),h&&t.customIdTracker.releaseCustomId(h),zo(p,i),qo(p,i),Jo(p,i),xh(i,p,g,_,r),{ok:!0,newId:p,parent:d,newActivity:I,beforeSnap:g,initialTouched:_}}function Eh(e,t){let r=L(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=Rh(e,t,r,s);return o||{ok:!0,parent:i,anchorSiblingId:s,isRoot:r}}function Rh(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 bh(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function Lh(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function wh(e,t,r,i,n,a){let{adapter:s,customIdTracker:o}=r,c=Lh(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??i,d=l!==void 0,u=d?s.getActivity(l):n;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Oh(e,t,r,i,n){if(!r)return;let a=De({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:s=>i.getActivity(s)??null});if(a){for(let[s,o]of Object.entries(a.fields))rt(i,a.parentId,s,o);a.promotionSnapshot&&i.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function xh(e,t,r,i,n){if(n.skipCorrelativeRecompute)return;let a=dt(e);n.skipBeforeSnap||kr(e,a,new Set([String(t)]),r,i)}async function Nh(e,t,r,i,n){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:vt.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),V(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:i,trackingEvents:[l],hoursPerDay:n})}async function nc(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=await pn(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 z({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 Nh(i,e,s,d,a.hoursPerDay)}}function Fh(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 Mh(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=fn(t,r).sort((a,s)=>ct(a)-ct(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:n}}function Wh(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function ac(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,s=Mh(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 I of e.activities){let T=l.get(I.originalParentId),_,A,h;T!==void 0?_=T:(_=s.parentId,u===void 0?(A=s.firstAfter,h=s.firstBefore):A=u);let g=await pn({kind:"activity-create",parentId:_,afterSiblingId:A,beforeSiblingId:h,...I.activityId?{activityId:I.activityId}:{},overrides:Wh(I.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.referenceActivityId});if(!g.ok)return g;if(I.baselineSnapshot!==void 0){let v=I.baselineSnapshot;i.setActivityField(g.newId,"baselineSnapshot",v?{...v,startDate:v.startDate?new Date(v.startDate):null,endDate:v.endDate?new Date(v.endDate):null}:null)}l.set(I.originalId,g.newId),d.push(g.newId),T===void 0&&(u=g.newId)}let f=dt(i),p=new Set(d.map(String));kr(i,f,p,o,c);for(let I of d)c.add(String(I));let m=[];for(let I of e.links){let T=l.get(I.source),_=l.get(I.target);if(T===void 0||_===void 0)continue;let A={kind:"create",source:T,target:_,type:I.type,lag:mt(I.lag,a.hoursPerDay)},h=Wt(A,{port:i,newLinkId:I.linkId?()=>I.linkId:r.linkIdGen.next});m.push({op:A,finalLinkId:h.applied?h.linkId:null,rejected:h.applied?null:h.rejected??"link_op_rejected"})}let{scheduledIds:k}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),C=Or(m,new Map,i);return{ok:!0,changes:await V(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:k,links:C,hoursPerDay:a.hoursPerDay})}}function sc(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 oc(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 xt(e,t){ln(e,t),dn(e,t),un(e,t)}function cc(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 lc(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 Uh(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 Bh(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=Uh(e.promotionSnapshot)??(i?{type:de,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Bh(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 dc(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 uc=200;async function fc(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 v of e.activityIds)if(!i.getActivity(v))return{ok:!1,reason:E.ACTIVITY_NOT_FOUND};let o=cc(e.activityIds,i),c=lc(o,i),l=new Set;for(let v of e.activityIds){let D=i.getActivity(v);if(!D)continue;let R=D.parentId;if(L(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 v of c){let D=i.getLink(v);D&&f.set(v,{...D})}let p=new Set,m=0;for(let v of o){m+=1,m%uc===0&&await Z();let D=i.getActivity(v);if(!D)continue;let R=L(D.parentId)?null:i.getActivity(String(D.parentId)),x=R?.hasNewActivities===!0&&R.newActivityIds.some(j=>String(j)===String(v));(D.isNewActivity===!0||x)&&p.add(v);let O=D.customId;typeof O=="string"&&O.length>0&&a.releaseCustomId(O)}for(let v of c)i.removeLink(v);let k=jh(i,o),C=0;for(let v of o)C+=1,C%uc===0&&await Z(),i.removeActivity(v);for(let v of l){let D=i.getActivity(v);if(!D)continue;Hh(D,p,i);let R=i.getChildren(v),x=Te({parent:D,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(v),computeEndDate:(O,j)=>i.calculateEndDate({startDate:O,durationHours:j,task:D}),idsRemoved:o});if(!x){hr(v,i);continue}for(let[O,j]of Object.entries(x.fields))rt(i,v,O,j);if(D.customId==null||D.customId===""){let O=qt(v,i),j=O?i.getActivity(O)?.customId:null,Y=a.generateCustomIdForRestoredChild(typeof j=="string"&&j?j:null);i.setActivityField(v,b.CUSTOM_ID,Y)}}for(let v of l)xt(v,i);let I=dt(i),{scheduledIds:T}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),_={name:vt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(_.properties.event_source=e.eventSource);let A=new Map;for(let[v,D]of f)A.set(v,D);let h=new Map;for(let v of o){let D=u.get(String(v));D&&h.set(String(v),D)}let g=await V(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:T,sirDetection:"after-diff",links:Vh(f),trackingEvents:[_],hoursPerDay:s.hoursPerDay,correlativeShifts:I});return{ok:!0,changes:k.length>0?{...g,viewState:k}:g,__beforeSnap:h,__beforeLinks:A}}function Hh(e,t,r){let i=dc({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))rt(r,i.parentId,n,a)}function jh(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 Vh(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 Wr(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)||(pc(s,a,t)||pc(a,s,t))&&i.push(String(n.id))}return i}function pc(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||L(s))return!1;let o=s;if(o===t)return!0;i=o}return!1}async function hc(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=L(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 h=i.getActivity(c);if(!h)return{ok:!1,reason:E.ANCHOR_SIBLING_NOT_FOUND};if((h.parentId===null?"0":String(h.parentId))!==e.parentId)return{ok:!1,reason:E.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Pt(l),u=String(e.parentId),f=d!==u,p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let m=await q(i,p);f&&i.setActivityField(e.activityId,b.PARENT,u);let k=Fr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,b.CORRELATIVE_ID,k),f){if(!o){let h=i.getActivity(e.parentId);if(h){let g=h.customId,v=Mt(h.type)&&i.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,D=De({parentId:e.parentId,newChildId:e.activityId,getParent:R=>i.getActivity(R)??null,isCurrentlyLeaf:v,promotionSource:"reparent"});if(D){for(let[R,x]of Object.entries(D.fields))rt(i,D.parentId,R,x);D.promotionSnapshot&&i.setPromotionSnapshot(D.parentId,D.promotionSnapshot),D.fields.customId===null&&xr(g,r.customIdTracker)}}}if(d!=="0"){let h=i.getActivity(d);if(h){let g=i.getChildren(d),v=Te({parent:h,remainingChildIds:g.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(D,R)=>i.calculateEndDate({startDate:D,durationHours:R,task:h}),idsRemoved:new Set([e.activityId])});if(v){for(let[j,Y]of Object.entries(v.fields))rt(i,d,j,Y);let D=qt(d,i),R=D?i.getActivity(D)?.customId:null,x=typeof R=="string"&&R?R:null,O=r.customIdTracker.generateCustomIdForRestoredChild(x);i.setActivityField(d,b.CUSTOM_ID,O)}}}}f&&(d!=="0"&&xt(d,i),o||xt(e.parentId,i));let C=dt(i);for(let h of C){if(p.add(h.activityId),m.has(h.activityId))continue;let g=i.getActivity(h.activityId);if(!g)continue;let v=J(g);h.before!==void 0&&(v.correlativeId=h.before),m.set(h.activityId,v)}let I=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:T}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...I],now:r.now,options:t,recomputeParentProgress:f}),_=f?Wr([e.activityId],i):[],A={name:vt.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&&(A.properties.event_source=e.eventSource),{ok:!0,changes:await V(i,{source:e,beforeSnap:m,touchedIds:p,scheduledIds:T,sirDetection:"before-diff",trackingEvents:[A],hoursPerDay:a.hoursPerDay})}}async function yc(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,f=new Set(s),p=[...e.activityIds].sort((h,g)=>{let v=i.getActivity(h),D=i.getActivity(g),R=v?ct(v):re,x=D?ct(D):re;return R-x});for(let h of p){if(!i.getActivity(h)){c.push({activityId:h,reason:E.ACTIVITY_NOT_FOUND}),f.delete(h);continue}if(Mr(h,u,i))continue;let v=ta(h,f,i);if(v==null){c.push({activityId:h,reason:E.INDENT_NO_ELIGIBLE_SIBLING}),f.delete(h);continue}let D=i.getActivity(h)?.parentId,R=L(D)?"0":String(D);d.push({activityId:h,newParentId:v,oldParentId:R}),u.add(h),o.add(h),o.add(v),R!=="0"&&o.add(R)}let m=await q(i,o);for(let{activityId:h,newParentId:g}of d)i.setActivityField(h,b.PARENT,g),i.setActivityField(h,b.CORRELATIVE_ID,ec),l.push(h);let k=new Set;for(let{activityId:h,newParentId:g}of d){if(k.has(g))continue;k.add(g);let v=i.getActivity(g);if(!v)continue;let D=v.customId,R=Mt(v.type)&&i.getChildren(g).filter(j=>!l.includes(j)).length===0,x=v.hasNewActivities&&v.newActivityIds.some(j=>String(j)===String(h)),O=De({parentId:g,newChildId:h,getParent:j=>i.getActivity(j)??null,isCurrentlyLeaf:R,promotionSource:"reparent"});if(O){for(let[j,Y]of Object.entries(O.fields))rt(i,O.parentId,j,Y);O.promotionSnapshot&&i.setPromotionSnapshot(O.parentId,O.promotionSnapshot),x||(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(D,r.customIdTracker)}let C=new Set;for(let h of d)h.oldParentId!=="0"&&C.add(h.oldParentId),C.add(h.newParentId);for(let h of C)xt(h,i);let I=dt(i);for(let h of I){if(o.add(h.activityId),m.has(h.activityId))continue;let g=i.getActivity(h.activityId);if(!g)continue;let v=J(g);h.before!==void 0&&(v.correlativeId=h.before),m.set(h.activityId,v)}let{scheduledIds:T}=await z({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),_=Wr(l,i),A={name:vt.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(h=>({activity_id:h.activityId,reason:h.reason})),invalid_link_ids:_}};return e.eventSource!==void 0&&(A.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let g=c.find(v=>String(v.activityId)===String(h));return g?{activityId:String(h),ok:!1,reason:g.reason}:{activityId:String(h),ok:!0}}),changes:await V(i,{source:e,beforeSnap:m,touchedIds:o,scheduledIds:T,trackingEvents:[A],hoursPerDay:a.hoursPerDay})}}async function mc(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 h of e.activityIds){let g=h;i.getActivity(g)&&(o.set(g,hi(g,i)),c.set(g,rc(g,s,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],m=new Set,k=[...e.activityIds].sort((h,g)=>{let v=i.getActivity(h),D=i.getActivity(g),R=v?ct(v):re,x=D?ct(D):re;return R-x});for(let h of k){let g=h,v=i.getActivity(g);if(!v){d.push({activityId:g,reason:E.ACTIVITY_NOT_FOUND});continue}if(Mr(g,m,i))continue;let D=v.parentId;if(L(D)){d.push({activityId:g,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let R=String(D),x=i.getActivity(R);if(!x){d.push({activityId:g,reason:E.ACTIVITY_NOT_FOUND});continue}let O=x.parentId;if(L(O)){d.push({activityId:g,reason:E.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let j=String(O),Y=hi(R,i)+1,it=c.get(g);if(it!=null&&s.has(it)){let Ee=o.get(it)??-1,lt=o.get(g)??-1;Ee>=0&&lt>=0&&(Y+=lt-Ee)}p.push({activityId:g,grandparentKey:j,oldParentKey:R,targetIndexInGrandparent:Y}),m.add(g),l.add(String(g)),l.add(String(R)),j!=="0"&&l.add(String(j)),f.add(R)}let C=await q(i,l);for(let h of p){i.setActivityField(h.activityId,b.PARENT,h.grandparentKey);let g=ic(i,h.grandparentKey,h.targetIndexInGrandparent,h.activityId);i.setActivityField(h.activityId,b.CORRELATIVE_ID,g),u.push(h.activityId)}for(let h of f){let g=i.getActivity(h);if(!g)continue;let v=i.getChildren(h),D=Te({parent:g,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(h),computeEndDate:(Y,it)=>i.calculateEndDate({startDate:Y,durationHours:it,task:g}),idsRemoved:new Set(p.filter(Y=>Y.oldParentKey===h).map(Y=>Y.activityId))});if(!D){hr(h,i);continue}for(let[Y,it]of Object.entries(D.fields))rt(i,h,Y,it);let R=qt(h,i),x=R?i.getActivity(R)?.customId:null,O=typeof x=="string"&&x?x:null,j=r.customIdTracker.generateCustomIdForRestoredChild(O);i.setActivityField(h,b.CUSTOM_ID,j)}let I=new Set;for(let h of f)I.add(String(h));for(let h of p)h.grandparentKey!=="0"&&I.add(String(h.grandparentKey));for(let h of I)xt(h,i);let T=dt(i);for(let h of T){if(l.add(h.activityId),C.has(h.activityId))continue;let g=i.getActivity(h.activityId);if(!g)continue;let v=J(g);h.before!==void 0&&(v.correlativeId=h.before),C.set(h.activityId,v)}let{scheduledIds:_}=await z({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}),A={name:vt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(h=>({activity_id:String(h.activityId),reason:h.reason}))}};return e.eventSource!==void 0&&(A.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let g=d.find(v=>String(v.activityId)===String(h));return g?{activityId:String(h),ok:!1,reason:g.reason}:{activityId:String(h),ok:!0}}),changes:await V(i,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:_,trackingEvents:[A],hoursPerDay:a.hoursPerDay})}}async function gc(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=Vt(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=Yt(e.activityId,l),u=await q(i,d);Kt(i,e.activityId,l),Bt(e.activityId,l.postProcessors??[],i);let{scheduledIds:f}=await z({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}),p=(l.trackingEvents??[]).map(m=>({name:m.name,properties:m.properties??{}}));return{ok:!0,changes:await V(i,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function vc(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 k=Yh(m,r);if(s.push(k.verdict),!k.verdict.ok||!k.changes)continue;let C=Yt(m.activityId,k.changes);Kh(o,C,r);for(let A of C)c.add(A);let I=Se(i,m.activityId),T=Ir(i,String(m.activityId));Kt(i,m.activityId,k.changes),Bt(m.activityId,k.changes.postProcessors??[],i,T),d.push(...ke(I,i,m.activityId)),f||=!!k.changes.needsAutoSchedule;for(let A of k.changes.trackingEvents??[])l.push({name:A.name,properties:A.properties??{}});let _=Ce(m.activityId,k.changes.constraintWarning);_&&u.push(_)}let{scheduledIds:p}=await z({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 V(i,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Yh(e,t){let{ctx:r}=t,i=e.activityId,n=Vt(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 Kh(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 hn=P.CUSTOM_ID;async function Ac(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=[],p=[],m=[],k=!1;for(let _ of e.edits){let A=$h(_,r);if(o.push(A.verdict),!A.verdict.ok||!A.changes)continue;let h=Ce(_.activityId,A.changes.constraintWarning);h&&m.push(h);let g=Yt(_.activityId,A.changes);Jh(c,g,r);for(let O of g)u.add(O);qh(l,_,c),br(_.column)&&d.add(String(_.activityId));let v=Se(i,_.activityId),D=Ir(i,String(_.activityId)),R=Gh(_,r),x=A.changes;Kt(i,_.activityId,x),Bt(_.activityId,A.changes.postProcessors??[],i,D),zh(_,R,r),p.push(...ke(v,i,_.activityId)),k||=!!A.changes.needsAutoSchedule;for(let O of A.changes.trackingEvents??[])f.push({name:O.name,properties:O.properties??{}})}let C={action:e,autoscheduleFrom:k?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},I=l.size>0,{scheduledIds:T}=await(I?wr({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([_])=>!d.has(_)).map(([_,A])=>({activityId:_,priorConstraintDate:A})),revert:(_,A)=>Lr(_,A,i,r.ctx.calendars)}):z({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},C));return{ok:!0,verdicts:o,changes:await V(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:T,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:m,hoursPerDay:a.hoursPerDay})}}function $h(e,t){let{ctx:r}=t,i=e.activityId,n=Vt(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===hn&&o.value!==null){let u=t.adapter.getActivity(e.activityId),f=u?u.customId:null,p=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(o.value),p))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 Gh(e,t){if(e.column!==hn)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function zh(e,t,r){if(e.column!==hn)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 qh(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 Jh(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 Xh(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 Cc(e,t,r,i){let n=new Set,a=new Set;for(let s of e)Xh(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));Cc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},n),Cc(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);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}for(let c of i){let l=t.adapter.getLink(c.id);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function Sc(e){return typeof e=="string"&&e.length>0?wt(e):e instanceof Date?e:null}function yn(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 Ur(e,t){let r=yn(e.duration),i=yn(e.cost),n=yn(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:Sc(e.start_date),endDate:Sc(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 kc(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=>Ur(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 Zh(e){let t=nt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Dc(e){let t=[];return e.forEachActivity((r,i)=>{let n=Zh(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 Br(e,t,r,i,n=null){let a=new Set;for(let s of kc(e,t,i))a.add(s);if(r)for(let s of $t(e,r,n))a.add(s);for(let s of Dc(e))a.add(s);for(let s of zt(e))a.add(s);return[...a]}function Tc(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=Qh(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(nt(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 Qh(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=nt(i);if(!n)return 0;if(t==="COST")return Hr(n.cost);if(t==="HH")return Hr(n.workHours);let a=i.type;return a==="project"?_c(e,r):a==="milestone"?0:Hr(n.durationDays)}function _c(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=nt(n);if(!a)continue;let s=n.type;s==="project"?r+=_c(String(i),t):s!=="milestone"&&(r+=Hr(a.durationDays))}return r}function Hr(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Pc(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,P.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&Tc(String(i),e,t)})}function jr(e){for(let t of ty(e))ry(t,e)}function ty(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,ey(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function ey(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ry(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 Vr(e,t){Pc(t,e.adapter),jr(e.adapter),e.now&&($t(e.adapter,e.now,e.defaultBaseCalendarId??null),Ot(e.adapter,e.now)),zt(e.adapter),e.now&&St(e.adapter,e.sector.statusCriteria)}function Ec(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 Rc(e,t){let r=await q(t.adapter,new Set(t.adapter.getAllIds())),i=Ec(t),n=Br(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Ec(t)!==i&&Vr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await V(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function iy(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function bc(e,t){iy(e.criterion);let r=new Set(t.adapter.getAllIds()),i=await q(t.adapter,r);return Vr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await V(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Lc(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 V(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function wc(e,t,r){return e.kind==="persistence-acknowledge"?Ic(e,r):e.kind==="baseline-apply"?Rc(e,r):e.kind==="ponderator-criterion-set"?bc(e,r):e.kind==="status-criteria-set"?Lc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?jo(e,t,r):e.kind==="links-batch"?Vo(e,t,r):e.kind==="activity-create"?nc(e,t,r):e.kind==="activity-paste"?ac(e,t,r):e.kind==="activity-delete"?fc(e,t,r):e.kind==="activity-move"?hc(e,t,r):e.kind==="activity-indent"?yc(e,t,r):e.kind==="activity-outdent"?mc(e,t,r):e.kind==="activity-set-progress"?gc(e,t,r):e.kind==="dates-batch"?vc(e,t,r):e.kind==="bulk-edit"?Ac(e,t,r):e.kind==="selection-toggle"?Yn(e,mn(r)):e.kind==="selection-replace"?Kn(e,mn(r)):e.kind==="visibility-set"?$n(e,mn(r)):e.kind==="filter-set"?Xn(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?ra(e,{adapter:r.adapter}):e.kind==="sir-sync"?sc(e,r):e.kind==="activity-lookahead-sync"?oc(e,r):e.kind==="inline-edit"&&(e.column===P.CUSTOM_PREDECESSORS||e.column===P.CUSTOM_SUCESSORS)?Yo(e,t,r):e.kind!=="inline-edit"?Ha(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Ho(e,t,r)}function mn(e){return{adapter:e.adapter}}var ny=new Set(["startDate","endDate","constraintDate"]);function Oc(e,t){return ny.has(e)&&typeof t=="string"?new Date(t):t}function xc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?ay(n,r):null}}}function ay(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 sy(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 oy={}.constructor.toString();function cy(e){var t=e.constructor.toString();return t!==oy}function ly(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 sy(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Dt(e[t]);break;default:if(cy(e))r=Object.create(e);else{if(ly(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 Nc(e){return typeof e<"u"}var Yr;function gn(){return Yr||(Yr=new Date().valueOf()),Yr++,Yr}function ht(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var uy=(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)},fy=(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)},Fc={date_to_str:uy,str_to_date:fy},py=(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}}),hy=(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])},Mc={date_to_str:py,str_to_date:hy};function Wc(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=Fc;return a()&&(l=Mc),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=Fc;return a()&&(l=Mc),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),p=1+Math.floor(f/7);return p},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 vn(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function An(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 Cn(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 yy(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 Uc=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 vn)return t;var r;if(t.date?r=new vn(t.date,t.unit,t.task,null,t.calendar):r=new vn(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 An)return r;var i;if(ie(r)?i=new An(r):i=new An(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=yy,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 Cn)return a;var s;if(ie(a)?s=new Cn(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new Cn(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 Bc(){}Bc.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 p in d.dates){let m=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&m)),Array.isArray(f)){let k=Array.isArray(m)?m:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,k))}}}};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 In=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}},Sn=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={}}},kn=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 my(){return typeof Map<"u"?new In:new Sn}var Dn=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 Tn(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=my(),this._largeUnitsCache=new kn(this),this._dateDurationCache=new Dn,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Tn.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 p=!1;a.valueOf()<s.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(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&&p?(f=!1,o+=(s.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):o++;else{var m=this._getUnitOrder(r),k=this.units[m-1];k&&!this._isWorkTime(a,k)&&(c=this._getClosestWorkTimeFuture(a,k))}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=ht(this._getMinutesPerDay,this):o=ht(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),p=d+f+u;return p},_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),p=d+f+u;return Math.round(p)},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 Tn))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(ht(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(ht(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 p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_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 p=r;return i===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:i,end:p}},_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 p=Math.abs(Math.round((d-u)/60));n-=p,i+=p,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 p=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&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var k=!1,C=null,I=null,T=c.length-1;T>=0;T--)if(c[T].start<m-1&&c[T].end>=m-1){k=!0,C=c[T],I=c[T-1];break}if(k)if(m===C.end&&p>=C.durationMinutes)n+=C.durationMinutes,i=this.$gantt.date.add(i,-C.durationMinutes,"minute");else if(!a&&p<=m/60-C.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=m/60-C.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=m/60-C.startMinute,I?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,I.end)):i=this.$gantt.date.day_start(i));else{var _=this._getMinutesPerHour(i);_<=p?(n+=_,i=this._nextDate(i,"hour",r)):(s=this._subtractMinutesUntilHourStart(i,p),n+=s.added,i=s.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var A=this._getClosestWorkTimePast(i,"hour");if(A.valueOf()===i.valueOf()){var A=this.$gantt.date.add(i,-1,"day"),h=this._getWorkHours(A);if(h.length){var g=h[h.length-1];A.setUTCSeconds(g.durationSeconds)}}i=A}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var v=t-n;s=this._subtractMinutesUntilHourStart(i,v),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 p=!1,m=null,k=0;k<o.length;k++)if(o[k].start<=f&&o[k].end>f){p=!0,m=o[k];break}if(p)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 C=this._getMinutesPerHour(i);C<=u?(n+=C,l?i=this.$gantt.date.add(i,C,"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 I=t-n;a=this._addMinutesUntilHourEnd(i,I),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 gy(){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 vy=gy();function Hc(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))}Hc.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 Bc,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 Tn(this.$gantt,Uc(this.$gantt));t.id=String(gn());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=vy.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||gn(),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 _n(e,t){this.argumentsHelper=t,this.$gantt=e}_n.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 _n},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 jc(e){this.$gantt=e.$gantt,this.argumentsHelper=Uc(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new _n(this.$gantt,this.argumentsHelper)}jc.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 Ay=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:ht(e.mergeCalendars,e),createCalendar:ht(e.createCalendar,e),addCalendar:ht(e.addCalendar,e),getCalendar:ht(e.getCalendar,e),getCalendars:ht(e.getCalendars,e),getResourceCalendar:ht(e.getResourceCalendar,e),getTaskCalendar:ht(e.getTaskCalendar,e),deleteCalendar:ht(e.deleteCalendar,e)}},Cy={create:Ay};function Vc(e){var t=new Hc(e),r=new jc(t),i=Cy.create(t,r);_e(e,i)}var Yc={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 Kc(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||Yc,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:Nc,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=Wc(r),r.date.init(),Vc(r),r}function Iy(e={}){let t=Kc(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 $c={createCalendar:Iy};var dw=3600*1e3;function Jc(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Sy}=$c,Ve="__replay_default__";function ky(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 Gc={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},zc="__main_global__",Dy={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function qc(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 Ty(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:ky(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Xc(e){let t=Sy({config:{work_time:!0}});t.addCalendar({id:Ve,worktime:Gc}),t.addCalendar({id:zc,worktime:Dy});let r=new Set(e.filter(d=>!qc(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>qc(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Ty(d.worktime):Gc});let n=xc(t),a=n.getCalendar(Ve),s=n.getCalendar(zc);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 p=a;return o.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function Zc(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 _y(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 _y(e,t){let r=[],i=new yt;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 Kr=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:Qc(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:Qc(r)}))}};function Qc(e){return{...e}}var $r=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=tl(t);return this.reader.getCalendar(r??Ve)}getClosestWorkTime(t){let r=`${En(t.task)}|${t.dir}|${t.date.getTime()}`;return Pn(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:st.HOUR}))}calculateEndDate(t){let r=`${En(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Pn(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${En(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Pn(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 Pn(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var Py="__default__";function tl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function En(e){return tl(e)??Py}var Gr=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&&!L(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||L(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(L(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(L(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 zr=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 Kr;_viewState=new zr;_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 $r(Xc(t.calendars)),this._flags=Ry(t),this._hierarchy=new Gr(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=Qn(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))??el}getIncomingLinkIds(t){return this._incoming.get(String(t))??el}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(),Rn(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,Oc(r,i)),r===b.PARENT&&this._hierarchy.markDirty(),Rn(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),Rn(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){il(this._outgoing,String(t.source),t.id),il(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),rl(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),rl(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(!Ey(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))}},el=[];function Ey(e){return e===bi.LAG||e===bi.TYPE}function Rn(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function rl(e,t){return e.filter(r=>String(r)!==String(t))}function il(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Ry(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 nl(e,t){let r=e.getActivity(t);return r?Q(r):null}function al(e){return e.getAllActivities().map(Q)}function sl(e){return e.getAllIds().map(String)}function ol(e,t){e.forEachActivity((r,i)=>t(i))}function cl(e,t){let r=t==="0"?bn(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(Q(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function bn(e,t){let r=t;if(r==="0"){let i=[];return e.forEachActivity((n,a)=>{L(n.parentId)&&i.push(a)}),i}return ut(r,e)}function ll(e){return e.checkedIds().map(String)}function dl(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=L(i.parentId)}),r}return e.getChildren(t).length>0}function ul(e,t){let r=e.getLink(t);return r?kt(r):null}function fl(e){return e.getAllLinks().map(t=>kt(t))}function qr(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function by(e){return e.reduce((t,r)=>qr(r)<qr(t)?r:t)}function Ly(e){return e.reduce((t,r)=>qr(r)>qr(t)?r:t)}function wy(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function pl(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=wy(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:by(i),endHour:Ly(n)}}function hl(e,t){return{calendars:e.calendarReader,hierarchy:Zc(e),activityReader:Jc(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function yl(e){return He(e)}function vl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>({...i,after:null}));return Q({...e,activities:t,links:r})}function Ln(e,t,r,i,n){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:i,afterLinks:n}}function Al(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 Cl(e){return e.kind!=="inline-edit"||!Be.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function ml(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 Il(e,t){if(!ml(e)||!ml(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Sl(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 Ln(o)}function kl(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 wn(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 On(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:gl(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:gl(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"?Oy(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function gl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:Q(i.after),after:Q(i.before)}:{before:Q(i.before),after:Q(i.after)}]))}function Oy(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 xn(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Dl(e,t){_l(e,t,"before")}function Tl(e,t){_l(e,t,"after")}function _l(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))rt(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))Qs(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 xy=100,Ny=600,Jr=class{constructor(t=xy){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<=Ny&&n!==void 0&&Il(n,t)?this.undoStack[this.undoStack.length-1]=Sl(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 Fy=["parentId","correlativeId"];function El(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(Pl(c.parentId?.before));continue}let s=n.fields;!s||!Fy.some(c=>c in s)||(i(a),"parentId"in s&&r.add(Pl(s.parentId?.before)))}return r}function Pl(e){return e==null?"0":String(e)}function My(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Wy(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Rl(e){return{id:String(e.id),worktime:Wy(e.worktime)}}function Xr(e,t,r,i=[]){let n=t.map(My),a=[...r.map(Rl),...i.map(Rl)];return{activities:[...e],links:n,calendars:a}}var bl=["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","responsableIds","tagIds"],Ll=new Set(["startDate","endDate","constraintDate","dateOrigin"]),wl=new Set(["newActivityIds","responsableIds","tagIds"]);function Ol(e){let t=bl.map(r=>[r,Uy(r,e[r])]);return Object.fromEntries(t)}function Uy(e,t){return Ll.has(e)?t instanceof Date?new Date(t):null:wl.has(e)?Array.isArray(t)?[...t]:[]:t}function Nn(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of bl)if(!By(r,e[r],t[r]))return!0;return!1}function By(e,t,r){return Ll.has(e)?Hy(t,r):wl.has(e)?jy(t,r):(t??null)===(r??null)}function Hy(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function jy(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 Zr=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),{persistable:Ol(r),deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}})}snapshotLinks(t){this.linksAtLastSave.clear();for(let r of t)r.proplannerId!=null&&this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}hasUnsavedChanges(t,r){return this.initialized?this.deletedActivities(t).length>0||this.deletedLinks(r).length>0||t.some(n=>{if(n.proplannerId==null)return!0;let a=this.activitiesAtLastSave.get(String(n.id));return!a||Nn(n,a.persistable)})?!0:r.some(n=>{if(n.proplannerId==null)return!0;let a=this.linksAtLastSave.get(String(n.id));return!a||n.lag!==a.lag||n.type!==a.type}):!1}deletedActivities(t){if(!this.initialized)return[];let r=new Set(t.map(n=>String(n.id))),i=[];for(let[n,a]of this.activitiesAtLastSave)r.has(n)||i.push({...a.deletedSnapshot});return i}deletedLinks(t){if(!this.initialized)return[];let r=new Set(t.map(i=>String(i.id)));return Array.from(this.linksAtLastSave.entries(),([i,n])=>r.has(i)?null:{...n}).filter(i=>i!==null)}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?Nn(r,i.persistable):!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 xl=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Fn=[!1,!0,!0,!0,!0,!0,!1],Nl=new Set(["1","true"]),Mn="DURATION",Fl="asap",Ml={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 Wl(e,t){let r=[],i=e.map(a=>{let s=Xy(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Qy(i);let n=new Set(i.map(a=>a.id));return tm(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function Vy(e){return e===0}function Yy(e,t){if(!e)return null;let r=Ml[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Fl):r}function Ky(e,t){let r=Yy(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?wt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function $y(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function Gy(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 zy(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Wn(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)zy(r)&&t.push(String(r.id));return t}function qy(e){return e==="0"?null:String(e)}function Jy(e,t){return Array.isArray(e)?e.map(r=>Ur(r,t)).filter(r=>r!==null):[]}function Xy(e,t){let r=$y(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:s}=Ky(e,t.reporter),o=e.type==="milestone",c=wt(e.start_date),l=o?c:wt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:qy(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:Vy(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:wt(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:Zy(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Gy(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Wn(e.pendingRequests),responsableIds:Wn(e.responsables),tagIds:Wn(e.tags),baselinePoints:Jy(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 Zy(e){return e.has_childs?null:e.custom_id}function Qy(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function tm(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 jl(e,t,r,i=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>im(c,i)),o=(r??[]).map(c=>nm(c,i));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:rm(s)}}function rm(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Vl(e,t){let r=dm(e.working_days),{days:i,hours:n}=lm(e,r),a=am(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 im(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return Vl(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function nm(e,t){return Vl(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function am(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=sm(i.from_date,i.to_date,t);if(n.length===0)continue;let a=om(i);if(a!==void 0)for(let s of n)r[s]=a}return Object.keys(r).length>0?r:null}function sm(e,t,r){let i=Ul(e),n=Ul(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 Ul(e){if(typeof e!="string")return null;let t=xl.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 om(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=cm(t);if(r.length>0)return r}}var Bl=/^\d{1,2}:\d{2}$/;function cm(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();!Qr(o)&&!Qr(c)&&Bl.test(o)&&Bl.test(c)&&t.push(`${o}-${c}`);continue}let s=Kl(i.startsCsv,i.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Yl),t}function Hl(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 Yl(e,t){return Hl(e)-Hl(t)}function lm(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Kl(l,d);for(let f=0;f<7;f+=1){let p=u[f],m=r[f];p&&m&&m.push(p)}},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(Yl);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 Kl(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];Qr(c)||Qr(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 dm(e){if(typeof e!="string")return[...Fn];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Fn]:t.map(r=>Nl.has(r))}var um=new Set(["false","null"]);function Qr(e){return!e||um.has(e)}function fm(e){return e==="0"||e==="1"||e==="2"||e==="3"}function pm(e){if(typeof e!="string")return null;let t=ys(e);return t||(fm(e)?e:null)}function zl(e,t){let r=[];for(let i of e)try{r.push(hm(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return ym(r)}function hm(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=pm(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:mt(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function ym(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||Gl(r)>Gl(n))&&t.set(i,r)}return[...t.values()]}function Gl(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function mm(e){if(typeof e!="string")return Mn;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Mn}}function gm(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function vm(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ql(e){let t=gm(e),r=vm(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:mm(e.activity_creter),statusCriteria:mi}}function ti(e,t=ue){let r=ql(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:s}=jl(e.calendars,e.sector.calendars,e.baseCalendars,Am(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=Wl(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=zl(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function Am(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 Jl(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 Xl(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 Zl(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 Ql(e){return!!e&&typeof e=="string"&&e.trim().length>0}function ei(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ri(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function td(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function ed(e,t){return!t&&Ql(e)}function rd(e,t){return t&&Ql(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 Cm(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 At(e,t){let r=Ye(e),i=Ye(t),n=r+i;return Cm(n,e)}function ii(e,t){let r=Ye(e),i=Ye(t);return r<i?-1:r>i?1:0}function ni(e,t){return ii(e,t)<=0?e:t}function ai(e,t){return ii(e,t)>=0?e:t}function id(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ni(t,r))}function nd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ai(t,r))}function ad(e){return{prefix:e,baseSuffix:null}}function sd(e,t){let r=ri(e);return{prefix:ei(e),baseSuffix:At(r,t)}}function od(e){return{prefix:e,baseSuffix:null}}function cd(e,t){return ed(e,t)?"parentConversion":rd(e,t)?"pasteReference":"noContext"}function Im(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var si=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?Im(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=id(i),r.max=nd(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 ei(t)}extractSuffix(t){return ri(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=ni(r,i.min),i.max=ai(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=ni(i,n.min),n.max=ai(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:At(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}${At(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(;ii(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=At(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=At(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=At(a,n)}let s=At(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,At(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=td(r),a=cd(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=At(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 ad(this.defaultPrefix);case"pasteReference":return sd(r,this.suffixIncrement);default:return od(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=At(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 Sm=1,km=-1;function Dm(e,t){return!e&&!t?null:e&&t?0:e?Sm:km}function ld(e){return e==null}function dd(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Tm(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 _m(e,t){let r=Nt(e.field);return r===null?null:(i,n)=>{let a=r.extract(i,t),s=r.extract(n,t),o=Dm(ld(a),ld(s));if(o!==null)return o;let c=r.valueKind==="enum"?dd(a,r.order)-dd(s,r.order):Tm(a,s,t.locale);return e.direction==="desc"?-c:c}}function ud(e,t){let r=e.rules.map(i=>_m(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 fd(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),Pm(e,r)}function Pm(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 oi(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?ft(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 pd(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(dt(t),r.updateDurationForPrimaveraEndDate&&Rm(t),bm(t),oi(t),n){a&&(Ot(t,a),St(t,r.statusCriteria));return}let s=await i.schedule({});Le(t,s),Lm(t),Em(t),await pe(t,void 0,!1),a&&(Ot(t,a),St(t,r.statusCriteria))}function Em(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 Rm(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function bm(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=bt(t.constraintDate,n,r))})}function Lm(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=bt(t.constraintDate,i,r))})}var _t={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function hd(e){let t=e.clock??null,r=t?Oe(t()):null,i=e.reporter??ue,n=ti({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=Xr(n.activities,n.links,n.calendars,o),l=I=>ud(I,ce(a.hoursPerDay)),d=new Pe(c,l);d.hydrateViewState({hiddenIds:n.viewStateSeed.hiddenIds});let u=new fr(d,i);fd(d);let f=Jl({knownIds:n.activities.map(I=>I.id)}),p=Xl({knownIds:n.links.map(I=>I.id)}),m=Zl({knownIds:n.activities.map(I=>I.uniqueCorrelativeId)}),k=new si({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(k.populateFromActivities(n.activities),e.baselinePoints&&e.baselinePoints.length>0){let I=o.find(T=>T.baseDefault)?.id??null;Br(d,e.baselinePoints,r,i,I)}let C=pd({state:d,sector:a,scheduler:u,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:d,scheduler:u,activityIdGen:f,linkIdGen:p,uidGen:m,customIdTracker:k,calendars:s,baseCalendars:o,clock:t,reporter:i,initPromise:C}}var ci=class{_status=_t.READY;coreRuntime;_undo=new Jr;_opQueue=Promise.resolve();_scheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=hd(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 Q(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),nl(this.coreRuntime.state,t)}getAllActivitiesView(){return this.assertReady(),al(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),cl(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ul(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),fl(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?Q(i[r]):null}getAllIds(){return this.assertReady(),sl(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),ol(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),bn(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),ll(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(),dl(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?Q(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>Q(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>Q(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),pl(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(Q)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(this.coreRuntime.state.getAllActivities()).map(Q)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(this.getAllLinksView()).map(Q)}_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=hl(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),n=kl(t);this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let a;try{a=await wc(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"&&xn(a.changes)){let s=Al(this.coreRuntime.state,a.changes);this._undo.record(Ln(vl(a.changes),a.__beforeSnap,a.__beforeLinks,s.afterSnap,s.afterLinks),Cl(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?(Mo(t)&&xn(a.changes)&&this._recordScheduleMutation(r.skipCriticalPath!==!0),wm(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||!Fo(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=El(t,a=>r.getParentId(a));if(i.size===0)return null;let n=[...i].map(a=>({parentId:a,childIds:ut(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(Xr(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 en(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 V(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 V(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(jr(t),oi(t),zt(t),this.coreRuntime.clock){let r=Oe(this.coreRuntime.clock());Ot(t,r);let i=!1;t.forEachActivity(n=>{i||=nt(n)!==null}),i&&$t(t,r,this.coreRuntime.baseCalendars.find(n=>n.baseDefault)?.id??null),St(t,this.coreRuntime.sector.statusCriteria)}}undo(t={}){let r=this._enqueue(async()=>{this.assertReady();let i=this._undo.takeUndo();if(!i)return null;Dl(this.coreRuntime.state,i),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),wn(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=On(this.coreRuntime.state,i,"before");return this._reapplyViewState(n)??n});return r.then(i=>{i&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",n)})},()=>{}),r}redo(t={}){let r=this._enqueue(async()=>{this.assertReady();let i=this._undo.takeRedo();if(!i)return null;Tl(this.coreRuntime.state,i),this._recomputeAfterHistoryRestore(),this._recordScheduleMutation(!1),wn(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(i),this._undo.resetCoalesce();let n=On(this.coreRuntime.state,i,"after");return this._reapplyViewState(n)??n});return r.then(i=>{i&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",n)})},()=>{}),r}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 Zr;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 wm(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}function yd(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 md=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var gd={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 vd=8;var $={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"},Om={[$.PERSISTENCE_ACKNOWLEDGE]:!0,[$.BASELINE_APPLY]:!0,[$.PONDERATOR_CRITERION_SET]:!0,[$.STATUS_CRITERIA_SET]:!0,[$.INLINE_EDIT]:!0,[$.DATES_BATCH]:!0,[$.BULK_EDIT]:!0,[$.LINK_CREATE]:!0,[$.LINK_UPDATE]:!0,[$.LINK_DELETE]:!0,[$.LINKS_BATCH]:!0,[$.ACTIVITY_CREATE]:!0,[$.ACTIVITY_DELETE]:!0,[$.ACTIVITY_MOVE]:!0,[$.ACTIVITY_INDENT]:!0,[$.ACTIVITY_OUTDENT]:!0,[$.ACTIVITY_SET_PROGRESS]:!0,[$.ACTIVITY_PASTE]:!0,[$.SELECTION_TOGGLE]:!0,[$.SELECTION_REPLACE]:!0,[$.VISIBILITY_SET]:!0,[$.FILTER_SET]:!0,[$.SORT_SET]:!0,[$.SIR_SYNC]:!0,[$.ACTIVITY_LOOKAHEAD_SYNC]:!0},Ad=Object.keys(Om);var Cd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Pd(xm);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map