@outbuild-company/schedule-core 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var Bn=Object.defineProperty;var eu=Object.getOwnPropertyDescriptor;var ru=Object.getOwnPropertyNames;var nu=Object.prototype.hasOwnProperty;var iu=(e,t)=>{for(var r in t)Bn(e,r,{get:t[r],enumerable:!0})},au=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ru(t))!nu.call(e,i)&&i!==r&&Bn(e,i,{get:()=>t[i],enumerable:!(n=eu(t,i))||n.enumerable});return e};var su=e=>au(Bn({},"__esModule",{value:!0}),e);var av={};iu(av,{ACTIVITY_TYPE:()=>Ce,CALENDAR_UNIT:()=>it,COLUMN:()=>P,CONSTRAINT_TYPE:()=>$,CONSTRAINT_TYPE_TO_LABEL:()=>Jd,CREATION_KIND:()=>Qd,DEFAULT_HOURS_PER_DAY:()=>Xd,DISPATCH_ACTION_KIND:()=>K,DISPATCH_ACTION_KINDS:()=>Zd,DISPATCH_TRACK_EVENT:()=>It,LINK_CODE_TO_TYPE:()=>re,LINK_TYPE:()=>B,LINK_TYPE_CODE:()=>Ts,NEW_ACTIVITY_DEFAULTS:()=>sn,REJECTION_REASON:()=>C,ROOT_PARENT_ID:()=>N,SCHEDULE_CORE_STATUS:()=>bt,STATUS:()=>Rt,ScheduleCore:()=>Wn,WORK_TIME_DIRECTION:()=>Z,checkNoUpdatedLinks:()=>ld,computeExpectedProgress:()=>pi,expectedProgressFromBaseline:()=>we,getActiveBaseline:()=>ut,getUnsavedActivities:()=>qd,isRootParent:()=>L,normalizeParentKey:()=>Ut,parseFromBackend:()=>En,willRunCriticalPath:()=>jl,yieldToBrowser:()=>Q});var ht=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 hr=e=>String(e);function Fa(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=hr(t),l=new Set([...n].map(String)),d=new Set(l),u=ou(c,i).filter(s),f=u.filter(h=>!a(h)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let h of f)r?d.add(h):d.delete(h);return p||cu({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:lu(l,d),parentBlocked:p}}function ou(e,t){let r=[],n=new ht;n.enqueue(e);let i=new Set([e]);for(;!n.isEmpty();){let a=n.dequeue();for(let s of t.getChildrenIds(a)){let o=hr(s);i.has(o)||(i.add(o),r.push(o),n.enqueue(o))}}return r}function cu(e){let{id:t,isChecked:r,autoCheckParents:n,hierarchy:i,isFrozen:a,exists:s,next:o}=e,c=i.getParentId(t);for(;c!==null&&typeof c<"u";){let l=hr(c);if(a(l))return;let d=i.getChildrenIds(l).map(hr).filter(s),u=d.some(a),f=d.filter(g=>!a(g)),h=f.length>0&&f.every(g=>o.has(g))&&!u;if(r){if(!n||!h||o.has(l))return;o.add(l)}else{if(h||!o.has(l))return;o.delete(l)}c=i.getParentId(l)}}function lu(e,t){let r=[],n=[];for(let i of t)e.has(i)||r.push(i);for(let i of e)t.has(i)||n.push(i);return{checked:r,unchecked:n}}function ve(e){return(e.pendingRequestIds?.length??0)>0}var C={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",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",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",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var xa=(e,t)=>{let r=e.getActivity(t);return r!=null&&ve(r)},Na=(e,t,r)=>{let n=[],i=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&n.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)i(a,!0);for(let a of r.unchecked)i(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}};function Ma(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let i=e.frozenIds?new Set(e.frozenIds):null,a=i?o=>i.has(o):o=>xa(r,o),s=Fa({clickedId:n,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:Na(e,r,s.changed)}}function yr(e,t){let{adapter:r}=t,n=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!xa(r,s))),i=new Set(r.checkedIds().map(String)),a={checked:[...n].filter(s=>!i.has(s)),unchecked:[...i].filter(s=>!n.has(s))};return{ok:!0,changes:Na(e,r,a)}}function Ae(e,t,r=e.getAllIds()){let n=[];for(let i of r){let a=String(i),s=t.has(a),o=e.isVisible(a);o!==s&&(e.setVisible(a,s),n.push({activityId:a,visible:{before:o,after:s}}))}return n}function Wa(e,t){let{adapter:r}=t,n=new Set(e.visibleIds.map(String)),i=Ae(r,n);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var du=["Waiting","Done","Doing","Overdue","Advancement"],uu=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function Un(e,t){return e===null||t<=0?null:e/t}function fu(e,t){let r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((n-r)/864e5)+1}var pu={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=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>Un(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>e.type==="milestone"?0:fu(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)=>Un(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>Un(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},expectedProgressBaseline:{valueKind:"number",equalityPrecision:2,extract:e=>e.expectedProgressBaseline},expectedProgress:{valueKind:"number",extract:e=>e.expectedProgress},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:du,extract:e=>e.status},constraintType:{valueKind:"enum",order:uu,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 Bt(e){return pu[e]??null}function jn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function wt(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function hu(e,t,r){let n=e===null;return r==="includes"?!n&&String(e).toLowerCase().includes(t.toLowerCase()):r==="notIncludes"?n||!String(e).toLowerCase().includes(t.toLowerCase()):r==="is"?!n&&String(e)===t:r==="isNot"?n||String(e)!==t:!1}function yu(e,t,r,n){if(e===null||typeof e!="number")return r==="notEquals";let i=n===void 0?e:Number(e.toFixed(n));return r==="equals"?i===t:r==="notEquals"?i!==t:r==="greaterThan"?e>t:r==="lessThan"?e<t:r==="greaterOrEqual"?e>=t:r==="lessOrEqual"?e<=t:!1}function mu(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function gu(e,t,r){if(!(e instanceof Date))return!1;let n=wt(e),i=wt(t);return r==="after"?n>i:r==="before"?n<i:!1}function vu(e,t,r){if(!(e instanceof Date))return!1;let n=wt(e);return n>=wt(t)&&n<=wt(r)}function Au(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function Iu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function Ba(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Ua(e,t,r){let n=Bt(t.field);if(n===null)return!1;let i=n.extract(e,r),{operator:a}=t;return a==="between"?n.valueKind==="number"?mu(i,Number(t.value),Number(t.valueTo)):n.valueKind==="date"?vu(i,jn(t.value),jn(t.valueTo)):!1:n.valueKind==="string"?hu(i,String(t.value),a):n.valueKind==="number"?yu(i,Number(t.value),a,n.equalityPrecision):n.valueKind==="date"?gu(i,jn(t.value),a):n.valueKind==="id-array"?Au(i,Ba(t.value),a):Iu(i,Ba(t.value),a)}function Cu(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>Ua(e,n,r)):t.criteria.every(n=>Ua(e,n,r))}function ku(e,t){let r=wt(e.startDate),n=wt(e.endDate),i=wt(t.start),a=wt(t.end),s=r>=i&&n<=a,o=r>=i&&r<=a,c=i>=r&&i<=n;return s||o||c}function Hn(e,t,r){let n=Cu(e,t,r),i=t.dateRange,a=i===void 0||ku(e,i);return n&&a}function Su(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function ja(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=[];for(let o of t)Hn(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)Su(o,r,a);return a}function Du(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=new Map,o=new Map,c=new Map;for(let l of t){let d=String(l.id),u=r(d);o.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=Hn(l,n,i);s.set(d,f?1:0),f&&a.add(d)}return{matchedIds:a,visibleReferenceCounts:s,parentIds:o,remainingChildren:c}}function Tu(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:n}=e,i=[];for(let a of r.keys())n.get(a)===0&&i.push(a);for(;i.length>0;){let a=i.pop();if(a===void 0)break;let s=r.get(a);if(s==null)continue;let o=t.get(a)??0;t.set(s,(t.get(s)??0)+o);let c=(n.get(s)??1)-1;n.set(s,c),c===0&&i.push(s)}}function _u(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function mr(e){let t=Du(e);Tu(t);let r=_u(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function Ha(e,t,r){let n=new Set;for(let i of t){let a=String(i.id);n.add(a);let s=e.matchedIds.has(a),o=Hn(i,e.filter,e.context);if(s===o)continue;o?e.matchedIds.add(a):e.matchedIds.delete(a);let c=o?1:-1,l=a;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(n.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return n}function te(e){return{hoursPerDay:e,locale:"en"}}var Pu={string:new Set(["includes","notIncludes","is","isNot"]),number:new Set(["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual","between"]),date:new Set(["after","before","between"]),"id-array":new Set(["someOf","notSomeOf"]),enum:new Set(["someOf","notSomeOf"]),boolean:new Set(["someOf","notSomeOf"]),reference:new Set(["someOf","notSomeOf"])};function Va(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:"invalid_value"};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:"invalid_value"};let n=t.getTime(),i=r.getTime();return!Number.isFinite(n)||!Number.isFinite(i)||n>i?{ok:!1,reason:"invalid_value"}:{ok:!0,dateRange:{start:new Date(n),end:new Date(i)}}}function Ya(e){let t=Bt(e.field);if(t===null)return{ok:!1,reason:"unknown_field"};if(!Pu[t.valueKind].has(e.operator))return{ok:!1,reason:"unknown_operator"};if(e.operator==="between")return bu(e,t.valueKind);if(t.valueKind==="number"){let n=Vn(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}if(t.valueKind==="date"){let n=Yn(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}let r=Ru(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind==="boolean"?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind==="id-array"||t.valueKind==="enum"||t.valueKind==="reference"?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function bu(e,t){if(t==="number"){let r=Vn(e.value),n=Vn(e.valueTo);return r===null||n===null||r>n?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:r,valueTo:n}}}if(t==="date"){let r=Yn(e.value),n=Yn(e.valueTo);return r===null||n===null||r.getTime()>n.getTime()?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:r,valueTo:n}}}return{ok:!1,reason:"unknown_operator"}}function Ru(e,t){let{value:r}=e;return t==="boolean"?Array.isArray(r)&&r.every(n=>typeof n=="boolean")?null:"invalid_value":t==="id-array"||t==="enum"||t==="reference"?Array.isArray(r)&&r.every(n=>typeof n=="string"||typeof n=="number")?null:"invalid_value":Array.isArray(r)?"invalid_value":null}function Vn(e){if(typeof e=="string"&&e.trim()===""||typeof e!="string"&&typeof e!="number")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function Yn(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e=="string")t=new Date(e);else if(typeof e=="number")t=new Date(e);else return null;return Number.isFinite(t.getTime())?t:null}function R(e){return structuredClone(e)}function Ka(e){return e.criteria.length===0&&e.dateRange===void 0}function Eu(e,t,r){let n=e.getAllActivities();if(Ka(t))return{visibleIds:ja({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:te(r)}),projection:null};let i=mr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:te(r)});return{visibleIds:i.visibleIds,projection:i}}function Ga(e,t){let{adapter:r,hoursPerDay:n}=t,i=[];for(let u of e.criteria){let f=Ya(u);if(!f.ok)return{ok:!1,reason:f.reason};i.push(f.criterion)}let a=Va(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=R(a.dateRange===void 0?{criteria:i,logic:e.logic}:{criteria:i,logic:e.logic,dateRange:a.dateRange});r.setActiveFilter(Ka(s)?null:s);let{visibleIds:o,projection:c}=Eu(r,s,n);r.setFilterProjection(c);let l=Ae(r,o);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var N="0";function L(e){return e==null||e===0||e==="0"}function Ut(e){return L(e)?"0":String(e)}var Kn=Number.MAX_SAFE_INTEGER;function gt(e,t){let r=Ve(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?gr:(i,a)=>n(i,a)||gr(i,a)),r.map(i=>String(i.id))}function za(e){let t=[],r=i=>{t.push(i);let a=gt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=gt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function qa(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=Ja(n),a=gt(i,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&&!Lu(t,c))return c}return null}function Gn(e,t){let r=t.getActivity(e);if(!r)return-1;let n=Ja(r);return gt(n,t).findIndex(a=>String(a)===String(e))}function Ve(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),n=[];for(let i of r){let a=t.getActivity(i);a&&n.push(a)}return n}function gr(e,t){let r=$a(e),n=$a(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function $a(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Kn}function Ja(e){let t=e.parentId;return t===null?"0":t}function Lu(e,t){return e.has(t)?!0:e.has(String(t))}function Ie(e){let t=[],r=n=>{let i=gt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function $n(e,t){let r=[];for(let n of t){let i=gt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function wu(e){return Bt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function Xa(e,t){let{adapter:r}=t;for(let a of e.rules){let s=wu(a);if(s!==null)return{ok:!1,reason:s}}let n=e.rules.length===0?null:R({rules:e.rules});return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:Ie(r)}}}var Ou={TEXT:"text",DESCRIPTION:"description",DURATION:"duration",PROGRESS:"progress",COST:"cost",USED_COST:"used_cost",HH_WORK_TIME:"hhWorkTime",START_DATE:"start_date",END_DATE:"end_date",CONSTRAINT_TYPE:"constraint_type",CONSTRAINT_DATE:"constraint_date",CALENDAR_ID:"calendar_id",CUSTOM_ID:"custom_id",SUBCONTRACT_ID:"subcontractId",RESPONSABLES:"responsables",TAGS:"tags",CUSTOM_PREDECESSORS:"custom_predecessors",CUSTOM_SUCESSORS:"custom_sucessors"},Fu={REAL_WORK:"real_work",REAL_COST:"real_cost",EXPECTED_PROGRESS:"expected_progress",EXPECTED_PROGRESS_BASE:"expected_progress_base",START_BASE:"start_base",END_BASE:"end_base",DURATION_BASE:"duration_base",COST_BASE:"cost_base",WORK_BASE:"work_base",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"is_critical",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",FREE_SLACK:"freeSlack",TOTAL_SLACK:"totalSlack",CORRELATIVE_ID:"correlative_id",UNIQUE_CORRELATIVE_ID:"unique_correlative_id",PONDERATOR:"ponderator",STATUS:"status"},P={...Ou,...Fu};function Za(e,t){throw new Error(t)}function Qa(e,t){return()=>t()===e}var Z={FUTURE:"future",PAST:"past"},it={HOUR:"hour",DAY:"day"},Rt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var $={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},xu={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 es(e,t,r){if(!t)return{violated:!1};let n=xu[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Nu=new Set(["mso","snet","snlt"]);function Ye(e,t,r){return Nu.has(e)?t:r}function rs(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Mu={snet:{startOfDay:!0,direction:Z.FUTURE},snlt:{startOfDay:!0,direction:Z.PAST},fnet:{startOfDay:!1,direction:Z.FUTURE},fnlt:{startOfDay:!1,direction:Z.PAST},mso:{startOfDay:!0,direction:Z.FUTURE},mfo:{startOfDay:!1,direction:Z.PAST}},vr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ts=(e,t)=>new Date(e.getTime()+t*864e5),Wu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function zn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Mu[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:vr(n),dir:Z.FUTURE,task:e});if(Wu(i,n))return n.getTime()!==vr(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:ts(vr(n),1),dir:Z.PAST,task:e});let a=vr(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:Z.FUTURE,task:e}):t.getClosestWorkTime({date:ts(a,1),dir:Z.PAST,task:e})}function ns(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},n=e.constraintType;if(!n||n==="asap"||n==="alap")return r;let i=zn(e,t);if(!i)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(n){case"snet":return{earliestStart:i,latestStart:null,earliestEnd:a(i),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:i,earliestEnd:null,latestEnd:a(i)};case"fnet":return{earliestStart:s(i),latestStart:null,earliestEnd:i,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(i),earliestEnd:null,latestEnd:i};case"mso":{let o=a(i);return{earliestStart:i,latestStart:i,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(i);return{earliestStart:o,latestStart:o,earliestEnd:i,latestEnd:i}}default:return r}}function is(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function qn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var B={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Ce={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},as={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Jn=typeof window>"u",Bu=!Jn&&typeof MessageChannel<"u";function Q(){return Bu?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 Ar(e,t){return performance.now()-e<as.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Q(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ke(e){return Jn||await Q(),e()?{aborted:!1}:{aborted:!0}}function Ir(e,t){let{inDegree:r,successors:n}=Uu(e,t),i=ju(r),a=Hu(i,r,n),s=a.length<e.length,o=s?Vu(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Uu(e,t){let r=new Map,n=new Map;for(let i of e)r.set(i,0),n.set(i,[]);for(let i of t){let a=i.source,s=i.target;!r.has(a)||!r.has(s)||(n.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:n}}function ju(e){let t=new ht;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function Hu(e,t,r){let n=[];for(;!e.isEmpty();){let i=e.dequeue();n.push(i);for(let a of r.get(i)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return n}function Vu(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var Cr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Ir(t,r),this.cached)}};function ss(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Xn={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 os(e){return e==="project"||e==="task"||e==="milestone"}function St(e,t){return t||os(e)&&Xn[e].alwaysSummary}function Ot(e){return e==="milestone"}function jt(e){return os(e)&&Xn[e].promotesToProjectOnFirstChild}var Zn="project",Se="task";function Ke(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function kr(e,t){let r=t.getActivity(e);return r?St(r.type,t.getChildren(e).length>0):!1}function Sr(e,t,r){let n=String(t),i=r.getActivity(e);for(;i?.parentId&&String(i.parentId)!=="0";){if(String(i.parentId)===n)return!0;i=r.getActivity(i.parentId)}return!1}function Qn(e,t,r){let n=kr(e,r);return kr(t,r)&&Sr(e,t,r)||n&&Sr(t,e,r)}function ds(e,t){let r=[],n=[e];for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);if(a.length===0){String(i)!==String(e)&&r.push(i);continue}for(let s of a)n.push(s)}return r}function Yu(e){let t=new Map;for(let r of e)cs(t,String(r.source),r),cs(t,String(r.target),r);return t}function cs(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function Ku(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)Gu(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function Gu(e,t,r,n,i){let a=String(e),s=r.getActivity(e);if(!s||s.autoScheduling===!1)return!1;let o=n.get(a)??[];for(let c of o)if($u(c,a,s,t,r,i))return!0;return!1}function $u(e,t,r,n,i,a){if(zu(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=qu(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Ju(e,r,c))}function zu(e){return e.source===e.target}function qu(e,t){return String(e.source)===t?e.target:e.source}function Ju(e,t,r){let n=e.lag??0,i=Math.abs(n);return String(e.target)===String(r.id)&&i<=r.durationHours||String(e.target)===String(t.id)&&i<=t.durationHours}function Tr(e,t){let r=[],n=Yu(e),i=0;for(let a of e){let s=kr(a.source,t),o=kr(a.target,t);if(Xu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=ls(a.source,s,t,n,!0),l=ls(a.target,o,t,n,!1);i=af(r,c,l,a,t,i,n)}return r}function Xu(e,t,r,n){return r&&Sr(e.source,e.target,n)||t&&Sr(e.target,e.source,n)}function ls(e,t,r,n,i){return t?Ku(ds(e,r),r,n,i):[e]}function Zu(e,t,r){let n=ds(e,t);if(n.length===0)return null;let i=null,a=null;for(let s of n){let o=r(s);if(!o)continue;(i===null||o.startDate<i)&&(i=o.startDate),(a===null||o.endDate>a)&&(a=o.endDate)}return i===null||a===null?null:{startDate:i,endDate:a}}function Dr(e,t){return Zu(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function Qu(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function tf(e,t,r,n){if(!t)return 0;let i=n.getActivity(e);return!r||!i?-t.durationHours:-n.calculateDuration({startDate:r.startDate,endDate:i.endDate,task:t})}function ef(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function rf(e,t,r,n,i){if(ef(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function nf(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=Dr(e.source,t),a=Dr(e.target,t),s=e.type===B.START_TO_START||e.type===B.START_TO_FINISH,o=e.type===B.FINISH_TO_FINISH||e.type===B.START_TO_FINISH;return{source:r,sourceBounds:i,targetStart:a?.startDate??n?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-Qu(n,a,t):0,summarySourceId:e.type===B.START_TO_START&&i?e.source:void 0,finishAnchoredSummaryTargetId:o&&a?e.target:void 0}}function af(e,t,r,n,i,a,s){let o=nf(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:h,finishAnchoredSummaryTargetId:g}=o,I=a;for(let _ of t){let v=f?tf(_,c,l,i):0;for(let k of r){if(String(_)===String(k))continue;let m=rf(k,d,c,i,s);e.push(sf(n,_,k,I,v,p,u+m,h,g??(m!==0&&p===0?n.target:void 0))),I+=1}}return I}function sf(e,t,r,n,i,a,s,o,c){return{id:`virtual_${e.id}_${n}`,source:t,target:r,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var _r=class{invalidate(){}get(t,r){return Tr(t,r)}};function of(e){let t=new Map,r=n=>(t.has(n)||t.set(n,new Set),t.get(n));for(let n of e)r(n.source).add(n.id),r(n.target).add(n.id);return{neighbors:t}}function cf(e,t,r){let n=new Set,i=new Map,a=new ht;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(n.has(o))continue;n.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}`;i.has(u)||i.set(u,d);let f=String(d.source)===o?d.target:d.source;n.has(String(f))||a.enqueue(f)}}return Array.from(i.values())}function us(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=of(t),i=cf(e,r,n),a=new Set([String(e)]);for(let s of i)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:i}}function ee(e){return e===0}function fs(e,t,r){let n=r.type===B.FINISH_TO_START,i=r.type===B.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:n,isFF:i,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case B.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case B.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case B.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case B.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1}}}function lf(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=Dr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function df(e,t,r,n,i){let a=t.durationHours===0&&i;return{successorStart:n.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function ps(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=fs(e,t,r),l=lf(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return df(e,t,r,n,o||c);let p=o?t:e,h=n.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(h=n.calculateEndDate({startDate:h,durationHours:l,task:e})),a!==0&&(h=n.calculateEndDate({startDate:h,durationHours:a,task:t})),s!==0&&(h=n.calculateEndDate({startDate:h,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:n.getClosestWorkTime({date:h,dir:"past",task:t}),link:r};let g=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:h,dir:"future",task:t}),link:r}}function hs(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=fs(t,e,r),o=n.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-a,task:e})),i!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-i,task:t})),o}function ys(e,t,r){for(let n of e){let i=t.getActivity(n);if(!i)continue;let a=i.constraintType;if(!a||a===$.ASAP||a===$.ALAP)continue;let s=ns(i,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(n,{activityId:n,startDate:i.startDate,endDate:i.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function Pr(e,t,r){let n={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},i=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;i===null?a=qn(e.startDate,n):is(i,n)?a=i:a=qn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function ms(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:n}=e;if(!r||!n)return t;switch(r){case $.MSO:case $.MFO:return new Date(n);case $.SNET:case $.FNET:return n>t?new Date(n):t;case $.SNLT:case $.FNLT:return n<t?new Date(n):t;default:return t}}function uf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function gs(e,t,r){return ti(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ti(e,t,r){return t.dragWithMultiple&&uf(e,r)}async function As(e,t,r,n,i,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=n.draggedIds??[],d=performance.now();for(let u of e){let f=await Ar(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||ff(p,r))continue;let h=s.get(String(u))??[],g=null,I=null,_=!1;for(let w of h){let S=r.getActivity(w.source);if(!S)continue;let A=o(w.source),T=A.startDate.getTime()!==S.startDate.getTime()||A.endDate.getTime()!==S.endDate.getTime(),x={...S,startDate:A.startDate,endDate:A.endDate},F=gs(x,c,l),J={...x,startDate:F.startDate,endDate:F.endDate},G=ti(w.source,c,l)?{...w,lag:0}:w,st=ps(J,p,G,r);(!g||st.successorStart>g)&&(g=st.successorStart,I=String(w.id),_=w._summaryTargetId!==void 0&&!T&&(w._targetLag===0||n.preventSummaryTargetPullback===!0))}g!==null&&_&&g<p.startDate&&(g=new Date(p.startDate));let k=a.get(u),m=k?{...k}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},b=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!g&&!b)){if(g){let w=g;p.type===Ce.MILESTONE&&(w=ms(p,g)),m.drivingLinkId=I,m.startDate=w,m.endDate=r.calculateEndDate({startDate:w,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=w,m.earliestSchedulingEnd=m.endDate}else p.constraintType===$.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===$.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Pr(p,m,r),a.set(u,m)}}return a}function ff(e,t){return St(e.type,t.getChildren(e.id).length>0)}async function Is(e,t,r,n,i,a){let s=new Map(r),o=n.getAllActivities(),c=o.length,l=[];for(let I of o)I.constraintType===$.ALAP&&l.push(I.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let I of t){let _=String(I.source);d.has(_)||d.set(_,[]),d.get(_).push(I);let v=String(I.target);u.has(v)||u.set(v,[]),u.get(v).push(I)}let f=I=>{let _=s.get(I);if(_)return{startDate:_.startDate,endDate:_.endDate};let v=n.getActivity(I);return v?{startDate:v.startDate,endDate:v.endDate}:{startDate:new Date,endDate:new Date}},p=I=>!I.parentId||L(I.parentId)?n.getProjectEnd():f(I.parentId).endDate,h=(I,_)=>{let v=I,k=0;for(;v&&!L(v)&&k++<c+1;){if(String(v)===String(_))return!0;let m=n.getActivity(v);if(!m||!m.parentId)break;v=m.parentId}return!1},g=performance.now();for(let I of e){let _=await Ar(g,a);if(_.aborted)return s;g=_.newSliceStart;let v=n.getActivity(I);if(!v||v.constraintType!==$.ALAP||!v.autoScheduling||v.progress===100||St(v.type,n.getChildren(I).length>0))continue;let k=p(v);if(!k)continue;let m=k,b=null,w=!1,S=d.get(String(I))??[];for(let kt of S){if((kt.lag??0)<0)continue;let ge=n.getActivity(kt.target);if(!ge||ge.autoScheduling===!1)continue;let Oa=f(kt.target),tu={...ge,startDate:Oa.startDate,endDate:Oa.endDate},pr=hs(tu,v,kt,n);pr<m&&(m=pr),(b===null||pr<b)&&(b=pr,w=v.parentId&&!L(v.parentId)?h(kt.target,v.parentId):!1)}if(b!==null)if(w)m=b;else{let kt=f(I).endDate,ge=kt.getTime()>k.getTime()?kt:k;m=b<ge?b:ge}else m>k&&(m=k);let T=(u.get(String(I))??[]).some(kt=>kt.type===B.FINISH_TO_START||kt.type===B.FINISH_TO_FINISH),x=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),F=()=>n.getClosestWorkTime({date:x,dir:"past",task:v}),J=n.getClosestWorkTime({date:m,dir:"future",task:v}).getTime()===m.getTime(),G;v.durationHours===0&&b===null?G=T&&J?F():n.getClosestWorkTime({date:m,dir:"past",task:v}):v.durationHours===0?T?G=F():G=n.getClosestWorkTime({date:m,dir:"future",task:v}):G=n.getClosestWorkTime({date:m,dir:"future",task:v});let st=n.calculateEndDate({startDate:G,durationHours:-v.durationHours,task:v}),pt=s.get(I),nt=pt?{...pt}:{activityId:I,startDate:st,endDate:G,drivingLinkId:null,kind:"alap",conflict:!1};nt.startDate=st,nt.endDate=G,nt.drivingLinkId=null,nt.kind="alap";let ye=nt.earliestSchedulingStart??null;nt.earliestSchedulingStart=null,nt.earliestSchedulingEnd=null;let me=ye!==null&&ye.getTime()>st.getTime()?ye:st;nt.latestSchedulingStart=me,nt.latestSchedulingEnd=me===st?G:n.calculateEndDate({startDate:me,durationHours:v.durationHours,task:v}),Pr(v,nt,n),s.set(I,nt)}return s}var De={warn(){},error(){}};function Et(e){if(e.type==="milestone")return 0;let t=e.startDate?.getTime(),r=e.endDate?.getTime();return t==null||r==null||Number.isNaN(t)||Number.isNaN(r)?null:Math.floor((r-t)/864e5)+1}function Ge(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let n=t.plans.get(r);if(!n)continue;let i=e.getLiveActivity(r);i&&(i.startDate=n.startDate,i.endDate=n.endDate,i.calendarDuration=Et(i),e.updateActivity(r))}})}function ei(e,t){let r=String(t.source),n=String(t.target);if(r===n)return!0;let i=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=i.get(s)??[];c.push(o),i.set(s,c)}return pf(i,n,r)}function $e(e){let t=new Map,r=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=t.get(s)??[];c.push(o),t.set(s,c),r.set(s,r.get(s)??0),r.set(o,(r.get(o)??0)+1)}let n=new ht;for(let[a,s]of r)s===0&&n.enqueue(a);let i=0;for(;!n.isEmpty();){let a=n.dequeue();i+=1;for(let s of t.get(a)??[]){let o=r.get(s)-1;r.set(s,o),o===0&&n.enqueue(s)}}return i!==r.size}function pf(e,t,r){if(t===r)return!0;let n=new Set([t]),i=new ht;for(i.enqueue(t);!i.isEmpty();){let a=i.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;n.has(o)||(n.add(o),i.enqueue(o))}}return!1}function br(e){let t=hf(e);for(let r of t.adjacency.keys())t.records.has(r)||yf(r,t);return t.components}function hf(e){let t=new Map,r=new Set;for(let n of e){let i=String(n.source),a=String(n.target),s=Cs(t,i);if(Cs(t,a),i===a){r.add(i);continue}s.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Cs(e,t){let r=e.get(t);if(r)return r;let n=[];return e.set(t,n),n}function yf(e,t){let r=[];for(r.push({node:e,record:ks(e,t),neighborCursor:0});r.length>0;){let n=r[r.length-1];if(n===void 0)break;let i=t.adjacency.get(n.node)??[];if(n.neighborCursor<i.length){let o=i[n.neighborCursor];if(n.neighborCursor+=1,o===void 0)continue;mf(n,o,r,t);continue}r.pop();let a=r[r.length-1];a&&n.record.lowLink<a.record.lowLink&&(a.record.lowLink=n.record.lowLink),n.record.lowLink===n.record.visitIndex&&gf(n.node,t)}}function mf(e,t,r,n){let i=n.records.get(t);if(!i){r.push({node:t,record:ks(t,n),neighborCursor:0});return}i.onStack&&i.visitIndex<e.record.lowLink&&(e.record.lowLink=i.visitIndex)}function ks(e,t){let r={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,r),t.componentStack.push({node:e,record:r}),r}function gf(e,t){let r=[];for(;;){let s=t.componentStack.pop();if(s===void 0||(s.record.onStack=!1,r.push(s.node),s.node===e))break}let n=r[0],i=r.length===1&&n!==void 0&&t.selfLooped.has(n);(r.length>1||i)&&t.components.push(r)}function ze(e,t,r){let n=r?new ri(e,r):e;return Tr([...t],n)}var ri=class{constructor(t,r){this.base=t;for(let[n,i]of r.reparented){let a=String(n),s=i===null||L(i)?null:i,o=t.getActivity(n)?.parentId??null,c=o===null||L(o)?null:String(o),l=s===null?null:String(s);if(c!==l){if(this.reparented.set(a,s),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(a),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(n),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),n=this.movedOutByParent.get(r),i=this.base.getChildren(t),a=n?i.filter(o=>!n.has(String(o))):[...i],s=this.movedInByParent.get(r);return s&&a.push(...s),a}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let n=String(r),i=new Set,a=this.getActivity(t);for(;a;){let s=a.parentId;if(s===null||L(s))return!1;let o=String(s);if(o===n)return!0;if(i.has(o))return!1;i.add(o),a=this.getActivity(s)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function qe(e){let{port:t,currentLinks:r,proposedLinks:n,proposal:i}=e,a=ze(t,n,i);if(!$e(a))return{ok:!0};let s=ze(t,r),o=Ss(s),l=[...Ss(a)].filter(d=>!o.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function Ss(e){let t=new Set;for(let r of br(e))for(let n of r)t.add(n);return t}function Ht(e,t){switch(e.kind){case"create":return vf(e,t);case"update":return Je(e,t.port);case"delete":return Af(e,t)}}function Er(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),n=new Map,i=[];for(let l of r){let d=Ds(l);n.has(d)||n.set(d,l.id),i.push({source:l.source,target:l.target})}let a=$e(i),s=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){s={applied:!1,rejected:"self-link"};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){s={applied:!1,rejected:"activity-missing"};break}if(Qn(l.source,l.target,t.port)){s={applied:!1,rejected:"hierarchy-link"};break}let u=Ds(l),f=n.get(u);if(f!==void 0){s={applied:!1,rejected:"duplicate",linkId:f};break}if(n.set(u,d),a&&ei(i,{source:l.source,target:l.target}))return{applied:!1,rejected:"cycle"};i.push({source:l.source,target:l.target})}if(!a&&$e(i))return{applied:!1,rejected:"cycle"};if(s)return s;let o=[...r,...e.map(({operation:l,linkId:d})=>({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1}))];if(!qe({port:t.port,currentLinks:r,proposedLinks:o}).ok)return{applied:!1,rejected:"cycle"};for(let{operation:l,linkId:d}of e){let u=t.preserved?.get(d);t.port.addLink({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1,...u?.ganttId===void 0?{}:{ganttId:u.ganttId},...u?.sectorId===void 0?{}:{sectorId:u.sectorId},...u?.proplannerId===void 0?{}:{proplannerId:u.proplannerId}})}return{applied:!0}}function Ds(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function vf(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let n=r.getActivity(e.source),i=r.getActivity(e.target);if(!n||!i)return{applied:!1,rejected:"activity-missing"};if(Qn(e.source,e.target,r))return{applied:!1,rejected:"hierarchy-link"};let a=r.getAllLinks();for(let d of a)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:"duplicate",linkId:d.id};let s=a.map(d=>({source:d.source,target:d.target}));if(ei(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??If)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return qe({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:o}):{applied:!1,rejected:"cycle"}}function Je(e,t){return t.getLink(e.linkId)?(e.lag!==void 0&&t.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&t.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function Af(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}var Rr=null;function If(){return Rr===null&&(Rr=Date.now()),Rr+=1,String(Rr)}var Ts={[B.FINISH_TO_START]:"fs",[B.START_TO_START]:"ss",[B.FINISH_TO_FINISH]:"ff",[B.START_TO_FINISH]:"sf"},re={fs:B.FINISH_TO_START,ss:B.START_TO_START,ff:B.FINISH_TO_FINISH,sf:B.START_TO_FINISH},_s="fs";function Ps(e){if(e in re)return re[e]}var bs=";",Rs=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Lr(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(bs)){if(i.length===0)continue;let a=Cf(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function Cf(e){let t=e.toLowerCase(),r=Rs.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?re[i]:re[_s],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:n,type:o,lag:c}}function Or(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:n}=e,i=[],a=new Map;for(let c of n){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){i.push(c);continue}let d=wr(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(wr(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:i}}function wr(e,t){return`${String(e)}::${t}`}function Fr(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:n}=e,i=[],a=new Map;for(let c of n){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){i.push(c);continue}let d=wr(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(wr(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:i}}function xr(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function vt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var Es={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:Z.FUTURE,date:e,unit:it.HOUR}):t.isWorkTime(e,it.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function ni(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 ii=Es;var Te=class{adapter;reporter;currentCalculationId=0;topoCache=new Cr;expandedLinksCache=new _r;constructor(t,r=De){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,n=Qa(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Df(this.adapter);let a=Vt("schedule.total"),s=Vt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Ft(s);let l=c;if((await ke(n)).aborted)return{...i,cancelled:!0};let d=Vt("schedule.scoping"),u=this.adapter.getAllIds(),f=Tf(t,l,this.adapter),p=f.links,h=f.idSet;Ft(d);let g=Vt("schedule.topologicalSort"),I=Pf(this.topoCache,u,l,h);if(Ft(g),I.hasCycles)return Ft(a),{...i,cycles:[I.cycleNodes]};if((await ke(n)).aborted)return{...i,cancelled:!0};let _=Vt("schedule.processConstraints"),v=new Map;if(ys(I.ordered,this.adapter,v),Ft(_),(await ke(n)).aborted)return{...i,cancelled:!0};let k=Vt("schedule.asapPass"),m=await As(I.ordered,p,this.adapter,t,n,v);if(Ft(k),(await ke(n)).aborted)return{...i,cancelled:!0};let b=Vt("schedule.alapPass"),w=await Is(I.reversed,p,m,this.adapter,t,n);if(Ft(b),(await ke(n)).aborted)return{...i,cancelled:!0};let S=Vt("schedule.diff"),A=[];for(let[T,x]of w){let F=this.adapter.getActivity(T);if(!F)continue;let J=F.startDate.getTime()!==x.startDate.getTime(),G=F.endDate.getTime()!==x.endDate.getTime();(J||G)&&A.push(T)}return Ft(S),Ft(a),{plans:w,updatedIds:A,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},kf=!1;function Sf(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:kf}function Vt(e){return{name:e,startedAt:performance.now()}}function Df(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Ft(e){if(!Sf())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Tf(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=us(n,t);return _f(i,t,r)}function _f(e,t,r){let n=new Set(e.activityIds),i=new Set;for(let s of r.getAllActivities()){let o=String(s.id);s.constraintType===$.ALAP&&!n.has(o)&&(i.add(o),n.add(o))}if(i.size===0)return{idSet:n,links:e.links};let a=[...e.links];for(let s of t)(i.has(String(s.source))||i.has(String(s.target)))&&a.push(s);return{idSet:n,links:a}}function Pf(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return Ir(s,r)}if(!n)return i;let a=ss(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Ls(e,t,r){let n=t.getActivity(e);if(!n)return;let i=r?{...n,endDate:r.endDate}:n,a=t.calendarReader.getCalendar(String(n.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"||Ot(n.type)&&(o.type===B.START_TO_FINISH||o.type===B.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ni(c,i,o.type),f=ii.computeLagBetweenTasks(d,u,a);f!==o.lag&&Je({kind:"update",linkId:o.id,lag:f},t)}}function ws(e,t){let r=t.getActivity(e);r&&Ot(r.type)&&(r.durationHours=0)}function Nr(e){let t=0,r=!1;for(let n of e)n.ponderator>0&&(t+=n.ponderator/100*n.progress,r=!0);return r?t:null}function Os(e){return Number(e.toFixed(2))}function Xe(e){for(let t of bf(e))xs(t,e)}function Fs(e,t){for(let r of e)xs(r,t)}function bf(e){let t=new Set;e.forEachActivity((n,i)=>{e.getChildren(i).length>0&&t.add(i)});let r=new Map;for(let n of t)r.set(n,Rf(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function Rf(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function xs(e,t){let r=t.getChildren(e);if(r.length===0)return;let n=[];for(let i of r){let a=t.getActivity(i);a&&n.push({progress:Number(a.progress??0),ponderator:Number(a.ponderator??0)})}ai(e,n,t)}function ai(e,t,r){let n=r.getActivity(e);if(!n)return;let i=Nr(t);if(i===null){let a=r.getProgressFallback(e);a!==null&&r.setActivityField(e,P.PROGRESS,a);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(n.progress??0)),r.setActivityField(e,P.PROGRESS,Os(i))}function Ns(e,t,r){let n=[e];for(;n.length>0;){let i=n.pop();if(i===void 0)continue;let a=r.getChildren(i);a.length!==0&&(r.setProgressFallback(i,t),n.push(...a))}}function dt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function _e(e,t,r=!0,n={}){let i=t?Ze(e,t):xf(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await Ef(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function Mr(e,t){Ms(e,t,"skip")}async function Ef(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)Ms(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Q()}function Ze(e,t){let r=new Set,n=new Map;for(let s of t)Lf(s,e,r,n);if(r.size===0)return[];let i=Array.from(r),a=wf(i,n);return Ws(i,a)}function Lf(e,t,r,n){let i=t.getParentId(e);for(;i&&!L(i);){if(r.has(i))return;r.add(i);let a=t.getParentId(i);n.set(i,a),i=a}}function wf(e,t){let r=new Map;for(let n of e){if(r.has(n))continue;let i=[],a=new Set,s=n;for(;s&&!L(s)&&!r.has(s)&&!a.has(s);)i.push(s),a.add(s),s=t.get(s)??null;let o=s?r.get(s)??0:0;for(let c=i.length-1;c>=0;c-=1)o+=1,r.set(i[c],o)}return r}function Of(e,t,r){let n=null,i=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();(n===null||l<n)&&(n=l),(i===null||d>i)&&(i=d),r&&(a+=Ff(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:n,maxEnd:i,realWorkSum:a,weightedChildren:s}}function Ms(e,t,r="freeze-when-no-contribution",n=!1){let i=t.getActivity(e);if(!i)return;let a=t.getChildren(e);if(a.length===0)return;let s=Of(a,t,n);if(s.minStart===null||s.maxEnd===null)return;let o=String(i.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),r!=="skip"&&ai(e,s.weightedChildren,t),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Ff(e,t){return t?Number(e.realWorkHours)||0:dt(e.workHours,e.progress)}function xf(e){let t=Nf(e),r=Mf(t,e);return Ws(t,r)}function Nf(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Mf(e,t){let r=new Map;for(let n of e)r.set(n,Wf(n,t));return r}function Wf(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function Ws(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var Bs={updateActivityDuration:ws,updateTaskTiming:Uf("updateTaskTiming"),adjustLinkLagOnTaskMove:Ls,recordLastStartDate:Bf};function Bf(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Yt(e,t,r,n){for(let i of t){let a=i in Bs?Bs[i]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,n??null)}}function Uf(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function O(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function M(e){return{ok:!1,reason:e}}function H(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function U(){return{allowed:!0}}function z(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function j(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 Us={targetField:"name",canEdit(){return U()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e)},validate(){return H()},transform(e,t){return j({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var js={targetField:"description",canEdit(){return U()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e.trim())},validate(){return H()},transform(e,t){return j({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Dt(e){return e.constraintType??$.ASAP}var Wr=100;function Kt(e){return e.progress>=Wr}function et(e,t){return St(e.type,t.hasChildren(e.id))}function Hs(e){return e.progress>0}function Vs(e){return e.hasLookaheadTasks}function ne(e,t){return Math.round(Math.ceil(e*t*60)/60)}var Pe=e=>({endDate:e});function Gt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=i=>Number(r.find(a=>a.type===i)?.value);return new Date(Date.UTC(n("year"),n("month")-1,n("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function Ur(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),n=f=>Number(r.find(p=>p.type===f)?.value),i=n("year"),a=n("month"),s=n("day"),o=Date.UTC(i,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 jf(e,t){let r=Gt(t,"UTC");for(;!e.isWorkTime(r,it.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Gt(r,"UTC");return r}function si(e,t){return e.getClosestWorkTime({direction:Z.FUTURE,date:t,unit:it.HOUR})}function oi(e,t){let r=jf(e,t),n=new Date(r);return n.setUTCDate(n.getUTCDate()+1),n.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:Z.PAST,date:n,unit:it.HOUR})}var Br=new Set(["snet","snlt","mso"]),ci=new Set(["fnet","fnlt","mfo"]),$t=new Set(["asap","alap"]),jr="snet";function xt(e,t,r){let n=Gt(e,"UTC");if(!Br.has(r)&&!ci.has(r))return n;let i=Br.has(r)?si(t,n):oi(t,n),a=new Date(n);return a.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),a}var zt=()=>({constraintType:jr});var ie=e=>({constraintDate:e}),Ys=e=>({constraintDate:e});var Ks={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Gs={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 be(e,t,r){return es(e,t,r)}function Re(e,t,r){return rs(e,t,r)}var zs={targetField:"durationHours",canEdit(e,t){return Kt(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):U()},parseInput(e,t,r){let n=parseFloat(String(e));return Number.isFinite(n)?O(ne(n,r.hoursPerDay)):M("not_a_number")},validate(e,t,r){return $s(r)?tt(Gs.NEGATIVE_DURATION):Hf(t,r)?tt("unchanged"):H()},transform(e,t,r){if($s(t))return j({},{autoSchedule:!1,postProcessors:[]});let n=Vf(e,t,r),i=Yf(e,t,r,n.violated);return{...j(i,{autoSchedule:!0,postProcessors:[Ks.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:Re(n.constraintType,n.constraintDate,qs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function $s(e){return Math.sign(e)===-1}function Hf(e,t){return e===t}function Vf(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)return{violated:!1};let i=e.constraintType;if(i!=="fnet"&&i!=="fnlt"&&i!=="mfo")return{violated:!1};let a=n.calculateEndDate(e.startDate,t);return be(i,e.constraintDate,a)}function Yf(e,t,r,n=!1){let i={};n&&Object.assign(i,zt(),ie(e.startDate));let a=Ke(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=qs(e,t,r);return s&&Object.assign(i,Pe(s)),i}function qs(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var Ee=e=>({realWorkHours:e});var Kf=0,Gf=Wr,Js={targetField:"progress",canEdit(e,t){return Vs(e)?z("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(e,t,r){return $f(r)?tt("out_of_range"):H()},transform(e,t,r){let n=ee(t),i=e.progress!==t&&n,a=zf(t),s=Xf(e,t,r.hierarchy),o={progress:t,autoScheduling:n,...Ee(s.get(e.id)??0)},c=a?qf(e,t,n,r.hierarchy,s):[],l=a?Qf(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=a?ep(e,t):void 0;return j(o,{autoSchedule:i,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:"activity_progress_entry"};function $f(e){return e<Kf||e>Gf}function zf(e){return e===Wr||ee(e)}function qf(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:Jf(t,r,i.get(s)??0)}))}function Jf(e,t,r){return{progress:e,autoScheduling:t,...Ee(r)}}function Xf(e,t,r){let n=new Map,i=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?i(c.id):dt(c.workHours,t);n.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?i(e.id):dt(e.workHours,t);return n.set(e.id,a),n}function Zf(e,t){let r=[e.id,...t.getDescendantIds(e.id)],n=a=>t.getChildProgressInfo(a).some(s=>t.hasChildren(s.id)),i=a=>t.getAncestorIds(a).length;return r.filter(a=>n(String(a))).map(String).sort((a,s)=>i(s)-i(a))}function Qf(e,t,r){let n=new Map;n.set(e.id,t);for(let s of r.getDescendantIds(e.id))n.set(s,t);let i=[...Zf(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=tp(s,n,r);o!==null&&(n.set(s,o),a.push({activityId:s,fields:{progress:o}}))}return a}function tp(e,t,r){let n=r.getChildProgressInfo(e).map(a=>({progress:t.has(a.id)?t.get(a.id):a.progress,ponderator:a.ponderator??0})),i=Nr(n);return i===null?null:Number(i.toFixed(2))}function ep(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Xs={targetField:"cost",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return O(0);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return H()},transform(e,t,r){let n=rp(e,t,r.hierarchy);return j({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function rp(e,t,r){let n=new Map;n.set(e.id,t);let i=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=n.has(o.id)?n.get(o.id):o.cost;n.set(a,s),i.push({activityId:a,fields:{cost:s}})}return i}var Zs={targetField:"usedCost",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return O(0);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return H()},transform(e,t,r){let n=np(e,t,r.hierarchy);return j({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function np(e,t,r){let n=new Map;n.set(e.id,t);let i=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=n.has(o.id)?n.get(o.id):o.usedCost;n.set(a,s),i.push({activityId:a,fields:{usedCost:s}})}return i}var Qs={targetField:"workHours",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){if(String(e).trim()==="")return O(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return H()},transform(e,t,r,n){let i=to(t,e.progress),a=String(n).trim()===""?[]:ip(e,t,i,r.hierarchy);return j({workHours:t,...Ee(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function to(e,t){return dt(e,t)}function ip(e,t,r,n){let i=new Map,a=new Map;i.set(e.id,t),a.set(e.id,r);let s=[];for(let o of n.getAncestorIds(e.id)){let c=0,l=0;for(let d of n.getChildHhInfo(o)){let u=i.has(d.id)?i.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??to(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...Ee(l)}})}return s}function Qe(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function li(e,t){return e.getTime()<t.getTime()}function ae(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Hr=e=>({durationHours:e});var ap="sir-apply",eo={targetField:"startDate",canEdit(e,t,r){return et(e,t)?z("summary","summary_column_value"):Hs(e)?r?.eventSource!==ap?z("has_progress","cant_edit_activity_with_progress"):Kt(e)?z("completed","cant_edit_completed_activity"):ae(r.newValue)?Qe(e.startDate,r.newValue)?U():r.newValue.getTime()>e.startDate.getTime()?z("sir_start_after_progress","sir_cant_move_start_after_progress"):U():U():U()},parseInput(e,t,r){return ae(e)?O(Gt(e,"UTC")):M("invalid_date")},validate(e,t,r,n){if(Qe(t,r))return tt("unchanged");let i=sp(e,r,n);return i||H()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=si(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...j({startDate:i,...Pe(s),...a?Hr(0):{},...zt(),...ie(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:op(e,i,n)}},trackEvent:"activity_start_date_entry"};function sp(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Gt(n,"UTC");return t.getTime()<i.getTime()?tt("before_parent_start"):null}function op(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=Ye(Dt(e),t,n),a=be(Dt(e),e.constraintDate,i);if(a.violated)return Re(a.constraintType,a.constraintDate,i)}var cp=99.999,no={targetField:"endDate",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):lp(e)?z("completed","cant_edit_completed_activity"):U()},parseInput(e,t,r){if(!ae(e))return M("invalid_date");let n=Gt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,it.DAY)?O(oi(i,n)):O(i.getClosestWorkTime({direction:"past",date:n,unit:it.HOUR})):O(n)},validate(e,t,r,n){if(Qe(e.endDate,r))return tt("unchanged");if(dp(r,e))return tt("before_date_origin");if(up(r,e))return tt("before_start_date");let i=fp(r,e,n);return i||H()},transform(e,t,r){let n=pp(e,t),i=hp(e,t,r,!!n);return{...j(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function lp(e){return e.progress>=cp}function dp(e,t){return t.dateOrigin?li(e,t.dateOrigin):!1}function up(e,t){return li(e,t.startDate)}function fp(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,it.DAY)?null:tt("not_working_day"):null}function pp(e,t){if(Dt(e)===$.MSO)return;let n=Ye(Dt(e),e.startDate,t),i=be(Dt(e),e.constraintDate,n);if(i.violated)return Re(i.constraintType,i.constraintDate,n)}function hp(e,t,r,n=!1){let i={};Ot(e.type)&&!n&&ro(e)?Object.assign(i,ie(e.startDate)):(n||ro(e))&&Object.assign(i,zt(),ie(e.startDate));let o=yp(e,t,r),c=Ke(e.durationHours,o);return c&&(i.type=c),Object.assign(i,Hr(o)),i.endDate=t,i}function ro(e){return $t.has(Dt(e))}function yp(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var mp=new Set(Object.values($)),io={targetField:"constraintType",canEdit(e,t){return Kt(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){let t=String(e).toLowerCase();return gp(t)?O(t):M("invalid_constraint_type")},validate(){return H()},transform(e,t,r){let n=vp(e,t,r);return j(n,{autoSchedule:!0})}};function gp(e){return mp.has(e)}function vp(e,t,r){let n=Ip(e,t);return{constraintType:t,...Ys(Ap(e,t,n,r))}}function Ap(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?xt(r,i,t):r}function Ip(e,t){return $t.has(t)?null:Br.has(t)?e.startDate:ci.has(t)?e.endDate:e.constraintDate}var ao={targetField:"constraintDate",canEdit(e,t){return Kt(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){return ae(e)?O(e):M("invalid_date")},validate(){return H()},transform(e,t,r){let n=so(e)?jr:Dt(e),i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=xt(t,i,n),s=Cp(e,a);return j(s,{autoSchedule:!0})}};function Cp(e,t){return{constraintDate:t,...so(e)?zt():{}}}function so(e){return $t.has(Dt(e))||!e.constraintType}var oo={targetField:"calendarId",canEdit(){return U()},parseInput(e){let t=String(e).trim();return kp(t)?M("empty_calendar"):O(t)},validate(e,t,r,n){return Sp(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?H():tt("unknown_calendar")},transform(e,t,r){return j(Dp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function kp(e){return e===""}function Sp(e,t){return e===t}function Dp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?Tp(e.startDate):e.startDate,o=i.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||i.getWorkHours(e.startDate).length===0)&&(n.startDate=o),!e.autoScheduling)return n;let c=n.startDate??e.startDate;Object.assign(n,Pe(i.calculateEndDate(c,e.durationHours)))}return n}function Tp(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var co={targetField:"customId",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):U()},parseInput(e){if(e==null)return M("empty_custom_id");if(typeof e!="string")return M("not_a_string");let t=e.trim();return t.length===0?M("empty_custom_id"):t.length>20?M("exceeds_max_length"):O(t)},validate(){return H()},transform(e,t){return j({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var lo={targetField:"subcontractId",canEdit(){return U()},parseInput(e){if(e==null)return O(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return O(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?M("not_an_integer"):O(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?M("not_an_integer"):O(e):M("not_an_integer")},validate(){return H()},transform(e,t){return j({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function tr(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 Vr(e){return e.some(t=>tr(t)===null)}var uo={targetField:"responsableIds",canEdit(){return U()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):M("not_an_array")},validate(e,t,r){return Vr(r)?tt("missing_id"):H()},transform(e,t){let r=t.map(tr).filter(n=>n!==null);return j({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var fo={targetField:"tagIds",canEdit(){return U()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):M("not_an_array")},validate(e,t,r){return Vr(r)?tt("missing_id"):H()},transform(e,t){let r=t.map(tr).filter(n=>n!==null);return j({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var _p=new Map([[P.TEXT,Us],[P.DESCRIPTION,js],[P.DURATION,zs],[P.PROGRESS,Js],[P.COST,Xs],[P.USED_COST,Zs],[P.HH_WORK_TIME,Qs],[P.START_DATE,eo],[P.END_DATE,no],[P.CONSTRAINT_TYPE,io],[P.CONSTRAINT_DATE,ao],[P.CALENDAR_ID,oo],[P.CUSTOM_ID,co],[P.SUBCONTRACT_ID,lo],[P.RESPONSABLES,uo],[P.TAGS,fo]]);function qt(e){return _p.get(e)}function Le(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 Pp=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],po=new Set(Pp);var E={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",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},er={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",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"};function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function ho(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function Nt(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Lt(e.constraintDate),dateOrigin:Lt(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Lt(t.startDate),endDate:Lt(t.endDate)})),baselineSnapshot:bp(e.baselineSnapshot),criticalPath:Rp(e.criticalPath)}}function Lt(e){return e===null?null:new Date(e)}function bp(e){return e===null?null:{...e,startDate:Lt(e.startDate),endDate:Lt(e.endDate)}}function Rp(e){return e===null?null:{...e,earlyStart:Lt(e.earlyStart),earlyFinish:Lt(e.earlyFinish),lateStart:Lt(e.lateStart),lateFinish:Lt(e.lateFinish)}}var go=200;function Jt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function q(e,t){let r=new Map,n=0;for(let i of t){n+=1,n%go===0&&await Q();let a=e.getActivity(i);a&&r.set(i,X(a))}return r}function X(e){return Nt(e)}function Yr(e,t){let r=e.getActivity(t);return r?Nt(r):null}function Xt(e,t,r){yo(e,t,r.patch);for(let n of r.cascadeMutations??[])yo(e,n.activityId,n.fields)}function yo(e,t,r){for(let[n,i]of Object.entries(r)){if(!po.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function Kr(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%go===0&&await Q();let o=Ep(e,t,s,n);o&&i.push(o)}return i}function Ep(e,t,r,n){let i=e.getActivity(r);if(!i)return{id:r,kind:"deleted",after:null};let a=t.get(r);if(!a&&n?.has(r))return Lp(r,n.get(r),i);let s=ui(a,i);return wp(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:X(i)}}function Lp(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:X(r)}}function wp(e,t,r,n){if(!t?.has(r)||Object.hasOwn(e,"correlativeId"))return;let i=t.get(r);i!==n.correlativeId&&(e.correlativeId={before:i,after:n.correlativeId})}function ui(e,t){let r={},n=e??{},i=t,a=new Set([...Object.keys(n),...Object.keys(i)]);a.delete(E.CALENDAR_DURATION);for(let s of a)(Object.hasOwn(n,s)!==Object.hasOwn(i,s)||!di(n[s],i[s]))&&(r[s]={before:mo(n[s]),after:mo(i[s])});return r}function mo(e){return e===null||typeof e!="object"?e:R(e)}function di(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)=>di(s,t[o]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,n=t,i=Object.keys(r),a=Object.keys(n);return i.length!==a.length?!1:i.every(s=>Object.hasOwn(n,s)&&di(r[s],n[s]))}function Gr(e,t,r){let n=new Set;n.add(e);for(let i of t)n.add(i);for(let i of r)n.add(i);return n}function fi(e,t){let r=new Set;for(let n of e)r.add(String(n));for(let n of t)r.add(n);return r}function $r(e,t,r,n,i){for(let a of t){if(r.has(a.activityId)||(i.add(a.activityId),n.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=X(s);a.before!==void 0&&(o.correlativeId=a.before),n.set(a.activityId,o)}}var Op=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Mt(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(Op);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,n,i,a,s]=t;return new Date(Date.UTC(Number(r),Number(n)-1,Number(i),Number(a),Number(s)))}function we(e,t,r,n){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let i=n.calculateDuration(e,r),a=n.calculateDuration(e,t);return a===0?0:i*100/a}var Fp=e=>e.type==="project",xp=(e,t,r)=>{let n=e.calendarId,i=n!=null?r.calendarReader.getCalendar(String(n)):null;if(!i)return 0;let a=s=>s instanceof Date?s:Mt(String(s));return we(a(e.startDate),a(e.endDate),t,i)};function Np(e,t,r){let n=[],i=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),n.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!Fp(o)){let d=xp(o,t,r);return i(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 i(s,l),l};for(let s of e)a(s);return n}function oe(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),Np(r,t,e)}function ut(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var Mp=e=>e.type==="project",Wp=e=>ut(e),Bp=(e,t,r,n)=>{let i=Wp(e);if(!i)return 0;let a=(i.baseCalendarId!=null?r.getBaseCalendar(`${i.baseCalendarId}-base`):null)??(n?r.getBaseCalendar(n):null);return!a||!i.startDate||!i.endDate?0:we(i.startDate,i.endDate,t,a)};function pi(e,t,r,n=null){let i=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),i.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!Mp(c)){let u=Bp(c,t,r,n);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),h=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*h}let d=l/100;return a(o,d),d};for(let o of e)s(o);return i}function Oe(e,t,r=null){let n={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)},i=[];return e.forEachActivity((a,s)=>{a.parentId===null&&i.push(s)}),pi(i,t,n,r)}var hi="Baseline";function zr(e){return e==="Actual"?"Actual":hi}var vo=e=>Math.round(e*100)/100;function Up(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function jp(e,t){let r=vo(e),n=vo(t);return r>99.99?Rt.DONE:n>r?Rt.OVERDUE:e>0&&r>n?Rt.ADVANCEMENT:e===0&&t===0?Rt.WAITING:e>0&&r<n?Rt.DOING:Rt.WAITING}function Wt(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=jp(a,Up(n,t));n.status!==s&&(rt(e,i,P.STATUS,s),r.push(i))}),r}function yi(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=(i,a)=>s=>s===void 0?t[i]():(t[a](s),n),n={__isMomentShim:!0,clone:()=>yi(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 n}yi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var At=yi;function Hp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function qr(e){return Hp(e)&&!isNaN(e.getTime())}function D(e,t,r,n){if(!qr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(n)}`);let i=t;return e.calculateEndDate({start_date:new Date(i),duration:r,unit:"hour",task:n})}function yt(e){if(!qr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:n,activity:i}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:n,unit:"hour",task:i})}var Vp=e=>e?e.$level===1:!1,Yp=e=>e.type==="project",Kp=e=>e.$level!==0,Gp=e=>e.type==="task",$p=e=>e.type==="task"||e.type==="milestone",lt={byFirstLevel:Vp,filterByParentType:Yp,avoidSubproject:Kp,byTaskType:Gp,byTaskTypeAndMilestone:$p};var y=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var V=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function ce(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Ao(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=zp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=qp({gantt:t,subprojectsWithNoLinks:a}),o=Jp({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:Xp,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function zp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(lt.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function qp(e){let{gantt:t,subprojectsWithNoLinks:r}=e,n=new Set;for(let i of r)t.getChildren(i).filter(o=>{let c=t.getTask(o),l=lt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>n.add(o));return[...n]}function Jp(e){let{gantt:t,childrenIds:r,linkProperty:n,getArrayOfLinkedActivities:i,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[n]||[];i({gantt:t,links:l,linkDirection:n==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function Xp(e){let{gantt:t,links:r,linkDirection:n}=e,i=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[n]);i.push(o)}return i}function Io({gantt:e,linkProperty:t,direction:r}){try{let n=Zp(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Qp(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function Zp(e,t){return e.getTaskByTime().filter(lt.avoidSubproject).filter(lt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Qp(e,t,r){let n=[],i=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?i.add(a.id):o.constraint_type!=="fnlt"&&n.push(a))}),{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:i}}function Co({gantt:e,direction:t,linkProperty:r}){try{let n=th(e),i=new Set,a=new Set,s=new Set;t==="backward"&&nh(n).forEach(d=>{i.add(d.id)});let o=eh(n,t,r),c=rh(n,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:i,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(n){throw n}}function th(e){return e.getTaskByTime().filter(lt.filterByParentType).filter(lt.avoidSubproject)}function eh(e,t,r){return e.filter(n=>{let i=n[r];if(!Array.isArray(i))return!1;let a=i.length>0,s=n.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function rh(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function nh(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function ko({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=ih(r),o=ah(r),c=a[s];if(!Array.isArray(c))return;sh(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function ih(e){return e==="forward"?"$source":"$target"}function ah(e){return e==="forward"?"target":"source"}function sh(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var rr={identifySecondLevelActivities:Ao,identifyInitialActivities:Io,identifyParentsWithAndWithoutLinks:Co,identifyForbiddenActivities:ko};function Jr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function mi({linkType:e,lag:t,predecessorTime:r,activityCalendar:n,activity:i}){return e===V.FS&&t===0?yt({predecessorTime:r,activityCalendar:n,direction:"future",activity:i}):nr(r,e,n,i)}function So({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:D(r,i,e,n),ef:i}}function Do({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t),a=D(r,i,e,n);return{es:i,ef:a}}function nr(e,t,r,n){if(![V.FS,V.SS,V.FF].includes(t))return e;let a=[V.FS,V.SS].includes(t)?"future":"past";return yt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:n})}var gi=class{constructor(t,r,n,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.linkCandidates=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=Jr(t),n=this.activity.constraint_type;return n==="snet"?this.handleSNETConstraint(r):n==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let n=r.linkType,i=ce(n),a=r.linkLag,s=r.es,o=r.ef,c=null;if(i==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(i==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(i==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(i==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&(this.linkCandidates?.set(r.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let r=Do({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=So({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 n=mi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity);t>0&&(i=nr(i,"ss",this.activityCalendar,this.activity));let a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let n=mi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(a=nr(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:i}}calculateFSLink({lag:t,predecessorEf:r}){let n=r;t===0&&(n=yt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let n=D(this.activityCalendar,r,t,this.activity),i=D(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(i=nr(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},To=gi;var vi=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 n=ce(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let i=r.linkLag,a=r.ls,s=r.lf;if(n==="ss"){let o={lag:i,workTime:a,lsDataCalculation:-i,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(n==="ff"){let o={lag:i,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-i},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(n==="fs"){let o={lag:i,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-i},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(n==="sf"){let o={lag:i,workTime:s,lsDataCalculation:-i,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),n=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([n,r]):n}else{let r=this.getMinLfFromLinks(t);if(r===!1){let n=this.gantt.getSubtaskDates();return{ls:D(this.activityCalendar,n.end_date,-this.activity.duration,this.activity),lf:n.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i}){let a=null,s=null;if(t===0)return a=D(this.activityCalendar,r,i,this.activity),s=D(this.activityCalendar,a,n,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=D(this.activityCalendar,o,i,this.activity),s=D(this.activityCalendar,a,n,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=D(this.activityCalendar,l,i,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=D(this.activityCalendar,s,n,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=D(this.activityCalendar,c,i,this.activity),o=D(this.activityCalendar,s,n,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i}){let a=null,s=null,o=r;return s=D(this.activityCalendar,o,n,this.activity),a=D(this.activityCalendar,s,i,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=D(this.activityCalendar,r,n,this.activity),s=D(this.activityCalendar,o,i,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=D(this.activityCalendar,c,n,this.activity),s=D(this.activityCalendar,o,i,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,n)=>n.lf<r.lf?n:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:D(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=At(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),yt({dateBaseToCalculate:new Date(a),direction:n,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let n=r instanceof Date?r:new Date(r),a=t.getWorkHours(n)[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),At.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}},_o=vi;function Po(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s,linkCandidates:o}=e,c=t[r],l=oh(t),d=null;if(s==="forward"){let u=ch(c,n,i,a);d=new To(u,t,a,o),d=d.calculate()}else{let u=lh(c,n,i,a);d=new _o({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function oh(e){return{duration:e.duration,calendarId:e.calendar_id}}function ch(e,t,r,n){return e.length===0?[]:e.map(i=>{let a=n.getLink(i);if(!a)return console.warn(`Link not found: ${i}`),null;let s=Number(a[t]),o=r.get(s);return o?{linkId:String(a.id),es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function lh(e,t,r,n){return e.length===0?[]:e.map(i=>{let a=n.getLink(i);if(!a)return console.warn(`Link not found: ${i}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=n.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 Eo(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(dh(t.id,r))return null;let a=uh(t.id,n),s=fh(a,r);return s.length===0?null:ph(s,i)}function dh(e,t){return t.has(e)}function uh(e,t){let r=t.get(e);return r?r.childrens:[]}function fh(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function ph(e,t){if(t==="forward"){let r=bo(e,"es"),n=Ro(e,"ef");return{es:r,ef:n}}else{let r=bo(e,"ls"),n=Ro(e,"lf");return{ls:r,lf:n}}}function bo(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function Ro(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var Ai={parentWithLinks:Po,parentWithNoLinks:Eo};var Ii=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.linkCandidates=t.linkCandidates,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let n=[y.FNLT];if(this.shouldCalculateParentWithLinksBackward(n)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(n)){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),n=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}calculateAndStoreParentWithLinks(t){let r=Ai.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});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),n=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}handleParentWithNoLinks(){let t=Ai.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,n=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:i,maxEf:a}=n.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(n[0].es),maxEf:new Date(n[0].ef)});this.calculations.set(this.activity.id,{es:i,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,n=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:i,maxLf:a}=n.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(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(this.activity.id,{ls:i,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}},Lo=Ii;var Ci=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 n=this.processEachActivity(r),{activitiesByLevel:i}=n,a=this.getAllLevels(i),s=this.getDeepestLevel(a),o=this.createResult(r,n,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(lt.byFirstLevel).filter(lt.filterByParentType)}processEachActivity(t){let r=new Set,n=new Set,i=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,n,i)},t.id),{parentsIds:r,allTasks:n,activitiesByLevel:i}}initializeParent(t){let r=Number(t.id),n=!!t[this.linkProperty]?.length,i=t.$level;this.singleParents.set(r,{level:i,hasLink:n,childrens:[]})}processActivity(t,r,n,i){let a=Number(t.id),s=Number(t.parent);n.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,i)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let n=Number(t.id),i=t.$level,a=this.hasLink(t),s={level:i,hasLink:a,childrens:[]};r.add(n),this.singleParents.set(n,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let n=t.$level,i=Number(t.parent);r.has(n)||r.set(n,new Map);let a=r.get(n);a.has(i)||a.set(i,[]),a.get(i).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,n,i){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:i,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:n,canBeCalculated:!1}}},wo=Ci;var ki=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:n,isALinkedParent:i}=t;if(i)return;let a=n.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(lt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:n}=rr.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=n}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=rr.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new wo({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,n=new Set,i=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(n.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),i.has(c.$level)||i.set(c.$level,new Map);let d=i.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:n,activitiesByLevel:i,singleParents:a})})}identifySecondLevelActivities(){try{let t=rr.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}=rr.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:n,ef:i}=r;this.calculations.set(t.id,{es:n,ef:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:n,lf:i}=r;this.calculations.set(t.id,{ls:n,lf:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,n=new Set(this.calculations.keys()),i=new Map;return t.forEach(a=>{a&&i.set(a.id,a)}),i.forEach((a,s)=>{if(n.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=>i.has(l)||n.has(l)),r.set(s,o)}),{graph:r,activityMap:i,calculatedActivities:n}}topologicalSort(t,r){let n=new Set,i=new Set,a=[],s=o=>{if(i.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!n.has(o)&&!r.has(o)){i.add(o);let c=t.get(o)||[];for(let l of c)s(l);i.delete(o),n.add(o),a.push(o)}};for(let o of t.keys())!n.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let n=t,i=Number(n.progress);i==="0.00"&&(i=0);let a=this.gantt.getCalendar(n.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);if((r||this.direction)==="forward"){let o=n.start_date,c=n.end_date;return{es:o,ef:c}}else{if(i>=100)return{ls:At(n.start_date).clone(),lf:At(n.end_date).clone()};if(i===0)return this.calculateBackwardWhenZeroProgress(n,a);if(i<100&&i>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(n,a)}}catch(n){throw n}}calculateBackwardWhenZeroProgress(t,r){let n=At(t.start_date).clone(),i=At(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))i=this.projectDates.end_date,n=D(r,i,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(n=t.constraint_date,i=D(r,n,a,t)),l.includes(o)&&(i=t.constraint_date,n=D(r,i,-a,t))}return{ls:n,lf:i}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,n=null,i=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(i))n=Math.max(t.end_date,a);else if(i===y.MSO)n=t.end_date;else if(i===y.MFO||o.includes(i)){let c=Math.min(a,t.constraint_date);n=Math.max(c,t.end_date)}return{ls:r,lf:new Date(n)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(n=>Number(this.gantt.getTask(n).progress)===100).map(n=>this.gantt.getTask(n)).forEach(n=>{let i=n.type==="project";this.setDatesForActivityWithFullProgress(n),this.activitiesWaitingForCalculation.delete(n.id),i&&this.pendingParentsWithLinks.has(n.id)&&(this.parentCalculationFromChildren.add(n.id),this.calculationsOfParentThatImpactChildrens.set(n.id,{[this.direction==="forward"?"es":"ls"]:n.start_date,[this.direction==="forward"?"ef":"lf"]:n.end_date}),this.calculationOfParentsFromLinks.add(n.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new Lo({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,linkCandidates:this.linkCandidates,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Zt=ki;function hh(e,t,r){let n={es:null,ef:null};if(!e)return n;if([y.SNET,y.SNLT].includes(t)){let i=new Date(e.constraint_date);n.es=i,n.ef=D(r,i,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let i=new Date(e.constraint_date);n.es=D(r,i,-e.duration,e),n.ef=i}else if(t===y.MSO){let i=new Date(e.constraint_date);n.es=i,n.ef=D(r,i,e.duration,e)}else if(t===y.MFO){let i=new Date(e.constraint_date);n.es=D(r,i,-e.duration,e),n.ef=i}return n}var Xr=hh;var Si=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,this.linkCandidates=t.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,n=0,i,a=V.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===V.FS&&i===0?o=yt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[V.FF,V.SF].includes(a)?(l=D(s,o,n,this.referenceActivity),c=D(s,l,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=D(s,o,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=D(s,c,n,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,V.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,V.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,V.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,V.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,n){if(![V.FS,V.SS,V.FF].includes(r))return t;let a=[V.FS,V.SS].includes(r)?"future":"past";return yt({dateBaseToCalculate:t,activityCalendar:n,direction:a,activity:this.referenceActivity})}},Oo=Si;var ir=class extends Oo{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Zt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Link data not found",{cause:{linkId:n}});let a=this.calculateLink(i);return this.linkCandidates?.set(String(i.id),{targetId:String(this.referenceActivity.id),...a}),a}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let n=this.gantt.getCalendar(this.referenceActivity.calendar_id),i=this.parentsCalculations.get(r).es,a=D(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Jr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Di=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,n=new Set(t);for(let i of t){let a=this.gantt.getTask(i);a.type==="project"?this.handleProjectActivity(i,a,r,n):this.handleNonProjectActivity(i,a,r,n)}return{activitiesThatCanBeCalculated:r,pendingActivities:n}}handleProjectActivity(t,r,n,i){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))&&(n.add(t),i.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(n.add(t),i.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(n.add(t),i.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,n=t.constraint_type;return(this.direction==="forward"?n==="fnlt"||n==="snlt":n==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,n,i){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){n.add(t),i.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){n.add(t),i.delete(t);return}l&&(n.add(t),i.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=i[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);i&&r.push(Number(i[this.linkDirection]))}return r}},Zr=Di;var Ti=(e,t)=>()=>t()===e;var _i=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var yh=16,le=async e=>performance.now()-e>yh?(await Q(),performance.now()):e;var ar=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:n,isCalculated:i,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await le(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await le(c),r([u])}for(let u of l){if(!s())return;n(u)&&d.add(u),a(u),i(u)&&d.delete(u)}o=d}};var Pi=class extends Zt{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.linkCandidates=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 Zr({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 ar({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(n.type==="project")return this.doCalculationForParentType(n);if(!n)throw new Error("Error trying to get activity",{cause:{activityId:r}});let i=n.$target,a=n.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(n.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);let l=Number(n.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(n);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(n),f=new ir({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new ir({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=Xr(n,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),n.progress===0)d=p.es,u=p.ef;else{let h=n.end_date;a===y.MFO&&(h=Math.max(p.ef,n.end_date)),d=n.start_date,u=h}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,n="greater"){if(n==="greater")return r.ef>t.ef?r:t;if(n==="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,n){let i=[y.SNET,y.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,n,i);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r);if(!n)throw new Error("Error trying to get link",{cause:{linkId:r}});let i=n.source,a=n.target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Fo=Pi;var bi=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,n=0,i,a=V.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&&i===0){let d=D(s,o,r,this.activity),u=D(s,d,n,this.activity);return{ls:d,lf:u}}let l={lag:i,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:n,isMilestone:c};if(a===V.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===V.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===V.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===V.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let n=this.getValueForSS(t,r),i=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(n,i,a,s,V.SS)}calculateFF(t,r){let n=this.getForwardOrBackwardCalculations(Number(t.target)),i=r===y.ALAP?"ef":"lf",a=n[i],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,V.FF)}calculateFS(t,r){let n="ls";n=r===y.ALAP?"es":"ls";let i=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(i[n],a,o,s,V.FS)}calculateSF(t,r=!1){let n=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,i=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(n,i,a,s,V.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,n){let i=At(r).clone();return D(t,new Date(i),n,this.activity)}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=At(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),yt({dateBaseToCalculate:new Date(a),direction:n,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let n=r instanceof Date?r:new Date(r),a=t.getWorkHours(n)[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),At.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,n,"past");return o=D(n,d,a,this.activity),o=this.getLastWorkingHour(o,n,"past"),c=D(n,o,i,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,n)),o=D(n,l,a,this.activity),c=D(n,o,i,this.activity),s||(o=this.getLastWorkingHour(o,n,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=D(n,r,a,this.activity),o=D(n,s,i,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,n,"past")),s=D(n,c,a,this.activity),o=D(n,s,i,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=D(n,r,i,this.activity),o=D(n,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,n,"future")),c=D(n,l,i,this.activity),o=D(n,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=D(n,r,i),s=D(n,o,a,this.activity),{ls:o,lf:s}):(o=D(n,r,i,this.activity),s=D(n,o,a,this.activity),{ls:o,lf:s})}},xo=bi;var Ri=class extends xo{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 Zt(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),n=!1;r&&(n=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let i=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(i.length!==0){let s=this.getMinLfFromLinks(i);if(i.push(this.calculateTheLsAndLfForTheActivity()),n){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));i.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(i),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(n){i.push(this.calculateTheLsAndLfForTheActivity());let o=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=D(this.gantt.getCalendar(this.activity.calendar_id),o,-this.activity.duration,this.activity);i.push({ls:c,lf:o});let l=this.getMinDateFromLinks(i);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,n=this.gantt.getCalendar(this.activity.calendar_id);if(!n)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let i=t?t.lf:this.projectDates.end_date;if(!i)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:D(n,i,-r,this.activity),lf:i}}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 n=this.getSpecialCalculationParamForConstraintLink(),i=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,n),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,i)}[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((n,i)=>i.lf<n.lf?i:n):t.reduce((r,n)=>n.ls<r.ls?n:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,n)=>n.lf<r.lf?n:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let n=Math.min(t.lf,this.projectDates.end_date),i=this.activity.end_date,a=this.activity.constraint_date;if(r===y.ASAP)return new Date(Math.max(n,i));if(r===y.FNET||r===y.FNLT){let s=Math.min(n,a);return new Date(Math.max(n,s))}if(r===y.ALAP)return new Date(Math.min(n,i))}},No=Ri;function mh(e,t,r){let n={ls:null,lf:null};return r===y.MSO&&(n.ls=t.constraint_date,n.lf=D(e,n.ls,t.duration,t)),r===y.MFO&&(n.lf=t.constraint_date,n.ls=D(e,n.lf,-t.duration,t)),n}var Mo=mh;var Ei=class extends Zt{constructor(t,r,n){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=n,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 Zr({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 ar({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),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,i=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=i.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(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(!n)throw new Error("Activity not found",{cause:{activityId:r}});let i=n.$source,a=n.constraint_type||y.ASAP,s=Number(n.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(n.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(n.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(n,this.direction);this.setCalculations(n,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(n)}if(n.type==="project")return this.doCalculationForParentType(n);if(s===100){this.setDatesForActivityWithFullProgress(n);return}if(this.allLinkedActivitiesHasProgress(i,n)){this.setWhenAllLinkedActivitiesHasProgress(n);return}if(s>0&&s<100&&(a===y.MSO||a===y.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(n,a);return}if(a===y.MSO||a===y.MFO){this.recalculateInBaseRestriction(n,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(i,n,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===y.SNLT||a===y.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(n.id,{ls:o,lf:c},a)),this.setCalculations(n,o,c),this.minFromLinks.set(n.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,n){let i=this.forwardConstraintsMap.get(t);if(!i){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);i=Xr(a,n,s)}return r.lf<i.ef?r:{ls:i.es,lf:i.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=this.gantt.getTask(i.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:n,lf:i}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){n=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(i=new Date(Math.min(i,a.lf)))}this.setCalculations(t,n,i)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===y.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===y.MFO){let n=Math.min(t.constraint_date,this.projectDates.end_date),i=new Date(Math.max(n,t.end_date));this.setCalculations(t,t.start_date,i);return}}setCalculations(t,r,n){this.calculations.set(t.id,{ls:r,lf:n,text:t.text})}calculateLfandLsFromLinks(t,r,n,i,a){return new No({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:n,parentsWithFullProgress:i,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let n=this.gantt.getCalendar(t.calendar_id);if(!n)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let i=Mo(n,t,r);this.constraintMap.set(t,i),this.setCalculations(t,i.ls,i.lf)}catch(n){throw new Error(n.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r).source,i=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),n=this.calculationsOfParentThatImpactChildrens.get(r),i=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,n.lf)),i=t.start_date}else a=n.lf,i=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([y.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=D(this.gantt.getCalendar(t.calendar_id),l.lf,-t.duration,t),u=t.constraint_date??d;i=new Date(Math.min(u.getTime(),d.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=t.constraint_date??l.lf;i=new Date(Math.min(d.getTime(),l.lf.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(i=t.constraint_date,a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,i=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:i,lf:a}];o.push({ls:D(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,n)=>n.lf<r.lf?n:r):!1}},Wo=Ei;function Bo(){return null}var Uo=({forward:e,backward:t,id:r,activity:n,gantt:i,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:n,gantt:i},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:n,projectDates:a,gantt:i}});var Li=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),n=this.getMinValue(t,r),i=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(n,i)/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 n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,n)/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),n=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let i=0;return this.activity.constraint_type===y.SNLT?i=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):i=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),n=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let i=0;return this.activity.constraint_type===y.MSO?i=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):i=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(i,n)/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)})}},jo=Li;var wi=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(n=>{let{LINK:i,LINK_TYPE:a}=this.getLinkData(n),s=this.gantt.getTask(i.target);if(!s)return{linkId:i.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(i.lag),f=Math.max(0,u);return this.linksFreeFloatObject[i.id]=f,{linkId:i.id,freeFloat:f,hasProgress:o}}).filter(n=>n.freeFloat!==null&&n.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=y.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),n=this.calculateFreeFloatForEndOfProject(t),i=0;return[y.SNLT,y.FNLT].includes(t)?i=this.doCalculationForSnltFnlt(t,n,r):i=this.doGeneralCalculation(n,r),Math.max(0,i)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=y.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,n){let i=n.constraint_type===y.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:i,sucessorId:n.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,n){let i=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(n,r,i)}calculateFreeFloatForEndOfProject(t){let r=t===y.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.ALAP?r?.lf:r?.ef))}calculateFreeFloatOfRestriction(t){let r=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===y.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},n=ce(r.type);return{LINK:r,LINK_TYPE:n}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:n,predecessorId:i}){let a=(r?this.backwardMap:this.forwardMap).get(n),s=(t===y.ALAP?this.backwardMap:this.forwardMap).get(i),o=t===y.ALAP?s?.ls:s?.es,c=t===y.ALAP?s?.lf:s?.ef;return{fs:{sucessor:a?.ls??a?.es,predecessor:c},ss:{sucessor:a?.ls??a?.es,predecessor:o},ff:{sucessor:a?.lf??a?.ef,predecessor:c},sf:{sucessor:a?.lf??a?.ef,predecessor:o}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,n=this.forwardMap.get(this.activity.id),i=t===y.MSO?n?.es:n?.ef,a=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(a))}getMinValue(...t){let r=t.filter(n=>n!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){if(!(t instanceof Date)||!(r instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime()))return Number.NaN;let n=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(n))return this.durationCache.get(n);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(n,a),a}parseHoursToDays(t){return t==null?0:t/this.gantt.config.hoursPerDay}getMinFloat(t){if(!t?.length)return null;let r=t.filter(n=>!n.hasProgress).map(n=>n.freeFloat);return r.length===0?null:Math.min(...r)}},Ho=wi;var Vo=e=>({totalFloat:new jo(e.totalFloat).getTotalFloat(),freeFloat:new Ho(e.freeFloat).getFreeFloat()});var Oi=async({activityIds:e,forward:t,backward:r,gantt:n,projectDates:i,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=n.getTask(l);if(!d)continue;let u=Uo({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=Vo(u);o.set(l,f),c.set(l,p),s=await le(s)}return{totalFloatMap:o,freeFloatMap:c}};var Fi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.linkResidualHours=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let n=++this.currentCalculationId,i=Ti(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||Bo(),_i(this.gantt))return!1;let o=new Fo(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new Wo(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(o.linkCandidates,c,a);if(!u||!a())return!1;this.linkResidualHours=u;let{totalFloatMap:f,freeFloatMap:p}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=f,this.freeFloat=p,this.gantt.refreshData(),!0):!1}catch(s){throw this.forwardPathCalculations?.size,s}}async calculateLinkResidualHours(t,r,n=()=>!0){let i=new Map,a=performance.now();for(let[s,o]of t){if(a=await le(a),!n())return null;let c=Number(o.targetId),l=this.gantt.getTask(c),d=r.get(c),u=o.ef,f=d?.ef,p=l&&this.gantt.getCalendar(l.calendar_id);if(!p||!(u instanceof Date)||!(f instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(f.getTime())){i.set(s,null);continue}let h=u.getTime(),I=f.getTime()>=h?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});i.set(s,Number.isFinite(I)?Object.is(I,-0)?0:I:null)}return i}async calculateFloatsAsync(t,r,n){try{let i=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await Oi({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},Yo=Fi;var gh=e=>e==="fnet"||e==="fnlt"||e==="mfo",vh=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Ah(e,t){let r=e.constraintDate;if(!r||!gh(e.constraintType))return r;let n=vh(r);if(r.getTime()!==n.getTime())return r;let i=t.getClosestWorkTime({date:n,dir:"future",task:e});return i.getUTCFullYear()===r.getUTCFullYear()&&i.getUTCMonth()===r.getUTCMonth()&&i.getUTCDate()===r.getUTCDate()?zn(e,t):r}function Ih(e){let t=new Map,r=new Map,n=new Map;return{calculateEndDate:({start_date:i,duration:a})=>{let s=`${i.getTime()}|${a}`,o=t.get(s);if(o!==void 0)return new Date(o);let c=e.calculateEndDate(i,a);return t.set(s,c.getTime()),c},calculateDuration:({start_date:i,end_date:a})=>{let s=`${i.getTime()}|${a.getTime()}`,o=r.get(s);if(o!==void 0)return o;let c=e.calculateDuration(i,a);return r.set(s,c),c},getWorkHours:i=>e.getWorkHours(i),$gantt:{getClosestWorkTime:({date:i,dir:a,unit:s})=>{let o=s??"hour",c=`${i.getTime()}|${a}|${o}`,l=n.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:i,direction:a,unit:o});return n.set(c,d.getTime()),d}}}}function Ch(e){let t=new Map;e.forEachActivity((i,a)=>t.set(String(a),i));let r=new Map,n=(i,a)=>{let s=r.get(i);if(s!=null)return s;let c=t.get(i)?.parentId??null,l=0;return c!==null&&!a.has(i)&&(a.add(i),l=n(String(c),a)+1),r.set(i,l),l};for(let i of t.keys())n(i,new Set);return r}function kh(e){let t=new Set;e.forEachActivity((o,c)=>{t.add(String(c)),o.parentId!==null&&t.add(String(o.parentId))});let r=new Map;for(let o of t){let c=Number(o);Number.isSafeInteger(c)&&c!==0&&r.set(c,(r.get(c)??0)+1)}let n=new Map,i=new Map;for(let o of t){let c=Number(o);Number.isSafeInteger(c)&&c!==0&&r.get(c)===1&&(n.set(o,c),i.set(c,o))}let a=1,s=o=>{let c=String(o),l=n.get(c);if(l!==void 0)return l;for(;i.has(a);)a+=1;return n.set(c,a),i.set(a,c),a++};for(let o of t)s(o);return{toLegacy:s,toCanonical:o=>typeof o=="number"?i.get(o)??null:n.has(String(o))?String(o):null}}function Sh(e,t){let r=Ch(e),n=new Map;return e.forEachActivity((i,a)=>{let s=String(a);n.set(s,{id:t.toLegacy(s),parent:i.parentId===null?0:t.toLegacy(i.parentId),$level:r.get(s)??0,$source:e.getOutgoingLinkIds(s),$target:e.getIncomingLinkIds(s),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:Ah(i,e)})}),n}function Dh(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=[],n=new Set,i=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)i.push(s[o])};for(a(t.get(0));i.length>0;){let s=i.pop();n.has(s)||(n.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())n.has(s)||r.push(s);return r}function Th(e){let t=null,r=null;return e.forEachActivity(n=>{if(n.startDate){let i=n.startDate.getTime();t=t==null?i:Math.min(t,i)}if(n.endDate){let i=n.endDate.getTime();r=r==null?i:Math.max(r,i)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function Ko(e,t){let r=new Map,n=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=Ih(f);return r.set(d,p),p},i=Th(e);await Q();let a=kh(e),s=Sh(e,a);await Q();let o=[...s.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await Q();let c=Dh(s);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=a.toCanonical(l);return d===null?null:s.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:a.toLegacy(d.source),target:a.toLegacy(d.target),lag:d.lag}:null},getCalendar:n,getChildren:l=>{let d=a.toCanonical(l);return d===null?[]:e.getChildren(d).map(a.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>o,getSubtaskDates:()=>i,getCanonicalActivityId:a.toCanonical,refreshData:()=>{}}}var Ni=1e3,_h=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,Ph=(e,t)=>typeof e!="number"||e<0?null:xi(e,t);function bh(e){let t=Ph(e.freeFloatDays,e.hoursPerDay),r=_h(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function Rh(e,t){let r=new Map,n=0;for(let i of e.values())for(let a in i.linksFreeFloat)if(Object.hasOwn(i.linksFreeFloat,a)){if(++n>=Ni&&(n=0,await Q(),!t()))return null;r.set(String(a),i.linksFreeFloat[a])}return t()?r:null}async function Eh(e,t,r,n,i){let a=new Map,s=0;for(let o of t.forward?.keys()??[]){if(++s>=Ni&&(s=0,await Q(),!i()))return null;let c=n(o);if(c===null)continue;let l=e.getActivity(c);l&&a.set(String(c),wh(o,Number(l.progress??0),t,r))}return i()?a:null}async function Lh(e,t,r,n,i,a){let s=new Map,o=0;for(let c of e.getAllLinks()){if(++o>=Ni&&(o=0,await Q(),!a()))return null;s.set(String(c.id),bh({freeFloatDays:t.get(String(c.id)),residualHours:r.get(String(c.id)),hoursPerDay:i,sourceIsCritical:n.get(c.source)?.isCritical===!0,targetIsCritical:n.get(c.target)?.isCritical===!0,targetProgress:e.getActivity(c.target)?.progress}))}return a()?s:null}var xi=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=e*t;return Number.isFinite(r)?Object.is(r,-0)?0:r:null};function wh(e,t,r,n){let i=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},a=r.forward?.get(e),s=r.backward?.get(e),o=xi(r.totalFloat.get(e),n);return{criticalPath:{earlyStart:i(a?.es),earlyFinish:i(a?.ef),lateStart:i(s?.ls),lateFinish:i(s?.lf),totalSlackHours:o},isCritical:t<100&&o!==null&&o<=0,freeSlackHours:xi(r.freeFloat.get(e)?.activityFreeFloat,n)}}var Qr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function Mi(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&Qr(i.earlyStart,a.earlyStart)&&Qr(i.earlyFinish,a.earlyFinish)&&Qr(i.lateStart,a.lateStart)&&Qr(i.lateFinish,a.lateFinish)&&Object.is(i.totalSlackHours,a.totalSlackHours)&&Object.is(n.isCritical,r.isCritical)&&Object.is(n.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function Wi(e,t,r){let n=e.getLink(t);!n||Object.is(n.freeSlackHours,r.freeSlackHours)&&Object.is(n.isCritical,r.isCritical)||(e.setLinkField(t,"freeSlackHours",r.freeSlackHours),e.setLinkField(t,"isCritical",r.isCritical))}async function Bi(e,t,r=()=>!0){if(!r())return null;let n=await Ko(e,t);if(!r())return null;let i=new Yo(n);if(!await i.calculate(n,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let s={forward:i.forwardPathCalculations,backward:i.backwardPathCalculations,totalFloat:i.totalFloat,freeFloat:i.freeFloat},o=await Eh(e,s,t,n.getCanonicalActivityId,r);if(!o)return null;let c=await Rh(s.freeFloat,r);if(!c)return null;let l=await Lh(e,c,i.linkResidualHours,o,t,r);return l?{activities:o,links:l}:null}async function Go(e,t,r=()=>!0){let n=await Bi(e,t,r);if(!n||!r())return!1;for(let[i,a]of n.activities){if(!r())return!1;Mi(e,i,a)}for(let[i,a]of n.links){if(!r())return!1;Wi(e,i,a)}return!0}function Fe(e){let t=[],r=[];e.forEachActivity((i,a)=>{i.parentId===null&&t.push(String(a))});let n=i=>{let a=e.getActivity(String(i));if(!a)return 0;let s=[...e.getChildren(String(i))],o;if(s.length===0){let c=ut(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=n(String(l));o=c}return e.setActivityField(String(i),E.REAL_COST,o),r.push(String(i)),o};for(let i of t)n(i);return r}var $o=new Set;var zo=new Set(["activity-outdent","activity-indent"]);var sr=new Set([P.TEXT,P.DESCRIPTION,P.COST,P.USED_COST,P.CUSTOM_ID,P.RESPONSABLES,P.SUBCONTRACT_ID,P.TAGS]),Oh=new Set(["activity-clipboard-clear","activity-copy","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"]),Fh=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Jo(e){return!Fh.has(e.kind)}var xh=new Set;function Nh(e){return e.kind==="inline-edit"?sr.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>sr.has(t.column)):!1}function Ui(e,t){return!(Oh.has(e.kind)||t.has(e.kind)||Nh(e))}function ji(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Ui(e,xh)}function de(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Ui(e,$o)}function Xo(e){return Ui(e,zo)}function Hi(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 Mh(e){return Xo(e)&&Hi(e)}var qo=new Set([P.PROGRESS,P.HH_WORK_TIME,P.DURATION,P.COST,P.USED_COST,P.REAL_COST]);function Wh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?qo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>qo.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 Zo(e,t,r){let n=new Set;t.ran&&n.add(at.AUTOSCHEDULE),n.add(at.PARENT_BOUNDS),Wh(e)&&n.add(at.PARENT_PROGRESS),Hi(e)&&n.add(at.REAL_WORK);let i=!r.skipAutoSchedule;return i&&Xo(e)&&n.add(at.EXPECTED_PROGRESS),i&&Mh(e)&&n.add(at.REAL_COST),i&&de(e)&&!r.skipCriticalPath&&n.add(at.CRITICAL_PATH),n}async function Y(e,t){let r=Uh(e.adapter),n=Bh(t,r);n.has(at.AUTOSCHEDULE)&&await Gh(e.adapter,t);let i=n.has(at.AUTOSCHEDULE)?await Vh(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):Kh();return await $h(e.adapter,t,i.scheduledIds,n,r),await qh(e,n,t.now),i}function Bh(e,t){let r=e.autoscheduleFrom!==null,n=!e.options.skipAutoSchedule&&r,i=new Set(Zo(e.action,{requested:r,ran:n},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&i.add(at.PARENT_PROGRESS),i}function Uh(e){let t=new Set,r=new Set,n=e.peekWriteCapture();if(!n)return{affectedParents:t,dirtySeeds:r};let i=a=>{if(a===null||L(a))return;let s=String(a);t.add(s);let o=e.getChildren(s)[0];o!==void 0&&r.add(o)};return jh(e,n.ops,i),Hh(e,n.before,r,i),{affectedParents:t,dirtySeeds:r}}function jh(e,t,r){for(let n of t)if(n.kind==="insert"){let i=e.getActivity(n.activityId);i&&r(i.parentId)}else n.kind==="remove"&&r(n.before.parentId)}function Hh(e,t,r,n){for(let[i,a]of t){let s=e.getActivity(i);if(!s)continue;let o=!Object.is(a.progress,s.progress),c=!Object.is(a.ponderator,s.ponderator),l=!Object.is(a.parentId,s.parentId);(o||c)&&(n(s.parentId),r.add(String(i))),l&&(n(a.parentId),n(s.parentId),r.add(String(i)))}}async function Vh(e,t,r=!1){let n=t==="roots"?{}:{triggerId:t};r&&(n.preventSummaryTargetPullback=!0);let i=await e.scheduler.schedule(n),a=Yh(e.adapter,i.updatedIds);return Ge(e.adapter,i),a}function Yh(e,t){let r=[];for(let n of t){let i=String(n);r.push(i);let a=e.getActivity(i);a&&e.noteScheduledBefore(i,a)}return{scheduledIds:r}}function Kh(){return{scheduledIds:[]}}async function Gh(e,t){let r=t.collectDirty?t.collectDirty([]):fi(t.recomputeParentsFrom,[]);r.size!==0&&await _e(e,r,!1)}async function $h(e,t,r,n,i){n.has(at.PARENT_PROGRESS)&&zh(e,i.affectedParents);let a=t.collectDirty?t.collectDirty(r):fi(t.recomputeParentsFrom,r);for(let s of i.dirtySeeds)a.add(s);await _e(e,a,n.has(at.PARENT_PROGRESS),{recomputeRealWork:n.has(at.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function zh(e,t){for(let r of t){if(e.hasChildren(r))continue;let n=e.getProgressFallback(r);n!==null&&(e.setActivityField(r,"progress",n),e.setProgressFallback(r,null))}}async function qh(e,t,r){t.has(at.EXPECTED_PROGRESS)&&r!==null&&(Jh(e.adapter)&&Oe(e.adapter,r,e.defaultBaseCalendarId??null),oe(e.adapter,r),Wt(e.adapter,e.sector.statusCriteria)),t.has(at.REAL_COST)&&Fe(e.adapter),t.has(at.CRITICAL_PATH)&&await Go(e.adapter,e.sector.hoursPerDay)}function Jh(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var Xh=new Set([P.CONSTRAINT_TYPE,P.CONSTRAINT_DATE]),Zh=new Set(["mso","mfo"]);function tn(e){return Xh.has(e)}function en(e){return e===P.CONSTRAINT_DATE}function rn(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||$t.has(a)||Zh.has(a))return!1;let s=Vi(i.startDate),o=Vi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Qh(t,a,String(i.calendarId??""),n),l=Vi(i.constraintDate);return ty(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Qh(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?xt(e,i,t):e}function Vi(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 ty(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function nn(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await Y(e,Qo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await Y(e,Qo(t));i=ry(i,s.scheduledIds)}return de(t.action)&&await Y(e,ey(t)),{scheduledIds:i}}function Qo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function ey(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function ry(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Yi(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(ve({pendingRequestIds:s})&&t.getActivity(i)==null)for(let o of s)n.push({kind:"sir-auto-reject",activityId:i,sirId:o,reason:"activity_deleted"})}return n}function ft(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag),freeSlackHours:typeof e.freeSlackHours=="number"&&Number.isFinite(e.freeSlackHours)?e.freeSlackHours:null,isCritical:e.isCritical===!0};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}async function W(e,t){let r=sy(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let f=cy(i);oy(e,i,f,n,r)}let a=t.sirDetection,s=a==="before-diff"?Yi(n,e,r):[],o=ay(t.correlativeShifts,r),c=await Kr(e,n,r,o),l=a==="after-diff"?Yi(n,e,r):s,d=t.warnings??[],u=iy(t.links??[],i?ny(e,i):[]);return{source:t.source,activities:c,links:u,calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}function ny(e,t){let r=[];for(let n of t.ops){if(n.kind!=="link-field")continue;let i=e.getLink(n.linkId);if(!i)continue;let a={};for(let s of["freeSlackHours","isCritical"])Object.is(n.before[s],i[s])||(a[s]={before:n.before[s],after:i[s]});Object.keys(a).length!==0&&r.push({id:n.linkId,kind:"updated",fields:a,after:ft(i)})}return r}function iy(e,t){let r=[],n=new Map;for(let i of e){let a=n.get(i.id);if(a===void 0){n.set(i.id,r.length),r.push(i);continue}let s=r[a];if((s.kind==="updated"||s.kind==="created")&&i.kind==="updated"){r[a]={...s,fields:{...s.fields,...i.fields},after:i.after};continue}r[a]=i}for(let i of t){let a=n.get(i.id);if(a===void 0){n.set(i.id,r.length),r.push(i);continue}let s=r[a];if(s.kind==="deleted")continue;let o=s.kind==="created"?Object.fromEntries(Object.entries(i.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):i.fields;r[a]={...s,fields:{...s.fields,...o},after:i.after}}return r}function ay(e,t){if(!e||e.length===0)return;let r=new Map;for(let n of e)r.set(n.activityId,n.before),t.add(n.activityId);return r}function sy(e,t){let r=new Set;for(let n of t.touchedIds)r.add(n);for(let n of t.scheduledIds)r.add(n);if(t.includeAllIds)for(let n of e.getAllIds())r.add(n);return r}function oy(e,t,r,n,i){for(let a of t.dirty){if(r.has(a)||n.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(ui(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function cy(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function xe(e,t,r){let n=[];for(let{op:i,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(i.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;let u=t.get(a);if(u){let f={};String(u.source)!==String(d.source)&&(f.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(f.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(f.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(f.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(f).length>0&&n.push({id:String(a),kind:"updated",fields:f,after:ft(d)});continue}n.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:ft(d)});continue}if(i.kind==="delete"){if(r.getLink(i.linkId))continue;let d=t.get(i.linkId);n.push({id:String(i.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(i.linkId),c=r.getLink(i.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)}),n.push({id:String(i.linkId),kind:"updated",fields:l,after:ft(c)})}return n}function Ne(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let n of e.getIncomingLinkIds(t)){let i=e.getLink(n);i&&r.set(String(i.id),Number(i.lag))}return r}function Me(e,t,r){let n=[];if(!t.getActivity(r))return n;for(let i of t.getIncomingLinkIds(r)){let a=t.getLink(i);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||n.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:ft(a)})}return n}function an(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function tc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=qt(e.column);if(!o)return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};e.column===P.DURATION&&a.invalidateExpandedLinksCache();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??C.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??C.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,i);if(!f.valid)return{ok:!1,reason:f.reason??C.INVALID,alertKey:f.notification?.messageKey};if(e.column===P.CUSTOM_ID&&d.value!==null){let A=n.getActivity(e.activityId),T=A?A.customId:null,x=typeof T=="string"?T:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:C.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),h=Jt(e.activityId,p),g=await q(n,h),I=Ne(n,String(e.activityId)),_=c.constraintDate;Xt(n,e.activityId,p),Yt(e.activityId,p.postProcessors??[],n,g.get(String(e.activityId))??null);let v=Me(I,n,String(e.activityId));if(e.column===P.CUSTOM_ID){let A=g.get(String(e.activityId)),T=A?A.customId:null,x=typeof T=="string"?T:null,F=typeof d.value=="string"?d.value:null;x!==F&&r.customIdTracker.trackCustomIdChange(x,F)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:A=>Gr(e.activityId,h,A),now:r.now,options:t}),m=tn(e.column),{scheduledIds:b}=await(m?nn({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:en(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:_}],revert:(A,T)=>rn(A,T,n,i.calendars)}):Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),w=(p.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}})),S=Le(e.activityId,p.constraintWarning);return{ok:!0,changes:await W(n,{source:e,beforeSnap:g,touchedIds:h,scheduledIds:b,sirDetection:"before-diff",links:v,trackingEvents:w,...S?{warnings:[S]}:{},hoursPerDay:s.hoursPerDay})}}function ly(e,t){let r=new Set,n=new Map;for(let i of e){if(i.kind==="create"){r.add(String(i.source)),r.add(String(i.target));continue}let a=t.getLink(i.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),n.set(i.linkId,{...a}))}return{activityIds:r,links:n}}function dy(e,t,r,n){return e.map((i,a)=>{let s=i.kind==="create"?n?.get(a):void 0,o=Ht(i,{port:t,newLinkId:s?()=>s:r.next});return{op:i,finalLinkId:o.applied?o.linkId:null,rejected:o.applied?null:o.rejected??"link_op_rejected"}})}function uy(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function ec(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(B).some(a=>a===n))return{ok:!1,reason:C.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:C.INVALID_LINK_LAG}}return Ki([gy(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function rc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>hy(s,n)),a=fy(e.operations);return Ki(i,e,t,r,a)}function fy(e){let t=new Map;return e.forEach((r,n)=>{r.kind==="create"&&r.linkId&&t.set(n,r.linkId)}),t.size>0?t:void 0}function py(e,t){if(e===void 0)return;let r=new Map,n=new Set,i=()=>{let a=t.linkIdGen.next();for(;t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||n.has(String(a));)a=t.linkIdGen.next();return a};for(let[a,s]of e){let o=t.adapter.getLink(s)!==null||t.isLinkIdReserved(String(s))||n.has(String(s)),c=o?i():s;o||t.linkIdGen.bump(s),n.add(String(c)),r.set(a,c)}return r}function hy(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Ki(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=ly(e,a),u=await q(a,l),f=dy(e,a,c,py(i,n));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=yy(f,d,a),{scheduledIds:h}=await Y({adapter:a,scheduler:s,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:n.now,options:r}),g=xe(f,d,a);return{ok:!0,linkVerdicts:f.map((I,_)=>I.rejected===null?{operationIndex:_,kind:I.op.kind,ok:!0,linkId:String(I.finalLinkId)}:{operationIndex:_,kind:I.op.kind,ok:!1,reason:I.rejected}),__beforeLinks:uy(d),changes:await W(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:h,links:g,hoursPerDay:o.hoursPerDay})}}function yy(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=my(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function my(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 gy(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function nc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:C.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=e.column===P.CUSTOM_PREDECESSORS,{specs:o}=Lr(e.newValue),c=o.map(h=>({...h,lag:vt(xr(h.lag),i.hoursPerDay)})),l=new Map;n.forEachActivity(h=>{h.correlativeId!=null&&l.set(String(h.correlativeId),h.id)});let d=h=>l.get(h)??null,u=s?n.getIncomingLinkIds(e.activityId):n.getOutgoingLinkIds(e.activityId),f=[];for(let h of u){let g=n.getLink(h);g&&f.push(g)}let p=s?Or({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):Fr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Ki(p.operations,e,t,r)}var It={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 ot(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(sc);let r=[];ic(r,t);let n=[],i=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==i){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;n.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),vy(a,i)}i+=1;let s=Ve(String(a.id),e);s.sort(sc),ic(r,s)}return n}function ic(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ac(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Kn}var sc=(e,t)=>ac(e)-ac(t);function vy(e,t){e.correlativeId=t}function Gi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:n,realWorkHours:i}=lc(r,t);t.setActivityField(r,E.WORK_HOURS,n),t.setActivityField(r,E.REAL_WORK_HOURS,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function oc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Gi(n,t)}function cc(e,t,r){for(let n of e){if(r.hasChildren(n))continue;let i=r.getActivity(n);i&&r.setActivityField(n,E.REAL_WORK_HOURS,dt(or(i,E.WORK_HOURS),or(i,E.PROGRESS)))}for(let n of t)r.setActivityField(n,E.REAL_WORK_HOURS,lc(n,r).realWorkHours)}function lc(e,t){let r=0,n=0;for(let i of t.getChildren(e)){let a=t.getActivity(i);if(!a)continue;let s=or(a,E.WORK_HOURS);r+=s,n+=Ay(i,a,s,t)}return{workHours:r,realWorkHours:n}}function or(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ay(e,t,r,n){return n.hasChildren(e)?or(t,E.REAL_WORK_HOURS):dt(r,or(t,E.PROGRESS))}function $i(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=Iy(c,E.USED_COST))}t.setActivityField(r,E.USED_COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function dc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||$i(n,t)}function Iy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function zi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=Cy(c,E.COST))}t.setActivityField(r,E.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function uc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||zi(n,t)}function Cy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var sn=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}),fc="New Master Plan",pc="New Activity";var ky=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],on=new Set(ky);function Sy(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"||!on.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function hc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=Sy(e.activityOverrides??{}),i=e.numTasksInGantt===0?fc:pc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=Dy(r,e.fallbackStartDate,n.startDate),l={...sn,...n,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=n.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:Z.FUTURE,task:l});if(!n.startDate&&r&&Ot(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let h=new Date(d);h.setUTCHours(0,0,0,0),h.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:Z.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:Et({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function Dy(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Ty(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,n=e.endDate;return!(r instanceof Date)||!(n instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(n),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 We(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&jt(t.type):_y(t),n=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:n.some(s=>String(s)===String(e.newChildId))?[...n]:[...n,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=Zn,(e.promotionSource??"create")==="create"&&(a.constraintType=$.ASAP,a.constraintDate=null)),{parentId:e.parentId,fields:a,promotionSnapshot:Ty(t)}}function _y(e){return jt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function cn(e,t,r,n){let i=t,a=i==="0",s=qi(e,i);if(n!==void 0){let c=s.find(l=>l.id===n);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 ue=Number.MAX_SAFE_INTEGER,yc=Number.MAX_SAFE_INTEGER-1;function ct(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:ue}function qi(e,t){return Ve(t,e)}function mc(e,t,r){let n=e,i=Qt(e,r);for(;i!=null&&t.has(i);)n=i,i=Qt(i,r);return n}function ln(e,t,r){let n=new Set([e]),i=Ut(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=Ut(r.getActivity(i)?.parentId)}return!1}function Qt(e,t){let r=t.getActivity(e);if(!r)return null;let n=Ut(r.parentId),i=gt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function gc(e,t,r,n){let i=gt(t,e).filter(c=>String(c)!==String(n)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(i.length===0)return 0;let a=i.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}var Py=new Set([...[...on].filter(e=>e!=="durationHours"),"durationDays"]);function dn(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:C.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!Py.has(a))return{ok:!1,reason:C.INVALID_VALUE};let{durationDays:n,...i}=e;return n!==void 0&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:C.INVALID_VALUE}:{ok:!0,value:{...i,...n===0&&(i.type===void 0||i.type==="task")?{type:"milestone"}:{},...n===void 0?{}:{durationHours:ne(n,t)}}}}async function cr(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=by(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Ey(e.activityId,n,o,t.isActivityIdReserved),h=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Ny(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:h,activityOverrides:e.overrides??{}},_=hc(g,{getActivity:A=>n.getActivity(A),calculateEndDate:A=>n.calculateEndDate(A),getClosestWorkTime:A=>n.getClosestWorkTime(A)}).newTask;_.realWorkHours=dt(_.workHours,_.progress),wy(_,e,t,u,d,r);let v=r.insertionCorrelativeId??cn(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);_.correlativeId=v;let k=new Set([p]);d&&k.add(d.id);let m=d!==null&&n.getChildren(d.id).length===0,b=m?d?.customId:null,w=r.skipBeforeSnap?new Map:await q(n,k);n.addActivity(_),Oy(e,p,d,n,m),b&&t.customIdTracker.releaseCustomId(b),r.skipRollupCascades||(oc(p,n),dc(p,n),uc(p,n));let S=Fy(n,p,k,r);return{ok:!0,newId:p,parent:d,newActivity:_,beforeSnap:w,initialTouched:k,correlativeShifts:S}}function by(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:C.PARENT_NOT_FOUND};if(n!==null&&ve(n))return{ok:!1,reason:C.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Ry(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function Ry(e,t,r,n){if(n===void 0)return null;let i=t.getActivity(n);if(!i)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}:null}function Ey(e,t,r,n){let i=()=>{let a=r.next();for(;t.activityExists(a)||n(String(a));)a=r.next();return a};return e===void 0||t.activityExists(e)||n(String(e))?i():(r.bump(e),e)}function Ly(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function wy(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=Ly(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??n,d=l!==void 0,u=d?s.getActivity(l):i;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Oy(e,t,r,n,i){if(!r)return;let a=We({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:i,getParent:s=>n.getActivity(s)??null});if(a){for(let[s,o]of Object.entries(a.fields))rt(n,a.parentId,s,o);a.promotionSnapshot&&n.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function Fy(e,t,r,n){if(n.skipCorrelativeRecompute)return[];let i=ot(e).filter(a=>a.activityId!==String(t));for(let a of i)r.add(a.activityId);return i}async function xy(e,t,r,n,i){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c,correlativeShifts:l}=r,d={name:It.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),W(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:n,correlativeShifts:l,trackingEvents:[d],hoursPerDay:i})}async function vc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=dn(e.overrides,a.hoursPerDay);if(!s.ok)return s;let o=await cr({...e,overrides:s.value},r);if(!o.ok)return o;let{newId:c}=o,l=o.newActivity.autoScheduling;n.setActivityField(c,"autoScheduling",!1);let d;try{d=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:r.now,options:t})}finally{n.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await xy(n,e,o,u,a.hoursPerDay)}}function Ny(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 Tt(e,t){Gi(e,t),$i(e,t),zi(e,t)}function Ac(e,t){let r=new Set,n=[];for(let i of e){let a=String(i);r.has(a)||(r.add(a),n.push(a))}for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);for(let s of a){let o=String(s);r.has(o)||(r.add(o),n.push(o))}}return r}function Ic(e,t){let r=new Set;for(let n of e){for(let i of t.getOutgoingLinkIds(n))r.add(String(i));for(let i of t.getIncomingLinkIds(n))r.add(String(i))}return[...r]}function My(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 Wy(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function Be(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=My(e.promotionSnapshot)??(n?{type:Se,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Wy(t,r,e.computeEndDate)}:{type:Se});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(i.newActivityIds=s)}}return t.hasLookaheadTasks&&(i.isLookahead=!0),{parentId:String(t.id),fields:i}}function Cc(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,n=r.filter(i=>!e.idsRemoved.has(i)&&!e.idsRemoved.has(String(i)));return n.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...n],hasNewActivities:n.length>0}}}var kc=200;async function Sc(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};for(let A of e.activityIds)if(!n.getActivity(A))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let o=e.activityIds.filter(A=>{let T=n.getActivity(A);return!(T?.correlativeId===0&&T.type===Ce.PROJECT)}),c=Ac(o,n),l=Ic(c,n),d=new Set;for(let A of e.activityIds){let T=n.getActivity(A);if(!T)continue;let x=T.parentId;if(L(x))continue;let F=String(x);c.has(F)||d.add(F)}let u=new Set([...c,...d]),f=await q(n,u),p=new Map;for(let A of l){let T=n.getLink(A);T&&p.set(A,{...T})}let h=new Set,g=0;for(let A of c){g+=1,g%kc===0&&await Q();let T=n.getActivity(A);if(!T)continue;let x=L(T.parentId)?null:n.getActivity(String(T.parentId)),F=x?.hasNewActivities===!0&&x.newActivityIds.some(G=>String(G)===String(A));(T.isNewActivity===!0||F)&&h.add(A);let J=T.customId;typeof J=="string"&&J.length>0&&a.releaseCustomId(J)}for(let A of l)n.removeLink(A);let I=Ji(n,c),_=0;for(let A of c)_+=1,_%kc===0&&await Q(),n.removeActivity(A);for(let A of d){let T=n.getActivity(A);if(!T)continue;Uy(T,h,n);let x=n.getChildren(A),F=Be({parent:T,remainingChildIds:x.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(J,G)=>n.calculateEndDate({startDate:J,durationHours:G,task:T}),idsRemoved:c});if(!F){Mr(A,n);continue}for(let[J,G]of Object.entries(F.fields))rt(n,A,J,G);if(T.customId==null||T.customId===""){let J=Qt(A,n),G=J?n.getActivity(J)?.customId:null,st=a.generateCustomIdForRestoredChild(typeof G=="string"&&G?G:null);n.setActivityField(A,E.CUSTOM_ID,st)}}for(let A of d)Tt(A,n);let v=ot(n),{scheduledIds:k}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:d,now:r.now,options:t}),m={name:It.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let b=new Map;for(let[A,T]of p)b.set(A,T);let w=new Map;for(let A of c){let T=f.get(String(A));T&&w.set(String(A),T)}let S=await W(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:k,sirDetection:"after-diff",links:jy(p),trackingEvents:[m],hoursPerDay:s.hoursPerDay,correlativeShifts:v});return{ok:!0,changes:I.length>0?{...S,viewState:I}:S,__beforeSnap:w,__beforeLinks:b}}function Uy(e,t,r){let n=Cc({parent:e,idsRemoved:t});if(n)for(let[i,a]of Object.entries(n.fields))rt(r,n.parentId,i,a)}function Ji(e,t){let r=[];for(let n of t){let i=e.isChecked(n),a=e.isVisible(n);!i&&a||r.push({activityId:String(n),...i?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function jy(e){let t=[];for(let[r,n]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(n.source),after:void 0},target:{before:String(n.target),after:void 0},type:{before:n.type,after:void 0},lag:{before:Number(n.lag),after:void 0}},after:null});return t}async function _c(e,t,r){let n=Hy(e,r);if(n)return{ok:!1,reason:n};let i=Yy(e,r);if(!i.ok)return i;let a=e.mode==="replace"?new Set(r.adapter.getAllIds().map(m=>String(m))):new Set,s=e.mode==="replace"?await q(r.adapter,a):new Map,o=e.mode==="replace"?Jy(r):new Map,c=e.mode==="replace"?Ji(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let m of o.keys()){let b=Ht({kind:"delete",linkId:m},{port:r.adapter});if(!b.applied)return{ok:!1,reason:b.rejected??C.INVALID};l.push({op:{kind:"delete",linkId:m},finalLinkId:m,rejected:null})}for(let m of a){let b=r.adapter.getActivity(m)?.customId;typeof b=="string"&&b.length>0&&r.customIdTracker.releaseCustomId(b),r.adapter.removeActivity(m)}}let d=await qy(e,i.plan.items,r);if(!d.ok)return d;let u=Pc(e)?[]:ot(r.adapter),f=new Set(i.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),h=e.mode==="replace"?new Set(a):new Set;$r(r.adapter,u,f,s,h);for(let m of i.plan.items)h.add(String(m.activityId));let g=i.plan.links.map(m=>({operation:{kind:"create",source:m.source,target:m.target,type:m.type,lag:vt(m.lag,r.sector.hoursPerDay)},linkId:m.linkId})),I=Er(g,{port:r.adapter,preserved:o});if(!I.applied)return{ok:!1,reason:I.rejected??C.INVALID};for(let{operation:m,linkId:b}of g)l.push({op:m,finalLinkId:b,rejected:null});let _=i.plan.items.map(m=>m.activityId),{scheduledIds:v}=await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?"roots":null,recomputeParentsFrom:_,now:r.now,options:t}),k=await W(r.adapter,{source:e,beforeSnap:s,touchedIds:h,scheduledIds:v,links:xe(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...k,viewState:c}:k,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:Xy(o)}:{}}}function Hy(e,t){if(e.mode!=="append"&&e.mode!=="replace")return C.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return C.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return C.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s))return C.INVALID;n.add(s)}}for(let a of e.items)if(!Xi(a.parent,!0,e.mode,r,t))return C.PARENT_NOT_FOUND;if(Vy(e.items))return C.INVALID;let i=new Set;for(let a of e.links){if(!Object.values(B).includes(a.type)||!Number.isFinite(a.lag))return Number.isFinite(a.lag)?C.INVALID_LINK_TYPE:C.INVALID_LINK_LAG;if(!Xi(a.source,!1,e.mode,r,t)||!Xi(a.target,!1,e.mode,r,t))return C.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s))return C.INVALID;i.add(s)}}return null}function Xi(e,t,r,n,i){return typeof e=="string"?e==="0"?t:r==="append"&&i.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&n.has(e.batchId)}function Vy(e){let t=new Map;for(let n of e)typeof n.parent!="string"&&t.set(n.batchId,n.parent.batchId);let r=new Set;for(let n of e){let i=new Set,a=n.batchId;for(;a!==void 0&&!r.has(a);){if(i.has(a))return!0;i.add(a),a=t.get(a)}for(let s of i)r.add(s)}return!1}function Yy(e,t){let r=new Map;for(let d of e.items){let u=dn(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let n=new Map,i=new Set;for(let d of e.items){let u=Ky(d.activityId,e.mode,i,t);i.add(String(u)),n.set(d.batchId,u)}let a=new Set,s=e.links.map(d=>{let u=Gy(d.linkId,e.mode,a,t);return a.add(String(u)),u}),o=$y(e,n,t),c=[];for(let d of e.items){let u=n.get(d.batchId),f=o.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:C.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,h=typeof d.parent=="string"?d.parent:n.get(d.parent.batchId);if(h===void 0)return{ok:!1,reason:C.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:h,parentBatchId:p,insertionCorrelativeId:f,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=Tc(u.source,n),p=Tc(u.target,n),h=s[d];if(f===null||p===null||h===void 0)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag,linkId:h})}return{ok:!0,plan:{items:c,links:l}}}function Ky(e,t,r,n){if(e!==void 0&&(t==="replace"||n.adapter.getActivity(e)===null&&!n.isActivityIdReserved(String(e)))&&!r.has(String(e)))return n.activityIdGen.bump(e),e;let a=n.activityIdGen.next();for(;r.has(String(a))||t==="append"&&(n.adapter.getActivity(a)!==null||n.isActivityIdReserved(String(a)));)a=n.activityIdGen.next();return a}function Gy(e,t,r,n){if(e!==void 0&&(t==="replace"||n.adapter.getLink(e)===null&&!n.isLinkIdReserved(String(e)))&&!r.has(String(e)))return n.linkIdGen.bump(e),e;let a=n.linkIdGen.next();for(;r.has(String(a))||t==="append"&&(n.adapter.getLink(a)!==null||n.isLinkIdReserved(String(a)));)a=n.linkIdGen.next();return a}function $y(e,t,r){if(Pc(e)){let o=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,o+l]))}let n=new Set(Array.from(t.values(),o=>String(o))),i=new Map;for(let o of e.items){let c=t.get(o.batchId);if(c===void 0)continue;let l=typeof o.parent=="string"?o.parent:t.get(o.parent.batchId);if(l===void 0)continue;let d=String(l),u=i.get(d);u||(u={existing:e.mode==="replace"||typeof o.parent!="string"&&t.has(o.parent.batchId)?[]:qi(r.adapter,d).sort((g,I)=>ct(g)-ct(I)||String(g.id).localeCompare(String(I.id))).map(g=>String(g.id)),newIdsByTarget:new Map},i.set(d,u));let f=o.index===void 0?u.existing.length:Math.min(o.index,u.existing.length),p=u.newIdsByTarget.get(f)??[];p.push(String(c)),u.newIdsByTarget.set(f,p)}let a=new Map,s=new Map(Array.from(t,([o,c])=>[String(c),o]));for(let o of i.values()){let c=[];for(let d=0;d<=o.existing.length;d+=1){for(let f of o.newIdsByTarget.get(d)??[])c.push(f);let u=o.existing[d];u!==void 0&&c.push(u)}let l=0;for(;l<c.length;){if(!n.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&n.has(c[l]);)l+=1;let u=l-d,f=d>0?Dc(c[d-1],r):null,p=l<c.length?Dc(c[l],r):null;for(let h=0;h<u;h+=1){let g=c[d+h],I=s.get(g);I!==void 0&&a.set(I,zy(f,p,h+1,u))}}}return a}function Pc(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Dc(e,t){let r=t.adapter.getActivity(e);return r?ct(r):0}function zy(e,t,r,n){return e!==null&&t!==null&&t>e?e+(t-e)*r/(n+1):e!==null?e+r:t!==null?t-(n-r+1):r-1}async function qy(e,t,r){let n=new Map,i=[];for(let s of t){if(s.parentBatchId===null){i.push(s);continue}let o=n.get(s.parentBatchId)??[];o.push(s),n.set(s.parentBatchId,o)}for(let s=0;s<i.length;s+=1){let o=i[s],c=await cr({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,overrides:o.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:o.insertionCorrelativeId});if(!c.ok)return c;for(let l of n.get(o.input.batchId)??[])i.push(l)}if(i.length!==t.length)return{ok:!1,reason:C.INVALID};let a=new Set;for(let s=i.length-1;s>=0;s-=1){let o=i[s].parentId;o==="0"||a.has(String(o))||(a.add(String(o)),Tt(o,r.adapter))}return{ok:!0}}function Tc(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Jy(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Xy(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function bc(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],s=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",s);let o=r.getActivity(n);if(!o)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let c={id:n,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:X(o)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Rc(e){let t=new Map;for(let r of e){let n=r.proplannerId;typeof n=="number"&&Number.isSafeInteger(n)&&n>0&&t.set(n,String(r.id))}return t}function Ec(e,t,r){let n=new Set(t.map(({id:i})=>String(i)));for(let i of e)if((i.proplannerId==null||i.proplannerId===0)&&!n.has(String(i.id)))throw new Error(`persistence-acknowledge: missing ${r} proplannerId for "${String(i.id)}"`)}function Zy(e,t,r,n,i,a){let s=String(e.id);if(s.length===0||i.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!==0&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=n.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);i.add(s),a.add(e.proplannerId)}function Lc(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Zy(s,t,r,n,i,a)}async function wc(e,t){let r=e.filter(o=>{let c=t.adapter.getActivity(String(o.activityId));return c!==null&&c.progress!==o.progress}),n=new Set(r.map(o=>String(o.activityId))),i=Ze(t.adapter,n),a=new Set(n);for(let o of i)a.add(String(o));let s=await q(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let o of r){let c=String(o.activityId);t.adapter.setActivityField(c,"progress",o.progress),t.adapter.setActivityField(c,"autoScheduling",ee(o.progress))}Fs(i,t.adapter),cc(n,i,t.adapter)}),[...await Kr(t.adapter,s,a)]}async function Oc(e,t){let r=e.activities??[],n=e.links??[],i=t.adapter.getAllActivities(),a=t.adapter.getAllLinks(),s=e.checkpoint?.activities??i,o=e.checkpoint?.links??a,c=new Map(s.map(h=>[String(h.id),h])),l=new Map(o.map(h=>[String(h.id),h])),d=Rc(s),u=Rc(o);Lc(r,"activity",h=>{let g=c.get(h);return{exists:g!==void 0,current:g?.proplannerId??null}},d),Lc(n,"link",h=>{let g=l.get(h);return{exists:g!==void 0,current:g?.proplannerId??null}},u),Ec(s,r,"activity"),Ec(o,n,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let h of r){let g=t.adapter.getActivity(h.id);if(!g||g.proplannerId===h.proplannerId)continue;let I=g.proplannerId;t.adapter.setActivityField(h.id,"proplannerId",h.proplannerId),f.push({id:h.id,kind:"updated",fields:{proplannerId:{before:I,after:h.proplannerId}},after:{...g,proplannerId:h.proplannerId}})}for(let h of n){let g=t.adapter.getLink(h.id);if(!g||g.proplannerId===h.proplannerId)continue;let I=g.proplannerId;t.adapter.setLinkProplannerId(h.id,h.proplannerId),p.push({id:h.id,kind:"updated",fields:{proplannerId:{before:I,after:h.proplannerId}},after:{...g,proplannerId:h.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function Fc(e,t,r){if(Qy(e))return{ok:!1,reason:C.INVALID_VALUE};let n=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&n.some(o=>!r.isActivityIdReserved(o)))return{ok:!1,reason:C.INVALID};let a=n.map(o=>r.adapter.getActivity(o));if(a.some(o=>!o))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=[];for(let[o,c]of n.entries()){let l=a[o];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},r.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},r.adapter.setActivityField(c,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(d).length!==0&&s.push({id:c,kind:"updated",fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await wc([{activityId:n[0],progress:e.persistedProgress}],r)).length>0?(await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.persistedProgress===0?n[0]:null,recomputeParentsFrom:[],now:r.now,options:t}),{ok:!0,changes:await W(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:s,links:[],calendars:[],trackingEvents:[]}}}function Qy(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function un(e,t){let r=new Set;for(let i of e)r.add(String(i));let n=[];for(let i of t.getAllLinks()){let a=String(i.source),s=String(i.target);!r.has(a)&&!r.has(s)||(xc(s,a,t)||xc(a,s,t))&&n.push(String(i.id))}return n}function xc(e,t,r){let n=String(e),i=new Set;for(;n!=null;){if(i.has(n))return!1;i.add(n);let a=r.getActivity(n);if(!a)return!1;let s=a.parentId;if(s===null||L(s))return!1;let o=s;if(o===t)return!0;n=o}return!1}function fn(e,t){let r=e.getAllLinks();return!qe({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function pn(e,t){let r=new Set;if(e.length===0)return r;let n=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!fn(t,n))return r;let i=new Map;for(let a of e){let s=new Map(i);if(s.set(a.activityId,a.newParentId),fn(t,s)){r.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return r}async function Nc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;i.invalidateAllCaches();let s=n.getActivity(e.activityId);if(!s)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:C.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:C.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let b=n.getActivity(c);if(!b)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};if((b.parentId===null?"0":String(b.parentId))!==e.parentId)return{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Ut(l),u=String(e.parentId),f=d!==u;if(f){let b=new Map([[e.activityId,o?null:e.parentId]]);if(fn(n,b))return{ok:!1,reason:C.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let h=await q(n,p);f&&n.setActivityField(e.activityId,E.PARENT,u);let g=cn(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,E.CORRELATIVE_ID,g),f){if(!o){let b=n.getActivity(e.parentId);if(b){let w=b.customId,S=jt(b.type)&&n.getChildren(e.parentId).filter(T=>T!==e.activityId).length===0,A=We({parentId:e.parentId,newChildId:e.activityId,getParent:T=>n.getActivity(T)??null,isCurrentlyLeaf:S,promotionSource:"reparent"});if(A){for(let[T,x]of Object.entries(A.fields))rt(n,A.parentId,T,x);A.promotionSnapshot&&n.setPromotionSnapshot(A.parentId,A.promotionSnapshot),A.fields.customId===null&&an(w,r.customIdTracker)}}}if(d!=="0"){let b=n.getActivity(d);if(b){let w=n.getChildren(d),S=Be({parent:b,remainingChildIds:w.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(d),computeEndDate:(A,T)=>n.calculateEndDate({startDate:A,durationHours:T,task:b}),idsRemoved:new Set([e.activityId])});if(S){for(let[J,G]of Object.entries(S.fields))rt(n,d,J,G);let A=Qt(d,n),T=A?n.getActivity(A)?.customId:null,x=typeof T=="string"&&T?T:null,F=r.customIdTracker.generateCustomIdForRestoredChild(x);n.setActivityField(d,E.CUSTOM_ID,F)}}}}f&&(d!=="0"&&Tt(d,n),o||Tt(e.parentId,n));let I=ot(n);for(let b of I){if(p.add(b.activityId),h.has(b.activityId))continue;let w=n.getActivity(b.activityId);if(!w)continue;let S=X(w);b.before!==void 0&&(S.correlativeId=b.before),h.set(b.activityId,S)}let _=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:v}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,..._],now:r.now,options:t,recomputeParentProgress:f}),k=f?un([e.activityId],n):[],m={name:It.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:k.map(String)}};return e.eventSource!==void 0&&(m.properties.event_source=e.eventSource),{ok:!0,changes:await W(n,{source:e,beforeSnap:h,touchedIds:p,scheduledIds:v,sirDetection:"before-diff",trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function hn(e,t){let r=new Set(e),n=[],i=[],a=new Set,s=new Set(r),o=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),h=f?ct(f):ue,g=p?ct(p):ue;return h-g});for(let d of o){if(!t.getActivity(d)){n.push({activityId:d,reason:C.ACTIVITY_NOT_FOUND}),s.delete(d);continue}if(ln(d,a,t))continue;let f=qa(d,s,t);if(f==null){n.push({activityId:d,reason:C.INDENT_NO_ELIGIBLE_SIBLING}),s.delete(d);continue}let p=t.getActivity(d)?.parentId,h=L(p)?"0":String(p);i.push({activityId:d,newParentId:f,oldParentId:h}),a.add(d)}let c=pn(i,t);for(let d of c)n.push({activityId:d,reason:C.HIERARCHY_CYCLE});let l=i.filter(d=>!c.has(d.activityId));return{moves:i,cyclicMoveIds:c,allowedMoves:l,failed:n}}async function Mc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let s=new Set,o=[],c=hn(e.activityIds,n),l=[...c.failed];for(let v of c.moves)s.add(String(v.activityId)),s.add(String(v.newParentId)),v.oldParentId!=="0"&&s.add(String(v.oldParentId));let d=c.allowedMoves,u=await q(n,s);for(let{activityId:v,newParentId:k}of d)n.setActivityField(v,E.PARENT,k),n.setActivityField(v,E.CORRELATIVE_ID,yc),o.push(v);let f=new Set;for(let{activityId:v,newParentId:k}of d){if(f.has(k))continue;f.add(k);let m=n.getActivity(k);if(!m)continue;let b=m.customId,w=jt(m.type)&&n.getChildren(k).filter(T=>!o.includes(T)).length===0,S=m.hasNewActivities&&m.newActivityIds.some(T=>String(T)===String(v)),A=We({parentId:k,newChildId:v,getParent:T=>n.getActivity(T)??null,isCurrentlyLeaf:w,promotionSource:"reparent"});if(A){for(let[T,x]of Object.entries(A.fields))rt(n,A.parentId,T,x);A.promotionSnapshot&&n.setPromotionSnapshot(A.parentId,A.promotionSnapshot),S||(n.setActivityField(k,E.HAS_NEW_ACTIVITIES,!1),n.setActivityField(k,E.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(k,E.CONSTRAINT_TYPE,"asap"),n.setActivityField(k,E.CONSTRAINT_DATE,null),n.setActivityField(k,E.CUSTOM_ID,null),an(b,r.customIdTracker)}let p=new Set;for(let v of d)v.oldParentId!=="0"&&p.add(v.oldParentId),p.add(v.newParentId);for(let v of p)Tt(v,n);let h=ot(n);for(let v of h){if(s.add(v.activityId),u.has(v.activityId))continue;let k=n.getActivity(v.activityId);if(!k)continue;let m=X(k);v.before!==void 0&&(m.correlativeId=v.before),u.set(v.activityId,m)}let{scheduledIds:g}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:o,now:r.now,options:t}),I=un(o,n),_={name:It.ACTIVITY_INDENT,properties:{activity_ids:o,failed:l.map(v=>({activity_id:v.activityId,reason:v.reason})),invalid_link_ids:I}};return e.eventSource!==void 0&&(_.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(v=>{let k=l.find(m=>String(m.activityId)===String(v));return k?{activityId:String(v),ok:!1,reason:k.reason}:{activityId:String(v),ok:!0}}),changes:await W(n,{source:e,beforeSnap:u,touchedIds:s,scheduledIds:g,trackingEvents:[_],hoursPerDay:a.hoursPerDay})}}async function Wc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let S of e.activityIds){let A=S;n.getActivity(A)&&(o.set(A,Gn(A,n)),c.set(A,mc(A,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],h=new Set,g=[...e.activityIds].sort((S,A)=>{let T=n.getActivity(S),x=n.getActivity(A),F=T?ct(T):ue,J=x?ct(x):ue;return F-J});for(let S of g){let A=S,T=n.getActivity(A);if(!T){d.push({activityId:A,reason:C.ACTIVITY_NOT_FOUND});continue}if(ln(A,h,n))continue;let x=T.parentId;if(L(x)){d.push({activityId:A,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let F=String(x),J=n.getActivity(F);if(!J){d.push({activityId:A,reason:C.ACTIVITY_NOT_FOUND});continue}let G=J.parentId;if(L(G)){d.push({activityId:A,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let st=String(G),pt=Gn(F,n)+1,nt=c.get(A);if(nt!=null&&s.has(nt)){let ye=o.get(nt)??-1,me=o.get(A)??-1;ye>=0&&me>=0&&(pt+=me-ye)}p.push({activityId:A,grandparentKey:st,oldParentKey:F,targetIndexInGrandparent:pt}),h.add(A),l.add(String(A)),l.add(String(F)),st!=="0"&&l.add(String(st)),f.add(F)}let I=pn(p.map(S=>({activityId:S.activityId,newParentId:S.grandparentKey})),n);for(let S of I)d.push({activityId:S,reason:C.HIERARCHY_CYCLE});let _=p.filter(S=>!I.has(S.activityId)),v=await q(n,l);for(let S of _){n.setActivityField(S.activityId,E.PARENT,S.grandparentKey);let A=gc(n,S.grandparentKey,S.targetIndexInGrandparent,S.activityId);n.setActivityField(S.activityId,E.CORRELATIVE_ID,A),u.push(S.activityId)}for(let S of f){let A=n.getActivity(S);if(!A)continue;let T=n.getChildren(S),x=Be({parent:A,remainingChildIds:T.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(S),computeEndDate:(pt,nt)=>n.calculateEndDate({startDate:pt,durationHours:nt,task:A}),idsRemoved:new Set(_.filter(pt=>pt.oldParentKey===S).map(pt=>pt.activityId))});if(!x){Mr(S,n);continue}for(let[pt,nt]of Object.entries(x.fields))rt(n,S,pt,nt);let F=Qt(S,n),J=F?n.getActivity(F)?.customId:null,G=typeof J=="string"&&J?J:null,st=r.customIdTracker.generateCustomIdForRestoredChild(G);n.setActivityField(S,E.CUSTOM_ID,st)}let k=new Set;for(let S of f)k.add(String(S));for(let S of _)S.grandparentKey!=="0"&&k.add(String(S.grandparentKey));for(let S of k)Tt(S,n);let m=ot(n);for(let S of m){if(l.add(S.activityId),v.has(S.activityId))continue;let A=n.getActivity(S.activityId);if(!A)continue;let T=X(A);S.before!==void 0&&(T.correlativeId=S.before),v.set(S.activityId,T)}let{scheduledIds:b}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),w={name:It.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(S=>({activity_id:String(S.activityId),reason:S.reason}))}};return e.eventSource!==void 0&&(w.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(S=>{let A=d.find(T=>String(T.activityId)===String(S));return A?{activityId:String(S),ok:!1,reason:A.reason}:{activityId:String(S),ok:!0}}),changes:await W(n,{source:e,beforeSnap:v,touchedIds:l,scheduledIds:b,trackingEvents:[w],hoursPerDay:a.hoursPerDay})}}async function Bc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:C.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let c=qt(P.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.canEdit(o,i.hierarchy);if(!l.allowed&&!(e.origin==="action-button"&&(l.reason==="has_lookahead_tasks"||l.reason==="summary")))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(o,e.newValue,i,e.newValue),u=Jt(e.activityId,d),f=await q(n,u);Xt(n,e.activityId,d),Ns(e.activityId,e.newValue,n),Yt(e.activityId,d.postProcessors??[],n);let{scheduledIds:p}=await Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:g=>Gr(e.activityId,u,g),now:r.now,options:t}),h=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await W(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function Uc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let h of e.edits){let g=tm(h,r);if(s.push(g.verdict),!g.verdict.ok||!g.changes)continue;let I=Jt(h.activityId,g.changes);em(o,I,r);for(let m of I)c.add(m);let _=Ne(n,h.activityId),v=Yr(n,String(h.activityId));Xt(n,h.activityId,g.changes),Yt(h.activityId,g.changes.postProcessors??[],n,v),d.push(...Me(_,n,h.activityId)),f||=!!g.changes.needsAutoSchedule;for(let m of g.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=Le(h.activityId,g.changes.constraintWarning);k&&u.push(k)}let{scheduledIds:p}=await Y({adapter:n,scheduler:i,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 W(n,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function tm(e,t){let{ctx:r}=t,n=e.activityId,i=qt(e.column);if(!i)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=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??C.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=i.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:n,ok:!1,reason:o.reason??C.PARSE_ERROR},changes:null};let c=Reflect.get(a,i.targetField),l=i.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:n,ok:!1,reason:l.reason??C.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function em(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,X(a))}}var Zi=P.CUSTOM_ID;async function jc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(k=>k.column===P.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],h=[],g=!1;for(let k of e.edits){let m=rm(k,r,e.eventSource);if(o.push(m.verdict),!m.verdict.ok||!m.changes)continue;let b=Le(k.activityId,m.changes.constraintWarning);b&&h.push(b);let w=Jt(k.activityId,m.changes);sm(c,w,r);for(let F of w)u.add(F);am(l,k,c),en(k.column)&&d.add(String(k.activityId));let S=Ne(n,k.activityId),A=Yr(n,String(k.activityId)),T=nm(k,r),x=m.changes;Xt(n,k.activityId,x),Yt(k.activityId,m.changes.postProcessors??[],n,A),im(k,T,r),p.push(...Me(S,n,k.activityId)),g||=!!m.changes.needsAutoSchedule;for(let F of m.changes.trackingEvents??[])f.push({name:F.name,properties:F.properties??{}})}let I={action:e,autoscheduleFrom:g?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},_=l.size>0,{scheduledIds:v}=await(_?nn({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:I,revertTargets:[...l].filter(([k])=>!d.has(k)).map(([k,m])=>({activityId:k,priorConstraintDate:m})),revert:(k,m)=>rn(k,m,n,r.ctx.calendars)}):Y({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},I));return{ok:!0,verdicts:o,changes:await W(n,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:v,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:h,hoursPerDay:a.hoursPerDay})}}function rm(e,t,r){let{ctx:n}=t,i=e.activityId,a=qt(e.column);if(!a)return{verdict:{activityId:i,ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN},changes:null};let s=n.activityReader.getActivity(e.activityId);if(!s)return{verdict:{activityId:i,ok:!1,reason:C.ACTIVITY_NOT_FOUND},changes:null};let o=a.canEdit(s,n.hierarchy,{eventSource:r,newValue:e.newValue});if(!o.allowed)return{verdict:{activityId:i,ok:!1,reason:o.reason??C.CANNOT_EDIT,...o.alertKey?{alertKey:o.alertKey}:{}},changes:null};let c=a.parseInput(e.newValue,s,n);if(!c.ok)return{verdict:{activityId:i,ok:!1,reason:c.reason??C.PARSE_ERROR},changes:null};let l=Reflect.get(s,a.targetField),d=a.validate(s,l,c.value,n);if(!d.valid)return{verdict:{activityId:i,ok:!1,reason:d.reason??C.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===Zi&&c.value!==null){let f=t.adapter.getActivity(e.activityId),p=f?f.customId:null,h=typeof p=="string"?p:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),h))return{verdict:{activityId:i,ok:!1,reason:C.CUSTOM_ID_DUPLICATE},changes:null}}let u=a.transform(s,c.value,n,c.raw);return{verdict:{activityId:i,ok:!0},changes:u}}function nm(e,t){if(e.column!==Zi)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function im(e,t,r){if(e.column!==Zi)return;let n=r.adapter.getActivity(e.activityId),i=n?n.customId:null,a=typeof i=="string"?i:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function am(e,t,r){if(!tn(t.column))return;let n=String(t.activityId);if(e.has(n))return;let i=r.get(n);i&&e.set(n,i.constraintDate??null)}function sm(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,X(a))}}function Hc(e){return typeof e=="string"&&e.length>0?Mt(e):e instanceof Date?e:null}function Qi(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 yn(e,t){let r=Qi(e.duration),n=Qi(e.cost),i=Qi(e.hh_work);return r===null||n===null||i===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:Hc(e.start_date),endDate:Hc(e.end_date),durationDays:r,cost:n,workHours:i,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 Vc(e,t,r){let n=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&n.set(c,o)});let i=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=n.get(o);if(c===void 0)continue;let l=i.get(c);l?l.push(s):i.set(c,[s])}let a=[];for(let[s,o]of i)e.setActivityField(s,"baselinePoints",o.map(c=>yn(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(i.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function om(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Yc(e){let t=[];return e.forEachActivity((r,n)=>{let i=om(r);if(!i){r.baselineSnapshot!==null&&(e.setActivityField(n,"baselineSnapshot",null),t.push(n));return}e.setActivityField(n,"baselineSnapshot",i),t.push(n)}),t}function mn(e,t,r,n,i=null){let a=new Set;for(let s of Vc(e,t,n))a.add(s);if(r)for(let s of Oe(e,r,i))a.add(s);for(let s of Yc(e))a.add(s);for(let s of Fe(e))a.add(s);return[...a]}function Kc(e,t,r){if(!e||e==="0")return;let n=r.getChildren(e);if(n.length===0)return;let i=new Map,a=0;for(let o of n){let c=cm(String(o),t,r);i.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of n){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(ut(c)){let u=i.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 cm(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return gn(i.cost);if(t==="HH")return gn(i.workHours);let a=n.type;return a==="project"?Gc(e,r):a==="milestone"?0:gn(i.durationDays)}function Gc(e,t){let r=0;for(let n of t.getChildren(e)){let i=t.getActivity(n);if(!i)continue;let a=ut(i);if(!a)continue;let s=i.type;s==="project"?r+=Gc(String(n),t):s!=="milestone"&&(r+=gn(a.durationDays))}return r}function gn(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function $c(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,P.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&Kc(String(n),e,t)})}function vn(e,t){$c(t,e.adapter),Xe(e.adapter),e.now&&(Oe(e.adapter,e.now,e.defaultBaseCalendarId??null),oe(e.adapter,e.now)),Fe(e.adapter),e.now&&Wt(e.adapter,e.sector.statusCriteria)}function zc(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(n=>n.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 qc(e,t){let r=await q(t.adapter,new Set(t.adapter.getAllIds())),n=zc(t),i=mn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return zc(t)!==n&&vn(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await W(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function lm(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function Jc(e,t){lm(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await q(t.adapter,r);return vn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await W(t.adapter,{source:e,beforeSnap:n,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Xc(e,t){let r=zr(e.criteria),n=new Set(t.adapter.getAllIds()),i=await q(t.adapter,n),a=Wt(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await W(t.adapter,{source:e,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Qc(e,t,r){let n=new Map,i=new Set;for(let s of r.adapter.getAllActivities()){if(!dm(s,r))continue;let o=r.ctx.calendars.getCalendar(s.calendarId);if(!o)continue;let c=o.getClosestWorkTime({date:s.startDate,direction:Z.FUTURE,unit:it.HOUR}),l=o.calculateEndDate(c,s.durationHours);if(Zc(c,s.startDate)&&Zc(l,s.endDate))continue;let d=String(s.id);n.set(d,X(s)),i.add(d),r.adapter.setActivityFields(d,{startDate:c,endDate:l})}let{scheduledIds:a}=await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:i,now:r.now,options:t});return{ok:!0,changes:await W(r.adapter,{source:e,beforeSnap:n,touchedIds:i,scheduledIds:a,hoursPerDay:r.sector.hoursPerDay})}}function dm(e,t){return e.progress===0&&!St(e.type,t.adapter.hasChildren(e.id))}function Zc(e,t){return e.getTime()===t.getTime()}var tl=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function um(e){let t={};for(let r of tl)Object.assign(t,{[r]:R(e[r])});return t}function fm(e,t){let r=[],n=i=>{t.has(String(i))&&r.push(i);for(let a of e.getChildren(i))n(a)};for(let i of e.getRootIds())n(i);return r}function el(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:C.NO_ACTIVITY_SELECTION};let n=fm(t.adapter,r);t.clipboard.value={activities:n.map(a=>{let s=t.adapter.getActivity(a);if(s===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:s.parentId??"0",overrides:um(s)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>R(a))};let i=yr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return i.ok?{...i,changes:{...i.changes,source:e}}:i}function rl(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function pm(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id}:{ok:!0,parentId:"0",afterSiblingId:e}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND}}var nl=()=>({ok:!1,reason:C.ACTIVITY_PASTE_INVARIANT_FAILED});async function il(e,t,r){let n=r.activityClipboard.value;if(n===null)return{ok:!1,reason:C.CLIPBOARD_EMPTY};let i=pm(e.destination.afterSiblingId,r.adapter);if(!i.ok)return i;let a=await q(r.adapter,new Set),s=new Set,o=new Map,c=[],l;for(let g of n.activities){let I=o.get(g.originalParentId),_=I===void 0?l??i.afterSiblingId:void 0,v=await cr({kind:"activity-create",parentId:I??i.parentId,..._===void 0?{}:{afterSiblingId:_},overrides:R(g.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!v.ok)return v;o.set(g.originalId,v.newId),c.push(v.newId),I===void 0&&(l=v.newId)}let d=ot(r.adapter),u=new Set(c.map(String));$r(r.adapter,d,u,a,s);for(let g of c)s.add(String(g));let f=[];for(let g of n.links){let I=o.get(g.source),_=o.get(g.target);if(I===void 0||_===void 0)return nl();let v={kind:"create",source:I,target:_,type:g.type,lag:g.lag},k=Ht(v,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return nl();f.push({op:v,finalLinkId:k.linkId,rejected:null})}let{scheduledIds:p}=await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:r.now,options:t}),h=xe(f,new Map,r.adapter);return{ok:!0,changes:await W(r.adapter,{source:e,beforeSnap:a,touchedIds:s,scheduledIds:p,links:h,hoursPerDay:r.sector.hoursPerDay})}}async function al(e,t,r){return e.kind==="activity-copy"?el(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="calendar-reconcile"?Qc(e,t,r):e.kind==="activity-clipboard-clear"?rl(e,r.activityClipboard):e.kind==="activity-paste-copied"?il(e,t,r):e.kind==="activity-batch"?_c(e,t,r):e.kind==="persistence-acknowledge"?Oc(e,r):e.kind==="baseline-apply"?qc(e,r):e.kind==="ponderator-criterion-set"?Jc(e,r):e.kind==="status-criteria-set"?Xc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?ec(e,t,r):e.kind==="links-batch"?rc(e,t,r):e.kind==="activity-create"?vc(e,t,r):e.kind==="activity-delete"?Sc(e,t,r):e.kind==="activity-move"?Nc(e,t,r):e.kind==="activity-indent"?Mc(e,t,r):e.kind==="activity-outdent"?Wc(e,t,r):e.kind==="activity-set-progress"?Bc(e,t,r):e.kind==="dates-batch"?Uc(e,t,r):e.kind==="bulk-edit"?jc(e,t,r):e.kind==="selection-toggle"?Ma(e,ta(r)):e.kind==="selection-replace"?yr(e,ta(r)):e.kind==="visibility-set"?Wa(e,ta(r)):e.kind==="filter-set"?Ga(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?Xa(e,{adapter:r.adapter}):e.kind==="sir-sync"?bc(e,r):e.kind==="activity-lookahead-sync"?Fc(e,t,r):e.kind==="inline-edit"&&(e.column===P.CUSTOM_PREDECESSORS||e.column===P.CUSTOM_SUCESSORS)?nc(e,t,r):e.kind!=="inline-edit"?Za(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):tc(e,t,r)}function ta(e){return{adapter:e.adapter}}var hm=new Set(["startDate","endDate","constraintDate"]);function sl(e,t){return hm.has(e)&&typeof t=="string"?new Date(t):t}function ol(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?ym(i,r):null}}}function ym(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,n){return e.calculateEndDate({start_date:r,duration:n,unit:t})},calculateDuration(r,n){return e.calculateDuration({start_date:r,end_date:n,unit:t})},isWorkTime(r,n){return e.isWorkTime({date:r,unit:n})},getWorkHours(r){return e.getWorkHours(r)}}}function mm(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function fe(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function pe(e){return fe(e)&&!isNaN(e.getTime())}var gm={}.constructor.toString();function vm(e){var t=e.constructor.toString();return t!==gm}function Am(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function _t(e){var t,r;if(e&&typeof e=="object")switch(!0){case fe(e):r=new Date(e);break;case mm(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=_t(e[t]);break;default:if(vm(e))r=Object.create(e);else{if(Am(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=_t(e[t]));break}return r||e}function Ue(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function cl(e){return typeof e<"u"}var An;function ea(){return An||(An=new Date().valueOf()),An++,An}function mt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Cm=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,i=>{switch(i){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 i}});let n=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return i=>n(i,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},km=(e,t,r)=>{let n="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=e.match(/%[a-zA-Z]/g);for(let o=0;o<i.length;o++)switch(i[o]){case"%j":case"%d":n+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":n+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":n+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":n+=`set[3]=temp[${o}]||0;`;break;case"%i":n+=`set[4]=temp[${o}]||0;`;break;case"%Y":n+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":n+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":n+=`set[5]=temp[${o}]||0;`;break;case"%M":n+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":n+=`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]; ${n} return new Date(${a});`);return o=>s(o,r.locale)},ll={date_to_str:Cm,str_to_date:km},Sm=(e,t,r)=>n=>e.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return t?r.date.to_fixed(n.getUTCDate()):r.date.to_fixed(n.getDate());case"%m":return t?r.date.to_fixed(n.getUTCMonth()+1):r.date.to_fixed(n.getMonth()+1);case"%j":return t?n.getUTCDate():n.getDate();case"%n":return t?n.getUTCMonth()+1:n.getMonth()+1;case"%y":return t?r.date.to_fixed(n.getUTCFullYear()%100):r.date.to_fixed(n.getFullYear()%100);case"%Y":return t?n.getUTCFullYear():n.getFullYear();case"%D":return t?r.locale.date.day_short[n.getUTCDay()]:r.locale.date.day_short[n.getDay()];case"%l":return t?r.locale.date.day_full[n.getUTCDay()]:r.locale.date.day_full[n.getDay()];case"%M":return t?r.locale.date.month_short[n.getUTCMonth()]:r.locale.date.month_short[n.getMonth()];case"%F":return t?r.locale.date.month_full[n.getUTCMonth()]:r.locale.date.month_full[n.getMonth()];case"%h":return t?r.date.to_fixed((n.getUTCHours()+11)%12+1):r.date.to_fixed((n.getHours()+11)%12+1);case"%g":return t?(n.getUTCHours()+11)%12+1:(n.getHours()+11)%12+1;case"%G":return t?n.getUTCHours():n.getHours();case"%H":return t?r.date.to_fixed(n.getUTCHours()):r.date.to_fixed(n.getHours());case"%i":return t?r.date.to_fixed(n.getUTCMinutes()):r.date.to_fixed(n.getMinutes());case"%a":return t?n.getUTCHours()>11?"pm":"am":n.getHours()>11?"pm":"am";case"%A":return t?n.getUTCHours()>11?"PM":"AM":n.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(n.getUTCSeconds()):r.date.to_fixed(n.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(n)):r.date.to_fixed(r.date.getISOWeek(n));case"%w":return r.date.to_fixed(r.date.getWeek(n));default:return i}}),Dm=(e,t,r)=>n=>{let i=[0,0,1,0,0,0],a=n.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":i[2]=a[o]||1;break;case"%n":case"%m":i[1]=(a[o]||1)-1;break;case"%y":i[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":i[3]=a[o]||0;break;case"%i":i[4]=a[o]||0;break;case"%Y":i[0]=a[o]||0;break;case"%a":case"%A":i[3]=i[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":i[5]=a[o]||0;break;case"%M":i[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":i[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(i[0],i[1],i[2],i[3],i[4],i[5])):new Date(i[0],i[1],i[2],i[3],i[4],i[5])},dl={date_to_str:Sm,str_to_date:Dm};function ul(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 n=null;function i(){try{new Function("canUseCsp = false;")}catch{n=!0}}function a(){var o=!1;return e.config.csp==="auto"?(n===null&&i(),o=n):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=ll;return a()&&(l=dl),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=ll;return a()&&(l=dl),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 ra(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function na(e,t,r,n,i,a){return this.date=e,this.dir=t,this.unit=r,this.task=n,this.id=i,this.calendar=a,this}function ia(e,t,r,n,i,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=n,this.task=i,this.id=a,this.calendar=s,this}function Tm(e,t,r,n){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=n,this.unit=null,this.step=null,this}var fl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(fe(t)?t={date:t}:t=Ue({},t),!pe(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 ra)return t;var r;if(t.date?r=new ra(t.date,t.unit,t.task,null,t.calendar):r=new ra(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!pe(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 na)return r;var n;if(fe(r)?n=new na(r):n=new na(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(n.task=r),n.dir=r.dir||"any",n.unit=r.unit||e.config.duration_unit,!pe(n.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return n},_getStartEndConfig:function(t){var r=Tm,n;if(t instanceof r)return t;if(fe(t)?n=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(n=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(n.task=t)),n.unit=n.unit||e.config.duration_unit,n.step=n.step||e.config.duration_step,n.start_date=n.start_date||n.start||n.date,!pe(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!pe(n.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return n},getDurationArguments:function(t,r,n,i){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,n,i){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,n,i){var a=arguments[0];if(a instanceof ia)return a;var s;if(fe(a)?s=new ia(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new ia(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,!pe(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 pl(){}pl.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 n(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var i=0;i<e.length;i++)t.push(n(e[i].start)+"-"+n(e[i].end));return t},_intersectHourRanges:function(e,t){var i=[],r=e.length>t.length?e:t,n=e===r?t:e;r=r.slice(),n=n.slice();for(var i=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<n.length;o++){var c=n[o];c.start<s.end&&c.end>s.start&&(i.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(n.splice(o,1),o--,a--))}return i},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],n=1;n<t.length;n++){var i=t[n];i.start<=r.end?(i.end>r.end&&(r.end=i.end),t.splice(n,1),n--):r=i}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=_t(e.getConfig()),n=_t(t.getConfig()),i=r.parsed,a=n.parsed;i.customWeeks=r.customWeeks,a.customWeeks=n.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(i.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 h=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&h)),Array.isArray(f)){let g=Array.isArray(h)?h:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,g))}}}};if(o(i,a),o(a,i),i.customWeeks)for(var c in i.customWeeks)s.customWeeks[c]=i.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 aa=class{constructor(){this.clear()}getItem(t,r,n){if(this._cache.has(t)){let a=this._cache.get(t)[n.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,n,i){if(!t||!r)return;let a=this._cache,s=i.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,n)}clear(){this._cache=new Map}},sa=class{constructor(){this.clear()}getItem(t,r,n){let i=this._cache;if(i&&i[t]){let a=i[t];if(a===void 0)return-1;let s=a[n.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,n,i){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=i.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=n}clear(){this._cache={}}},oa=class{constructor(t){this.getMinutesPerWeek=r=>{let n=r.valueOf();if(this._weekCache.has(n))return this._weekCache.get(n);let i=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=i.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(n,s),s},this.getMinutesPerMonth=r=>{let n=r.valueOf();if(this._monthCache.has(n))return this._monthCache.get(n);let i=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+=i.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(n,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function _m(){return typeof Map<"u"?new aa:new sa}var ca=class{constructor(){this.clear()}_getCacheObject(t,r,n){let i=this._cache;i[r]||(i[r]=[]);let a=i[r];a||(a=i[r]={});let s=a[n];s||(s=a[n]={});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,n,i,a){let s=this._getCacheObject(t,n,i),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,n,i,a){let s=this._getCacheObject(t,n,i),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 la(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=_m(),this._largeUnitsCache=new oa(this),this._dateDurationCache=new ca,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}la.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)),n=this.$gantt.date.add(r,1,t);return this.hasDuration(r,n)}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(),n=0;n<t.length;n++)if(r>=t[n].startHour&&r<t[n].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),n=0;n<t.length;n++)if(r>=t[n].start&&r<t[n].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,n){var i=this.$gantt.date,a=new Date(e),s=new Date(t);n=n||1;var o=0,c=null,l,d,u=!1;l=i[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=i[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,n),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=i[r+"_start"](new Date(a)),d=i.add(l,n,r)),u?(u=!1,c=this._nextDate(l,r,n),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 h=this._getUnitOrder(r),g=this.units[h-1];g&&!this._isWorkTime(a,g)&&(c=this._getClosestWorkTimeFuture(a,g))}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 n=this._getWorkHours(e),i=0;i<n.length;i++){var a=n[i];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(n){r+=n.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(n){r+=n.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,n){var i=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=mt(this._getMinutesPerDay,this):o=mt(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),i+=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),i+=c,a=this.$gantt.date.add(a,7,"day");continue}}i+=o(a),a=this._nextDate(a,"day",1)}return i/n},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),n=this._getWorkHours(e),i=0,a=0;a<n.length;a++){var s=n[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);i+=(c-o)/60,r.start=c}}return Math.floor(i)},_getMinutesBetween:function(e,t,r,n){var i=new Date(e),a=new Date(t);n=n||1;var s=new Date(i),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),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,n),p=d+f+u;return p},_getHoursBetween:function(e,t,r,n){var i=new Date(e),a=new Date(t);n=n||1;var s=new Date(i),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),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,n)/60,u=this._getMinutesBetweenSingleDay(c,l,r,n)/60,f=this._getWorkUnitsForRange(o,c,r,n),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,n=null;for(var t in e.customWeeks){var i=e.customWeeks[t];if(i.from&&i.to){var a=i.from,s=i.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!n||n<s.valueOf())&&(n=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:i.from,to:i.to,hours:this._parseHours(i.hours),dates:{}};if(i.days&&!i.dates){i.dates=i.dates||{};for(var t=0;t<i.days.length;t++)i.dates[t]=i.days[t],i.days[t]instanceof Array||(i.dates[t]=!!i.days[t]);delete i.days}for(var c in i.dates)o.dates[c]=this._parseHours(i.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=n}},_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),n=Object.keys(t.dates);if(r.sort(),n.sort(),!this._arraysEqual(r,n))return!1;for(var i=0;i<r.length;i++){var a=r[i],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 la))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 n in t.parsed.customWeeks){var i=t.parsed.customWeeks[n],a=r.parsed.customWeeks[n];if(!a||!this._compareSettings(i,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 n=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var i=this._timestamp({date:n});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=i&&r.customWeeksRangeEnd>i){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=i&&r.customWeeksBoundaries[a].to>i){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[i]!==void 0?s=r.dates[i]: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 n=t.getUTCHours();return!n&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(n=24),r.end=n*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=[],n=0;n<t.length;n+=2){var i=t[n],a=t[n+1],s=a-i;r.push({start:i,end:a,startHour:Math.floor(i/3600),startMinute:Math.floor(i/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(mt(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),n=this.getConfig();if(r!==null?n.dates[r]=t:e.customWeeks||(n.hours=t),e.customWeeks){if(n.customWeeks||(n.customWeeks={}),typeof e.customWeeks=="string")r!==null?n.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(n.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var i in e.customWeeks)n.customWeeks[i]=e.customWeeks[i]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(mt(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,n=null;return n=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,n,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,n,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,n){var i=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&n==1?i=this._getHoursBetween(e,t,r,n):r=="minute"&&n==1?i=this._getMinutesBetween(e,t,r,n):i=this._getWorkUnitsBetweenGeneric(e,t,r,n),a*Math.round(i)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,n=e.unit,i=e.step;if(!n)return!1;var a=new Date(t),s=new Date(r);for(i=i||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,n))return!0;a=this._nextDate(a,n,i)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,n=e.unit,i=e.step;if(!n)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,n,i*a,function(){return s._calculateEndDate(t,r,n,i*a)})},_calculateEndDate:function(e,t,r,n){if(!r)return!1;if(n==1&&r=="minute")return this._calculateMinuteEndDate(e,t,n);if(n==-1&&r=="minute")return this._subtractMinuteDate(e,t,n);if(n==1&&r=="hour")return this._calculateHourEndDate(e,t,n);var i=this._addInterval(e,t,r,n,null);return i.end},_addInterval:function(e,t,r,n,i){for(var a=0,s=e;a<t&&!(i&&i(s));){var o=this._nextDate(s,r,n),c=new Date(o.valueOf()+1);n>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"),n=0,i=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&n<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>i&&(u=i,d=l+i*60*60);var f=Math.round((d-l)/3600);n+=f,i-=f,a.start=d}}var p=r;return n===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:n,end:p}},_calculateHourEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(n,t);i=a.added,n=a.end;var s=t-i;if(s){for(var o=n;i<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)),i+l>=t)break;i+=l,o=c}n=o}if(i<t){var s=t-i;a=this._addHoursUntilDayEnd(n,s),n=a.end}return n},_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"),n=0,i=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&n<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>i&&(u=i,d=l+i*60);var f=Math.round((d-l)/60);i-=f,n+=f,a.start=d}}var p=r;return n===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:n,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),n=0,i=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&&n<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>i&&(f=i,u=d-i*60);var p=Math.abs(Math.round((d-u)/60));i-=p,n+=p,s=u}}var h=r;return n===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:n,end:h}},_subtractMinuteDate:function(e,t,r){var n=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),i=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(n),s=this._subtractMinutesUntilHourStart(n,t);i+=s.added,n=s.end;for(var o=0,c=[],l=0;i<t;){var d=this.$gantt.date.day_start(new Date(n)),u=!1;n.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-i,h=this._getTimeOfDayStamp(n,u);if(!c.length||!l){n=this.$gantt.date.add(n,-1,"day");continue}if(c[c.length-1].end<=h&&p>l){i+=l,n=this.$gantt.date.add(n,-1,"day");continue}for(var g=!1,I=null,_=null,v=c.length-1;v>=0;v--)if(c[v].start<h-1&&c[v].end>=h-1){g=!0,I=c[v],_=c[v-1];break}if(g)if(h===I.end&&p>=I.durationMinutes)i+=I.durationMinutes,n=this.$gantt.date.add(n,-I.durationMinutes,"minute");else if(!a&&p<=h/60-I.startMinute)i+=p,n=this.$gantt.date.add(n,-p,"minute");else if(a)p<=h/60-I.startMinute?(i+=p,n=this.$gantt.date.add(n,-p,"minute")):(i+=h/60-I.startMinute,_?n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,_.end)):n=this.$gantt.date.day_start(n));else{var k=this._getMinutesPerHour(n);k<=p?(i+=k,n=this._nextDate(n,"hour",r)):(s=this._subtractMinutesUntilHourStart(n,p),i+=s.added,n=s.end)}else if(n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0){var m=this._getClosestWorkTimePast(n,"hour");if(m.valueOf()===n.valueOf()){var m=this.$gantt.date.add(n,-1,"day"),b=this._getWorkHours(m);if(b.length){var w=b[b.length-1];m.setUTCSeconds(w.durationSeconds)}}n=m}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var S=t-i;s=this._subtractMinutesUntilHourStart(n,S),i+=s.added,n=s.end}return n},_calculateMinuteEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(n,t);i+=a.added,n=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(n);i<t;){var d=this.$gantt.date.day_start(new Date(n)).valueOf();d!==s&&(o=this._getWorkHours(n),c=this._getMinutesPerDay(n),s=d);var u=t-i,f=this._getTimeOfDayStamp(n);if(!o.length||!c){n=this.$gantt.date.add(this.$gantt.date.day_start(n),1,"day");continue}if(o[0].start>=f&&u>=c){if(i+=c,u==c){n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,o[o.length-1].end));break}else n=this.$gantt.date.add(n,1,"day"),n=this.$gantt.date.day_start(n);continue}for(var p=!1,h=null,g=0;g<o.length;g++)if(o[g].start<=f&&o[g].end>f){p=!0,h=o[g];break}if(p)if(f===h.start&&u>=h.durationMinutes)i+=h.durationMinutes,n=this.$gantt.date.add(n,h.durationMinutes,"minute");else if(u<=h.endMinute-f/60)i+=u,n=this.$gantt.date.add(n,u,"minute");else{var I=this._getMinutesPerHour(n);I<=u?(i+=I,l?n=this.$gantt.date.add(n,I,"minute"):n=this._nextDate(n,"hour",r)):(a=this._addMinutesUntilHourEnd(n,u),i+=a.added,n=a.end)}else n=this._getClosestWorkTimeFuture(n,"hour")}if(i<t){var _=t-i;a=this._addMinutesUntilHourEnd(n,_),i+=a.added,n=a.end}return n},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 n=new Date(e);if(this._isWorkTime(n,t))return n;if(n=this.$gantt.date[t+"_start"](n),r=="any"||!r){var i=this._getClosestWorkTimeFuture(n,t),a=this._getClosestWorkTimePast(n,t);Math.abs(i-e)<=Math.abs(e-a)?n=i:n=a}else r=="past"?n=this._getClosestWorkTimePast(n,t):n=this._getClosestWorkTimeFuture(n,t);return n},_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 n=new Date(e),i=null,a=!1;this._getWorkHours(n).length||(n=this._getClosestWorkTime(n,"day",t<0?"past":"future"),t<0&&(n=new Date(n.valueOf()-1),a=!0),r=this._getWorkHours(n));var s=this._getTimeOfDayStamp(n);if(a&&(s=this._getTimeOfDayStamp(new Date(n.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,s));break}return i},_getClosestWorkMinute:function(e,t,r){var n=new Date(e),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i);return a||(r>0?(n=this.calculateEndDate(n,r,t),n=this.$gantt.date.day_start(n)):(n=this.calculateEndDate(n,r,"day"),n=this.$gantt.date.day_start(n),n=this.$gantt.date.add(n,1,"day"),n=new Date(n.valueOf()-1)),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i)),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 n=this._getUnitOrder(t),i=this.units[n-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(i&&!this._isWorkTime(a,i)&&(r>0?a=this._getClosestWorkTimeFuture(a,i):a=this._getClosestWorkTimePast(a,i),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 n in e.dates);var i=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=i: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 lr={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 n in e){r=n;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var n=t[r];if(e[r]){var i=n[e[r]];if(i)return i}}return null}};function Pm(){function e(i){return i.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(i,a){return a.mergeCalendars(i.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function n(i,a){var s=e(i);if(i.length){if(i.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(i,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:n}}var bm=Pm();function hl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=lr.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))}hl.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 n=0;n<7;n++)r[n]=t.weekdays[n];t?.dates&&Object.entries(t.dates).forEach(([n,i])=>{r[new Date(n).valueOf()]=i}),Object.entries(r).forEach(([n,i])=>{i instanceof Array||(r[n]=!!i)}),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 n=new pl,i;return e.forEach((function(a){i?i=this._createCalendarFromConfig(n.merge(i,a)):i=a}).bind(this)),this.createCalendar(i)},_createCalendarFromConfig:function(e){var t=new la(this.$gantt,fl(this.$gantt));t.id=String(ea());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var n in r.customWeeks)r.customWeeks[n]=this._convertWorkTimeSettings(r.customWeeks[n]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=_t(e.getConfig()):e.worktime?t=_t(e.worktime):t=_t(e);var r=_t(this.defaults.fulltime.worktime);return Ue(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,n,i;if(this._legacyConfig===!1?i=t.resource_property:i=lr.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=bm.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=lr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=lr.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(i&&e[i]&&t.resource_calendars[e[i]])var r=this.getResourceCalendar(e[i]);if(n&&(r=this.getCalendar(n)),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,n=r.resource_calendars,i=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),n){if(this._legacyConfig===void 0&&(this._legacyConfig=lr.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in n)if(n[a][t]){i=n[a][t];break}}else var i=n[t];if(i)return this.getCalendar(i)}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 n=this._getOwnCalendar(r),i=!!t.getState().group_mode;if(!n&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(n=this._getOwnCalendar(a),n))););i&&!n&&e.$effective_calendar&&(n=this.getCalendar(e.$effective_calendar))}return n||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||ea(),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],n=this.createCalendar(r);n.id=t,this.addCalendar(n)}},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 da(e,t){this.argumentsHelper=t,this.$gantt=e}da.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,n=e.unit,i=e.step;return this._calculateDuration(t,r,n,i)},_calculateDuration:function(e,t,r,n){var i=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)/(n*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=i.add(o,n,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(i.add(o,n,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,n=e.unit;return n?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof da},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,n=e.unit,i=e.step;return this.$gantt.date.add(t,i*r,n)}};function yl(e){this.$gantt=e.$gantt,this.argumentsHelper=fl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new da(this.$gantt,this.argumentsHelper)}yl.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,n){var i=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return n=this._getCalendar(i),n.isWorkTime(i)},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 Rm=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,n,i){return t.isWorkTime(r,n,i)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,n,i){return t.calculateDuration(r,n,i)},_hasDuration:function(r,n,i){return t.hasDuration(r,n,i)},calculateEndDate:function(r,n,i,a){return t.calculateEndDate(r,n,i,a)},mergeCalendars:mt(e.mergeCalendars,e),createCalendar:mt(e.createCalendar,e),addCalendar:mt(e.addCalendar,e),getCalendar:mt(e.getCalendar,e),getCalendars:mt(e.getCalendars,e),getResourceCalendar:mt(e.getResourceCalendar,e),getTaskCalendar:mt(e.getTaskCalendar,e),deleteCalendar:mt(e.deleteCalendar,e)}},Em={create:Rm};function ml(e){var t=new hl(e),r=new yl(t),n=Em.create(t,r);Ue(e,n)}var gl={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 vl(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||gl,templates:e.templates||{},getTask:e.getTask||function(n){return null},isTaskExists:e.isTaskExists||function(n){return!1},isSummaryTask:e.isSummaryTask||function(n){return!1},getState:function(){return{group_mode:!1}},callEvent:function(n,i){let a=e.onEvent;return a&&a(n,i),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:cl,mixin:Ue,copy:_t,assert:function(n,i){if(!n){if(e.throwOnAssert)throw new Error("[calendar] "+i);e.silent!==!0&&console.error("[calendar]",i)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(n){return n},r.date=ul(r),r.date.init(),ml(r),r}function Lm(e={}){let t=vl(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 Al={createCalendar:Lm};var GO=3600*1e3;function Sl(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:wm}=Al,dr="__replay_default__";function Om(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],n=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${n+1}:00`]:e}var Il={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Cl="__main_global__",Fm={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function kl(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 xm(e){let t={};if(Array.isArray(e.days))for(let n=0;n<e.days.length;n+=1)t[n]=e.days[n];if(e.dates)for(let[n,i]of Object.entries(e.dates))t[n]=i;let r={hours:Om(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Dl(e){let t=wm({config:{work_time:!0}});t.addCalendar({id:dr,worktime:Il}),t.addCalendar({id:Cl,worktime:Fm});let r=new Set(e.filter(d=>!kl(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>kl(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?xm(d.worktime):Il});let i=ol(t),a=i.getCalendar(dr),s=i.getCalendar(Cl);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([dr]);for(let d of n)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=i.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function Tl(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let n=e.getParent(r.id);return!n||e.getIncomingLinkIds(n.id).length===0?null:n.startDate},getDescendantIds(t){return Nm(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],n=e.getActivity(t);for(;n;){let i=n.parentId;if(i===null)break;let a=e.getActivity(i);if(!a)break;r.push(String(i)),n=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,cost:Number(i?.cost??0)}})}}}function Nm(e,t){let r=[],n=new ht;for(let i of e.getChildren(t))n.enqueue(i);for(;!n.isEmpty();){let i=n.dequeue();r.push(i);for(let a of e.getChildren(i))n.enqueue(a)}return r}var In=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map,progressFallbackBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let n=this._journal;n&&(n.before.has(t)||n.before.set(t,Nt(r)),n.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:Nt(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:_l(r)})}noteCorrelativeBefore(t,r){let n=this._journal;!n||n.correlativeBefore.has(t)||n.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let n=this._journal;if(!n)return;let i=Nt(r);n.scheduledBefore.has(t)||n.scheduledBefore.set(t,i),n.before.has(t)||n.before.set(t,i),n.dirty.add(t)}noteLinkField(t,r){let n=this._journal;!n||n.linkFieldCaptured.has(t)||(n.linkFieldCaptured.add(t),n.ops.push({kind:"link-field",linkId:t,before:_l(r)}))}noteProgressFallback(t,r){let n=this._journal;!n||n.progressFallbackBefore.has(t)||n.progressFallbackBefore.set(t,r)}};function _l(e){return{...e}}var Cn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Pl(t);return this.reader.getCalendar(r??dr)}getClosestWorkTime(t){let r=`${fa(t.task)}|${t.dir}|${t.date.getTime()}`;return ua(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:it.HOUR}))}calculateEndDate(t){let r=`${fa(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return ua(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${fa(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return ua(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 ua(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var Mm="__default__";function Pl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function fa(e){return Pl(e)??Mm}var kn=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 n=this.activities.get(t)?.parentId,i=0,a=this.activities.size;for(;n&&!L(n);){if(n===r)return!0;if(++i>a)return!1;n=this.activities.get(n)?.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 n=String(t),i=this._childrenByParent.get(n);i?i.push(r):this._childrenByParent.set(n,[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 n=String(r.parentId),i=this._childrenByParent.get(n)??[];i.push(r.id),this._childrenByParent.set(n,i)}let t=(r,n)=>{let i=this.activities.get(r),a=this.activities.get(n);return i&&a?gr(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Sn=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 je=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new In;_viewState=new Sn;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=R(t.calendars);for(let n of t.activities)this._activities.set(n.id,n);for(let n of t.links){let i={...n,freeSlackHours:n.freeSlackHours??null,isCritical:n.isCritical===!0};this._links.set(String(n.id),i),this._indexLink(i)}this._calendar=new Cn(Dl(this._calendarSnapshot)),this._flags=Bm(t),this._hierarchy=new kn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(Nt),links:this.getAllLinks().map(r=>({...r})),calendars:R(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(R(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([r,n])=>[r,new Date(n)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([r,n])=>[r,R(n)])),t._progressFallback=new Map(this._progressFallback),t._flags=R(this._flags),t._filterProjection=R(this._filterProjection),t}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=za(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,n]of this._activities)t(n,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)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,r){let n=String(t),i=this._progressFallback.get(n)??null;Object.is(i,r)||(this._writeCapture.noteProgressFallback(n,i),r===null?this._progressFallback.delete(n):this._progressFallback.set(n,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),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=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._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??bl}getIncomingLinkIds(t){return this._incoming.get(String(t))??bl}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,n){let i=this.getActivity(t);i&&(this._writeCapture.note(String(t),i),i[r]=n,ha(i,r),r===E.PARENT&&this._hierarchy.markDirty(),pa(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,n){let i=this.getActivity(t);if(i){if(!Object.hasOwn(i,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),i),Reflect.set(i,r,sl(r,n)),ha(i,r),r===E.PARENT&&this._hierarchy.markDirty(),pa(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let n=this.getActivity(t);if(!n)return;this._writeCapture.note(String(t),n);let i=!1;for(let a of Object.keys(r))Reflect.set(n,a,Reflect.get(r,a)),ha(n,a),a===E.PARENT&&(i=!0),pa(a)&&(this._cache.visualOrderIds=null);i&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r);let n={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),n),this._indexLink(n)}_indexLink(t){El(this._outgoing,String(t.source),t.id),El(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Rl(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),Rl(n,t.id))}setLinkField(t,r,n){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i[r]=n)}setLinkFieldDynamic(t,r,n){if(!Wm(r))return;let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),Reflect.set(i,r,n))}setLinkProplannerId(t,r){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n.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 n=String(t);this.setProgressFallback(n,null),(this._viewState.isChecked(n)||!this._viewState.isVisible(n))&&this._captureViewStateOnce(),this._viewState.forget(n),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:n,correlativeBefore:i,scheduledBefore:a,progressFallbackBefore:s}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(i),this._restoreActivityFields(a),this._restoreActivityFields(n),this._restoreProgressFallbacks(s),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,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()}_restoreProgressFallbacks(t){for(let[r,n]of t)n===null?this._progressFallback.delete(r):this._progressFallback.set(r,n)}_restoreCorrelatives(t){for(let[r,n]of t){let i=this._activities.get(r);i&&(i.correlativeId=n)}}_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,n]of t){let i=this._activities.get(r);i&&this._restoreScalarFields(i,n)}}_restoreScalarFields(t,r){for(let n of Object.keys(t))Object.hasOwn(r,n)||Reflect.deleteProperty(t,n);for(let n of Object.keys(r))Reflect.set(t,n,Reflect.get(r,n))}_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))}},bl=[];function Wm(e){return e===er.LAG||e===er.TYPE||e===er.FREE_SLACK_HOURS||e===er.IS_CRITICAL}function pa(e){return e===E.PARENT||e===E.CORRELATIVE_ID}function ha(e,t){t!==E.START_DATE&&t!==E.END_DATE&&t!==E.TYPE||(e.calendarDuration=Et(e))}function Rl(e,t){return e.filter(r=>String(r)!==String(t))}function El(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function Bm(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 Ll(e,t){let r=e.getActivity(t);return r?R(r):null}function wl(e){return e.getAllActivities().map(R)}function Ol(e){return e.getAllIds().map(String)}function Fl(e,t){e.forEachActivity((r,n)=>t(n))}function xl(e,t){let r=t==="0"?ya(e,"0"):e.getChildren(t),n=[];for(let i of r){let a=e.getActivity(i);a&&n.push(R(a))}return n.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),n}function ya(e,t){return gt(t,e)}function Nl(e){return e.checkedIds().map(String)}function Ml(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function ma(e,t){let r=e.getLink(t);return r?ft(r):null}function Wl(e){return e.getAllLinks().map(t=>ft(t))}function Dn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Um(e){return e.reduce((t,r)=>Dn(r)<Dn(t)?r:t)}function jm(e){return e.reduce((t,r)=>Dn(r)>Dn(t)?r:t)}function Hm(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Bl(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Hm(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:Um(n),endHour:jm(i)}}function Ul(e,t){return{calendars:e.calendarReader,hierarchy:Tl(e),activityReader:Sl(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function jl(e){return de(e)}var Vm=new Set(["freeSlackHours","isCritical"]);function Ym(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([n])=>!t.has(n)));return e.kind==="updated"&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function Kl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>Ym(i,Vm)).filter(i=>i!==null),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return R({...e,source:n,activities:t,links:r})}function ga(e,t,r,n,i,a,s){return{changeSet:e,beforeSnap:t,beforeLinks:Hl(r),afterSnap:n,afterLinks:Hl(i),progressFallbackBefore:a,progressFallbackAfter:s}}function Hl(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Gl(e,t){let r=new Map,n=new Map;for(let i of t.activities){if(i.kind!=="created")continue;let a=e.getActivity(String(i.id));a&&r.set(String(i.id),X(a))}for(let i of t.links){if(i.kind==="deleted")continue;let a=e.getLink(String(i.id));a&&n.set(String(i.id),{...a})}return{afterSnap:r,afterLinks:n}}function $l(e){return e.kind!=="inline-edit"||!sr.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Vl(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 zl(e,t){if(!Vl(e)||!Vl(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function ql(e,t){let r=e.changeSet.activities[0],n=t.changeSet.activities[0];if(!r||!n)return t;let i=r.fields??{},a=n.fields??{},s={};for(let c of new Set([...Object.keys(i),...Object.keys(a)])){let l=i[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...n,fields:s}]};return ga(o)}function Jl(e){return e.kind==="persistence-acknowledge"?"checkpoint-on-success":e.kind==="sir-sync"||e.kind==="calendar-reconcile"||e.kind==="activity-lookahead-sync"||e.kind==="baseline-apply"||e.kind==="ponderator-criterion-set"||e.kind==="status-criteria-set"||e.kind==="activity-clipboard-clear"||e.kind==="activity-copy"||e.kind==="selection-toggle"||e.kind==="selection-replace"||e.kind==="visibility-set"||e.kind==="filter-set"||e.kind==="sort-set"?"skip":"record"}function va(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 Aa(e,t,r){let n=[],i=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);n.push({id:o,kind:"updated",fields:Yl(s.fields,r),after:c?X(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);n.push({id:o,kind:"created",after:c?X(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.getActivity(o);n.push({id:o,kind:"created",after:c?X(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);i.push({id:o,kind:"updated",fields:Yl(s.fields,r),after:c?ft(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);i.push({id:o,kind:"created",after:c?ft(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.getLink(o);i.push({id:o,kind:"created",after:c?ft(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Km(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Yl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t==="before"?{before:R(n.after),after:R(n.before)}:{before:R(n.before),after:R(n.after)}]))}function Km(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 Ia(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Xl(e,t){Ql(e,t,"before")}function Zl(e,t){Ql(e,t,"after")}function Ql(e,t,r){let n=t.changeSet;for(let a of n.activities)if(a.kind==="updated"){if(!a.fields)continue;for(let[s,o]of Object.entries(a.fields))rt(e,a.id,s,r==="before"?o.before:o.after)}else if(a.kind==="deleted")if(r==="before"){let s=t.beforeSnap?.get(String(a.id));if(!s)throw new Error(`undo: missing beforeSnap for resurrecting activity ${a.id}`);e.addActivity(X(s))}else e.removeActivity(String(a.id));else if(r==="before")e.removeActivity(String(a.id));else{let s=t.afterSnap?.get(String(a.id));if(!s)throw new Error(`redo: missing afterSnap for re-creating activity ${a.id}`);e.addActivity(X(s))}for(let a of n.links)if(a.kind==="updated"){if(!a.fields)continue;if(Object.hasOwn(a.fields,"source")||Object.hasOwn(a.fields,"target")){let s=r==="before"?t.beforeLinks?.get(String(a.id)):t.afterLinks?.get(String(a.id));if(!s)throw new Error(`${r==="before"?"undo":"redo"}: missing link snapshot for ${a.id}`);e.removeLink(String(a.id)),e.addLink({...s});continue}for(let[s,o]of Object.entries(a.fields))ho(e,String(a.id),s,r==="before"?o.before:o.after)}else if(a.kind==="deleted")if(r==="before"){let s=t.beforeLinks?.get(String(a.id));if(!s)throw new Error(`undo: missing beforeLinks for re-adding link ${a.id}`);e.addLink(s)}else e.removeLink(String(a.id));else if(r==="before")e.removeLink(String(a.id));else{let s=t.afterLinks?.get(String(a.id));if(!s)throw new Error(`redo: missing afterLinks for re-creating link ${a.id}`);e.addLink(s)}for(let a of n.viewState??[])a.checked&&e.setChecked(a.activityId,r==="before"?a.checked.before:a.checked.after),a.visible&&e.setVisible(a.activityId,r==="before"?a.visible.before:a.visible.after);let i=r==="before"?t.progressFallbackBefore:t.progressFallbackAfter;for(let[a,s]of i??[])e.setProgressFallback(a,s)}var Gm=100,$m=600,Tn=class e{constructor(t=Gm){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...R(this.undoStack)),t.redoStack.push(...R(this.redoStack)),t.sequence=this.sequence,t._lastKey=this._lastKey,t._lastTime=this._lastTime,t}record(t,r=null,n=0){let i=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&n-this._lastTime<=$m&&i!==void 0&&zl(i.entry,t)?(i.entry=ql(i.entry,t),i.touchedAt=this.touch()):(this.undoStack.push({entry:t,touchedAt:this.touch()}),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=r,this._lastTime=n,this.redoStack.length=0}resetCoalesce(){this._lastKey=null}takeUndo(){return this.undoStack.pop()?.entry??null}takeRedo(){return this.redoStack.pop()?.entry??null}pushRedo(t){this.redoStack.push({entry:t,touchedAt:this.touch()})}pushUndo(t){this.undoStack.push({entry:t,touchedAt:this.touch()})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(t){this.removeEntriesThrough(this.undoStack,t),this.removeEntriesThrough(this.redoStack,t),this.resetCoalesce()}applyPersistedIdentities(t,r){let n=new Map(t.map(({id:a,proplannerId:s})=>[String(a),s])),i=new Map(r.map(({id:a,proplannerId:s})=>[String(a),s]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,n,i)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,r){let n=t.filter(({touchedAt:i})=>i>r);t.splice(0,t.length,...n)}withPersistedIdentities(t,r,n){let i=s=>s===void 0?void 0:new Map(Array.from(s,([o,c])=>[o,r.has(o)?{...c,proplannerId:r.get(o)}:c])),a=s=>s===void 0?void 0:new Map(Array.from(s,([o,c])=>[o,n.has(o)?{...c,proplannerId:n.get(o)}:c]));return{...t,beforeSnap:i(t.beforeSnap),afterSnap:i(t.afterSnap),beforeLinks:a(t.beforeLinks),afterLinks:a(t.afterLinks)}}};var zm=["parentId","correlativeId"];function ed(e,t){let r=new Set,n=i=>{let a=t(i);r.add(a===null?"0":String(a))};for(let i of e.activities){let a=String(i.id);if(i.kind==="created"){n(a);continue}if(i.kind==="deleted"){let c=i.fields;c&&"parentId"in c&&r.add(td(c.parentId?.before));continue}let s=i.fields;!s||!zm.some(c=>c in s)||(n(a),"parentId"in s&&r.add(td(s.parentId?.before)))}return r}function td(e){return e==null?"0":String(e)}function qm(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Jm(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function rd(e){return{id:String(e.id),worktime:Jm(e.worktime)}}function _n(e,t,r,n=[]){let i=t.map(qm),a=[...r.map(rd),...n.map(rd)];return{activities:[...e],links:i,calendars:a}}var nd={id:"ignored",proplannerId:"ignored",parentId:"tracked",name:"tracked",description:"tracked",type:"tracked",startDate:"tracked",endDate:"tracked",durationHours:"tracked",constraintType:"tracked",constraintDate:"tracked",autoScheduling:"tracked",calendarId:"tracked",assignedDefaultCalendar:"ignored",dateOrigin:"tracked",progress:"tracked",cost:"tracked",usedCost:"tracked",realCost:"tracked",workHours:"tracked",realWorkHours:"tracked",ponderator:"tracked",hasCustomPonderator:"tracked",correlativeId:"tracked",uniqueCorrelativeId:"tracked",customId:"tracked",subcontractId:"tracked",isLookahead:"tracked",hasLookaheadTasks:"ignored",newActivityIds:"tracked",hasNewActivities:"tracked",isNewActivity:"ignored",pendingRequestIds:"ignored",responsableIds:"tracked",tagIds:"tracked",baselinePoints:"ignored",baselineSnapshot:"ignored",recursiveDurationHours:"ignored",isCritical:"ignored",freeSlackHours:"ignored",calendarDuration:"ignored",expectedProgress:"ignored",expectedProgressBaseline:"ignored",status:"ignored",criticalPath:"ignored"},id=Object.keys(nd).filter(e=>nd[e]==="tracked"),ad=new Set(["startDate","endDate","constraintDate","dateOrigin"]),sd=new Set(["newActivityIds","responsableIds","tagIds"]);function od(e){let t=id.map(r=>[r,Xm(r,e[r])]);return Object.fromEntries(t)}function Xm(e,t){return ad.has(e)?t instanceof Date?new Date(t):null:sd.has(e)?Array.isArray(t)?[...t]:[]:t}function ur(e,t){return Ca(e,t).length>0}function Ca(e,t){return id.filter(r=>!Zm(r,e[r],t[r]))}function Zm(e,t,r){return ad.has(e)?Qm(t,r):sd.has(e)?tg(t,r):(t??null)===(r??null)}function Qm(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function tg(e,t){let r=new Set(Array.isArray(e)?e.map(String):[]),n=new Set(Array.isArray(t)?t.map(String):[]);if(r.size!==n.size)return!1;for(let i of r)if(!n.has(i))return!1;return!0}var cd={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},eg=Object.keys(cd).filter(e=>cd[e]==="tracked");function Pn(e,t){return eg.some(r=>e[r]!==t[r])}function ld(e,t){let r=new Map(e.map(n=>[String(n.id),n]));return t.filter(n=>{let i=r.get(String(n.id));return i?Pn(i,n):!1})}function Pt(e){if(e==null||e===0)return!1;if(!(typeof e=="number"&&Number.isSafeInteger(e)&&e>0))throw new Error(`invalid proplannerId ${String(e)}`);return!0}function dd(e,t){for(let r of e)Pt(r.proplannerId);for(let r of t)Pt(r.proplannerId)}var bn=class e{trackingEnabled;initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;constructor(t=!0){this.trackingEnabled=t}fork(){let t=new e(!1);t.initialized=this.initialized;for(let[r,n]of this.linksAtLastSave)t.linksAtLastSave.set(r,R(n));for(let[r,n]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,R(n));return t}init(t,r){if(this.trackingEnabled){dd(t,r),this.snapshotActivities(t),this.snapshotLinks(r);for(let n of t)if(n.assignedDefaultCalendar){let i=String(n.id);this.initialCalendarRepairIds.add(i),this.dirtyActivityIds.add(i)}this.initialized=!0}}acknowledge(t,r,n=[],i=[],a,s){if(!this.trackingEnabled)return;let o=new Map(n.map(({id:p,proplannerId:h})=>[String(p),h])),c=new Map(i.map(({id:p,proplannerId:h})=>[String(p),h])),l=t.map(p=>({...p,proplannerId:o.get(String(p.id))??p.proplannerId})),d=r.map(p=>{let h=c.get(String(p.id));return h===void 0?{...p}:{...p,proplannerId:h}});if(dd(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!a||!s)return;let u=new Map(a.map(p=>[String(p.id),p])),f=new Map(s.map(p=>[String(p.id),p]));for(let p of l){let h=String(p.id);this.activityIsDirty(h,u.get(h)??null)&&this.dirtyActivityIds.add(h)}for(let p of a){let h=String(p.id);this.activityIsDirty(h,p)&&this.dirtyActivityIds.add(h)}for(let p of d){let h=String(p.id);this.linkIsDirty(h,f.get(h)??null)&&this.dirtyLinkIds.add(h)}for(let p of s){let h=String(p.id);this.linkIsDirty(h,p)&&this.dirtyLinkIds.add(h)}}snapshotActivities(t){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){this.dirtyActivityIds.add(n);continue}let i=od(r);this.activitiesAtLastSave.set(String(r.id),{persistable:i,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),ur(r,i)&&this.dirtyActivityIds.add(n)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){this.dirtyLinkIds.add(n);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}}recordChanges(t,r,n,i){if(!(!this.trackingEnabled||!this.initialized)){for(let a of t){let s=String(a.id),o=n(s);this.activityIsDirty(s,o)?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s);this.linkIsDirty(s,o)?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}activityIsDirty(t,r){let n=this.activitiesAtLastSave.get(t);return r===null?n!==void 0:this.initialCalendarRepairIds.has(t)||!Pt(r.proplannerId)||n===void 0||ur(r,n.persistable)}linkIsDirty(t,r){let n=this.linksAtLastSave.get(t);return r===null?n!==void 0:!Pt(r.proplannerId)||n===void 0||Pn(n,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let n=t.map(i=>{let a=typeof i=="string"?i:String(i.id),s=r(a),o=this.activitiesAtLastSave.get(a);if(s===null||o===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof i=="string"||!!i.fields?.isLookahead,acknowledgesProgress:typeof i!="string"&&!!i.fields?.progress,current:s,saved:o}});for(let{activityId:i,acknowledgesLookahead:a,acknowledgesProgress:s,current:o,saved:c}of n){let l={...c.persistable,...a?{isLookahead:o.isLookahead}:{},...s?{progress:o.progress,autoScheduling:o.autoScheduling}:{}};this.activitiesAtLastSave.set(i,{...c,persistable:l}),this.initialCalendarRepairIds.has(i)||!Pt(o.proplannerId)||ur(o,l)?this.dirtyActivityIds.add(i):this.dirtyActivityIds.delete(i)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=this.activitiesAtLastSave.get(n);i&&t(n)===null&&r.push({...i.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=this.linksAtLastSave.get(n);i&&t(n)===null&&r.push({...i})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.activitiesAtLastSave.get(n);(a===void 0||this.initialCalendarRepairIds.has(n)||ur(i,a.persistable))&&r.push(i)}return r}modifiedActivityFields(t){let r=new Map;if(!this.trackingEnabled||!this.initialized)return r;for(let n of this.dirtyActivityIds){let i=t(n),a=this.activitiesAtLastSave.get(n);if(!i||!a)continue;let s=Ca(i,a.persistable);s.length>0&&r.set(n,s)}return r}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.linksAtLastSave.get(n);(a===void 0||Pn(a,i))&&r.push(i)}return r}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var ud=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var ka=[!1,!0,!0,!0,!0,!0,!1],fd=new Set(["1","true"]),Sa="DURATION",pd="asap",hd={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 yd(e,t){let r=[],n=e.map(a=>{let s=ug(a,t);return a.should_be_showed===!1&&r.push(s.id),s});pg(n);let i=new Set(n.map(a=>a.id));return hg(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function rg(e,t){if(!e)return null;let r=hd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),pd):r}function ng(e,t){let r=rg(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?Mt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function ig(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function ag(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 sg(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Da(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)sg(r)&&t.push(String(r.id));return t}function og(e){return e==="0"?null:String(e)}function cg(e){if(e==null)return null;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid activity proplannerId ${String(e)}`);return e}function lg(e,t){return typeof e.is_critical=="boolean"?e.is_critical:(t.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${e.unique_id}" received ${typeof e.is_critical}`)),!1)}function dg(e,t){return Array.isArray(e)?e.map(r=>yn(r,t)).filter(r=>r!==null):[]}function ug(e,t){let r=ig(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=ng(e,t.reporter),o=e.type==="milestone",c=Mt(e.start_date),l=o?c:Mt(e.end_date),d=o?0:Number(e.duration),u=lg(e,t.reporter);return{id:String(e.unique_id),proplannerId:cg(e.id),parentId:og(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:ne(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:ee(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:Mt(e.date_origin),progress:i,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:fg(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:ag(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Da(e.pendingRequests),responsableIds:Da(e.responsables),tagIds:Da(e.tags),baselinePoints:dg(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:ne(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Et({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function fg(e){return e.has_childs?null:e.custom_id}function pg(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function hg(e,t,r){for(let n of e)n.parentId!==null&&(t.has(n.parentId)||(r.warn(`[parseFromBackend] activity "${n.id}" references unknown parent "${n.parentId}" \u2014 re-parenting to root (null)`),n.parentId=null))}function Ad(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>gg(c,n)),o=(r??[]).map(c=>vg(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:mg(s)}}function mg(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Id(e,t){let r=Dg(e.working_days),{days:n,hours:i}=Sg(e,r),a=Ag(t.exceptionsSource,t.exceptionRange),s={days:n,hours:i};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 gg(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return Id(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function vg(e,t){return Id(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Ag(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=Ig(n.from_date,n.to_date,t);if(i.length===0)continue;let a=Cg(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function Ig(e,t,r){let n=md(e),i=md(t);if(n===null||i===null)return[];if(r&&(i<r.start||n>r.end))return[];let a=[],s=r?Math.max(n,r.start):n,o=r?Math.min(i,r.end):i;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function md(e){if(typeof e!="string")return null;let t=ud.exec(e.trim());if(!t)return null;let r=Number(t[1]),n=Number(t[2]),i=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(i)?Date.UTC(r,n-1,i):null}function Cg(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=kg(t);if(r.length>0)return r}}var gd=/^\d{1,2}:\d{2}$/;function kg(e){let t=[];for(let r of e){let n=Sd(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!Rn(o)&&!Rn(c)&&gd.test(o)&&gd.test(c)&&t.push(`${o}-${c}`);continue}let s=kd(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Cd),t}function vd(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[n,i]=r.split(":");return(Number(n)||0)*60+(Number(i)||0)}function Cd(e,t){return vd(e)-vd(t)}function Sg(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=kd(l,d);for(let f=0;f<7;f+=1){let p=u[f],h=r[f];p&&h&&h.push(p)}},i=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(i)for(let l of e.shifts){let d=Sd(l?.shift_string);d&&n(d.startsCsv,d.endsCsv)}else a&&n(e.shift_start,e.shift_end);for(let l of r)l.sort(Cd);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 kd(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let n=e.split(",").map(o=>o.trim()),i=t.split(",").map(o=>o.trim());if(!(n.length===i.length&&n.length>0&&n.length<=7))return r;let s=[...r];for(let o=0;o<n.length;o+=1){let c=n[o],l=i[o];Rn(c)||Rn(l)||(s[o]=`${c}-${l}`)}return s}function Sd(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 Dg(e){if(typeof e!="string")return[...ka];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...ka]:t.map(r=>fd.has(r))}var Tg=new Set(["false","null"]);function Rn(e){return!e||Tg.has(e)}function _g(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Pg(e){if(typeof e!="string")return null;let t=Ps(e);return t||(_g(e)?e:null)}function bg(e){if(e==null)return;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid link proplannerId ${String(e)}`);return e}function Td(e,t){let r=[];for(let n of e)try{r.push(Rg(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return Eg(r)}function Rg(e,t,r){let n=String(e.unique_id??e.id),i=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(i))throw new Error(`[parseFromBackend] link "${n}" source "${i}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${n}" target "${a}" does not exist`);let s=Pg(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${n}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=bg(e.id);return{id:n,source:i,target:a,type:s,lag:vt(Number(e.lag??0),r),freeSlackHours:null,isCritical:!1,...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function Eg(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||Dd(r)>Dd(i))&&t.set(n,r)}return[...t.values()]}function Dd(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Lg(e){if(typeof e!="string")return Sa;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Sa}}function wg(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function Og(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function _d(e){let t=wg(e),r=Og(e),n=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}:{},...n?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:Lg(e.activity_creter),statusCriteria:hi,ganttId:null}}function En(e,t=De){let r=_d(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=Ad(e.calendars,e.sector.calendars,e.baseCalendars,Fg(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=yd(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=Td(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function Fg(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 n=new Date(t),i=new Date(r);return n.setFullYear(n.getFullYear()-1),i.setFullYear(i.getFullYear()+1),{start:n.getTime(),end:i.getTime()}}function _a(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{fork(){return _a({seed:t})},next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function Pa(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{fork(){return Pa({seed:t})},next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function ba(e={}){let t=e.seed??0,r=n=>{Number.isFinite(n)&&n>0&&n<=9999999&&n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){if(n==null)continue;let i=typeof n=="number"?n:Number(n);r(i)}return{fork(){return ba({seed:t})},next(){return t+=1,String(t)},bump(n){if(n==null)return;let i=typeof n=="number"?n:Number(n);r(i)},snapshot(){return t},restore(n){t=n}}}function Pd(e){return!!e&&typeof e=="string"&&e.trim().length>0}function Ln(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function wn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function bd(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Rd(e,t){return!t&&Pd(e)}function Ed(e,t){return t&&Pd(e)}function fr(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function On(e){if(!fr(e))return 0n;try{return BigInt(e)}catch{return 0n}}function xg(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!fr(t))return r;let n=t.length;return r.padStart(n,"0")}function Ct(e,t){let r=On(e),n=On(t),i=r+n;return xg(i,e)}function Fn(e,t){let r=On(e),n=On(t);return r<n?-1:r>n?1:0}function xn(e,t){return Fn(e,t)<=0?e:t}function Nn(e,t){return Fn(e,t)>=0?e:t}function Ld(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>xn(t,r))}function wd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Nn(t,r))}function Od(e){return{prefix:e,baseSuffix:null}}function Fd(e,t){let r=wn(e);return{prefix:Ln(e),baseSuffix:Ct(r,t)}}function xd(e){return{prefix:e,baseSuffix:null}}function Nd(e,t){return Rd(e,t)?"parentConversion":Ed(e,t)?"pasteReference":"noContext"}function Md(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Mn=class e{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[n,i]of t)i===null?this.prefixMap.delete(n):this.prefixMap.set(n,i);for(let n of[...r].reverse())n.hadId?this.processedIds.add(n.customId):this.processedIds.delete(n.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 n=this.prefixMap.get(r);this._journalPrefixBefore.set(r,n?Md(n):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 n=Array.from(r.usedSuffixes);r.min=Ld(n),r.max=wd(n),r.quantity=n.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}fork(){let t=new e({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[r,n]of this.prefixMap)t.prefixMap.set(r,Md(n));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return Ln(t)}extractSuffix(t){return wn(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 n=this.prefixMap.get(t);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=xn(r,n.min),n.max=Nn(r,n.max),n.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let n=this.getNextAvailableSuffix(t);r.next=n??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:n}=this.analyzeCustomId(t);if(!r&&!n)return{prefix:r,suffix:n};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let i=this.prefixMap.get(r);i.usedSuffixes.has(n)||(i.usedSuffixes.add(n),i.min=xn(n,i.min),i.max=Nn(n,i.max),i.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:n,max:n,next:Ct(n,this.suffixIncrement),quantity:1,usedSuffixes:new Set([n])});return this.processedIds.add(t),{prefix:r,suffix:n}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:n}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:n};this._noteCustomIdBefore(t);let i=this.prefixMap.get(r);return i.usedSuffixes.has(n)&&(i.usedSuffixes.delete(n),i.quantity-=1,i.usedSuffixes.size===0?this.prefixMap.delete(r):i.boundsDirty=!0),this.processedIds.delete(t),{prefix:r,suffix:n}}trackCustomIdChange(t,r){let n=this.releaseCustomId(t),i=this.registerCustomId(r);return{oldPrefix:n.prefix,oldSuffix:n.suffix,newPrefix:i.prefix,newSuffix:i.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}${Ct(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let n=r&&fr(r)?r:this.suffixIncrement;return`${t}${n}`.length>20?null:n}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),n=this.suffixIncrement;for(;Fn(n,r.max)<0;){if(`${t}${n}`.length>20)return null;if(!r.usedSuffixes.has(n))return n;n=Ct(n,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 n=this.prefixMap.get(t),i=this.suffixIncrement;if(!r||!fr(r)){let o=Ct(n.max,i);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(!n.usedSuffixes.has(a))return a;a=Ct(a,i)}let s=Ct(n.max,i);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 i=this.prefixMap.get(t),a=0;for(;i.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,Ct(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let n=`${t}${r}`;return this._exceedsMaxLength(n)&&(n=this._generateDefaultCustomId()),n}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(n=>n&&typeof n.customId=="string"&&n.customId).map(n=>n.customId))];for(let n of r){if(this.processedIds.has(n))continue;let{prefix:i,suffix:a}=this.analyzeCustomId(n);(i||a)&&(this._updatePrefixStats(i,a),this.processedIds.add(n))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:n=!1}=t,i=bd(r),a=Nd(i,n),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,i),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){this._ensureFreshBounds(s);let f=this.prefixMap.get(s).max;c=Ct(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(i);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 Od(this.defaultPrefix);case"pasteReference":return Fd(r,this.suffixIncrement);default:return xd(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let n=t.trim();if(n.length>0){let i=this.extractPrefix(n),a=this.extractSuffix(n),s=Ct(a,this.suffixIncrement),o=this.getNextAvailableSuffix(i,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${i}${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 n=t.trim();return r&&n===r.trim()?!1:this.processedIds.has(n)}};var Ng=1,Mg=-1;function Wg(e,t){return!e&&!t?null:e&&t?0:e?Ng:Mg}function Wd(e){return e==null}function Bd(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Bg(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 Ug(e,t){let r=Bt(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=Wg(Wd(a),Wd(s));if(o!==null)return o;let c=r.valueKind==="enum"?Bd(a,r.order)-Bd(s,r.order):Bg(a,s,t.locale);return e.direction==="desc"?-c:c}}function Ud(e,t){let r=e.rules.map(n=>Ug(n,t)).filter(n=>n!==null);return r.length===0?null:(n,i)=>{for(let a of r){let s=a(n,i);if(s!==0)return s}return 0}}function jd(e){let t=[];e.forEachActivity((r,n)=>{r.type==="project"&&e.getChildren(String(n)).length===0&&t.push(String(n))});for(let r of t)e.setActivityField(r,E.TYPE,Se),jg(e,r)}function jg(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let n=new Date(r.startDate);n.setUTCHours(0,0,0,0);let i=e.getClosestWorkTime({date:n,dir:Z.FUTURE,task:r});if(i.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:i,durationHours:r.durationHours,task:r});e.setActivityField(t,E.START_DATE,i),e.setActivityField(t,E.END_DATE,a)}function Hd(e){let t=[],r=[];e.forEachActivity((i,a)=>{i.parentId===null&&t.push(String(a))});let n=i=>{let a=e.getActivity(i);if(!a)return 0;let s=[...e.getChildren(i)],o=s.length===0?dt(a.workHours,a.progress):s.reduce((c,l)=>c+n(String(l)),0);return e.setActivityField(i,E.REAL_WORK_HOURS,o),r.push(i),o};for(let i of t)n(i);return r}async function Vd(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(ot(t),r.updateDurationForPrimaveraEndDate&&Vg(t),Yg(t),Hd(t),i){Xe(t),a&&(oe(t,a),Wt(t,r.statusCriteria));return}let s=await n.schedule({});Ge(t,s),Kg(t),Hg(t),await _e(t,void 0,!1),Xe(t),a&&(oe(t,a),Wt(t,r.statusCriteria))}function Hg(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}),t.calendarDuration=Et(t))})}function Vg(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Yg(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let n=t.constraintDate;if(t.type==="milestone"&&(n.getUTCHours()!==0||n.getUTCMinutes()!==0))return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=xt(t.constraintDate,i,r))})}function Kg(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=xt(t.constraintDate,n,r))})}var bt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Yd(e){let t=e.clock??null,r=t?.()??null,n=r?Ur(r):null,i=e.reporter??De,a=En({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=zr(e.statusCriteria),s.ganttId=e.ganttId??null;let o=a.calendars,c=a.baseCalendars??[],l=_n(a.activities,a.links,a.calendars,c),d=v=>Ud(v,te(s.hoursPerDay)),u=new je(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new Te(u,i);jd(u);let p=_a({knownIds:a.activities.map(v=>v.id)}),h=Pa({seed:r?.getTime()??0,knownIds:a.links.map(v=>v.id)}),g=ba({knownIds:a.activities.map(v=>v.uniqueCorrelativeId)}),I=new Mn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(I.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let v=c.find(k=>k.baseDefault)?.id??null;mn(u,e.baselinePoints,n,i,v)}let _=Vd({state:u,sector:s,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:n??void 0});return{sector:s,state:u,scheduler:f,activityIdGen:p,linkIdGen:h,uidGen:g,customIdTracker:I,calendars:o,baseCalendars:c,clock:t,reporter:i,initPromise:_}}function He(e){if(e===void 0)return["undefined"];if(e===null)return["null"];if(typeof e=="string")return["string",e];if(typeof e=="boolean")return["boolean",e];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="bigint")return["bigint",String(e)];if(e instanceof Date)return["date",String(e.getTime())];if(Array.isArray(e))return["array",e.map(He)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[He(t),He(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,He).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,He(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function he(e){return JSON.stringify(He(e))}function Ra(e,t){let r=new Map(e.map(s=>[String(s.id),s])),n=new Map(t.map(s=>[String(s.id),s])),i=[...new Set([...r.keys(),...n.keys()])].sort(),a=[];for(let s of i){let o=n.get(s),c=r.get(s);if(c===void 0){a.push({id:s,kind:"deleted",after:null});continue}if(o===void 0){a.push({id:s,kind:"created",after:R(c)});continue}let l=Gg(o,c);Object.keys(l).length>0&&a.push({id:s,kind:"updated",fields:l,after:R(c)})}return a}function Gg(e,t){let r={},n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let i of n)he(e[i])!==he(t[i])&&(r[i]={before:R(e[i]),after:R(t[i])});return r}function $g(e,t){let r=new Set(t.selectedIds.map(String)),n=new Set(e.selectedIds.map(String)),i=new Set(t.hiddenIds.map(String)),a=new Set(e.hiddenIds.map(String)),s=e.activities.map(({id:c})=>String(c)).sort(),o=[];for(let c of s){let l=r.has(c),d=n.has(c),u=!i.has(c),f=!a.has(c);l===d&&u===f||o.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===f?{}:{visible:{before:u,after:f}}})}return o}function Kd(e,t){let r=he(e.order)!==he(t.order);return{source:{kind:"init"},activities:Ra(e.activities,t.activities),links:Ra(e.links,t.links),calendars:Ra(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:$g(e,t),...r?{order:R(e.order)}:{}}}var zg=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Ea=(e,t)=>e===null?t:Math.min(e,t),La=(e,t)=>e===null?t:Math.max(e,t);function $d(e,t,r){let n=[...new Set(t.kind==="move"?t.activityIds.map(String):[String(t.activityId)])];if(n.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let i=qg(e,t,n);return Jg(e,n,i),{getDates(a,s){if(r(),!Number.isFinite(s))throw new Error("[ScheduleCore] invalid date gesture edge");let o=i.get(String(a));if(!o)return null;let c=Zg(o,s),l=Qg(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function qg(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Gd(e,i);if(i!==null&&!r.includes(i))throw new Error("[ScheduleCore] move anchor is not a participant");for(let s of r){let o=Gd(e,s);if(t.kind==="move"){let c=a.startDate.getTime();n.set(s,{constantStart:null,variableStartOffset:o.startDate.getTime()-c,constantEnd:null,variableEndOffset:o.endDate.getTime()-c})}else t.kind==="resize-start"?n.set(s,{constantStart:null,variableStartOffset:0,constantEnd:o.endDate.getTime(),variableEndOffset:null}):n.set(s,{constantStart:o.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return n}function Jg(e,t,r){let n=Ze(e,new Set(t));for(let i of n){let a=zg();for(let s of e.getChildren(i)){let o=r.get(s);if(o){Xg(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=Ea(a.constantStart,c.startDate.getTime()),a.constantEnd=La(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Gd(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function Xg(e,t){t.constantStart!==null&&(e.constantStart=Ea(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Ea(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=La(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=La(e.variableEndOffset,t.variableEndOffset))}function Zg(e,t){if(e.variableStartOffset===null)return e.constantStart;let r=t+e.variableStartOffset;return e.constantStart===null?r:Math.min(e.constantStart,r)}function Qg(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}var wa=Symbol("ScheduleCore.fork.source");function tv(e){return e.kind==="persistence-acknowledge"||e.kind==="activity-lookahead-sync"&&e.acknowledgePersistedLookahead===!0}function ev(e){for(let t of e.activities)if(t.kind==="deleted"||t.kind==="updated"&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function rv(e,t){let r=[];for(let n of e.activities){let i=t.getActivity(n.id);if(i===null)return null;r.push(i)}return r}function nv(e,t,r){if(e===null||e.filter!==t)return!1;let n=e.context.hoursPerDay===r.hoursPerDay,i=e.context.locale===r.locale;return n&&i}var Wn=class e{_activityClipboard={value:null};_status=bt.READY;coreRuntime;_isFork;_undo=new Tn;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(wa in t){this._isFork=!0;let i=t[wa],a=i.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new Te(a,i.coreRuntime.reporter),sector:R(i.coreRuntime.sector),activityIdGenerator:i.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:i.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:i.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:i.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(i.coreRuntime.calendars,([s,o])=>[s,R(o)])),baseCalendars:R(i.coreRuntime.baseCalendars),clock:i.coreRuntime.clock,reporter:i.coreRuntime.reporter},this._activityClipboard.value=R(i._activityClipboard.value),this._undo=i._undo.fork(),this._saveTracker=i._saveTracker.fork(),this._scheduleRevision=i._scheduleRevision,this._pendingScheduleRevision=i._scheduleRevision,this._criticalPathRevision=i._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let r=Yd(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(i=>[i.id,i])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==bt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let n=t.criticalPathOnLoad===!0;this._ready=n?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[wa]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return R(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Ll(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return $d(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),wl(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=hn(t.map(n=>String(n)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(n=>String(n.newParentId)))]}getChildrenView(t){return this.assertReady(),xl(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ma(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,n=[],i=new Set,a=s=>{if(i.has(s))return;i.add(s);let o=ma(r,s);o&&n.push(o)};for(let s of r.getOutgoingLinkIds(t))a(s);for(let s of r.getIncomingLinkIds(t))a(s);return n}getAllLinksView(){return this.assertReady(),Wl(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),n=ze(t,r),i=br(n),a=0;for(let s of i)s.length>a&&(a=s.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:n.length,circularComponents:i,largestComponentSize:a}}getProperty(t,r){this.assertReady();let n=this.coreRuntime.state.getActivity(t);return n?R(n[r]):null}getAllIds(){return this.assertReady(),Ol(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Fl(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),ya(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Nl(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let t=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(r=>!t.has(r))}getActiveFilter(){return this.assertReady(),R(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),R(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),Ml(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?R(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>R(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>R(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Bl(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(R)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(R)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(R)}getModifiedActivityFields(){return this.assertReady(),R(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(R)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}getCanonicalDigest(){this.assertReady();let t=(r,n)=>String(r.id).localeCompare(String(n.id));return he({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(t),links:[...this.getAllLinksView()].sort(t),calendars:[...this.getAllCalendars()].sort(t),baseCalendars:[...this.getBaseCalendars()].sort(t)})}createProjectionChangeSetFrom(t){this.assertReady(),t.assertReady();let r=n=>({activities:n.getAllActivitiesView(),links:n.getAllLinksView(),calendars:n.getAllCalendars(),selectedIds:n.getSelectedActivityIds(),hiddenIds:n.getHiddenActivityIds(),order:Ie(n.coreRuntime.state)});return Kd(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(R)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(R)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return ji(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,r){t&&(r||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",n)})))}async dispatch(t,r={}){let n=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async applyActivityBatch(t,r={}){let n=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async _dispatchInner(t,r={},n=!1){let i=!1;try{let a=await this._runDispatch(t,r);return i=a.changedState,a.result}finally{this._settleScheduleMutation(n,i)}}async _runDispatch(t,r){if(this.assertReady(),this._isFork&&tv(t))return{result:{ok:!1,reason:C.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=Ul(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),i=Jl(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,o;try{s=await al(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:l=>this._saveTracker.hasCheckpointActivityId(l),isLinkIdReserved:l=>this._saveTracker.hasCheckpointLinkId(l),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(l=>l.baseDefault)?.id??null,now:this.coreRuntime.clock?Ur(this.coreRuntime.clock()):null});let c=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;c&&c.size>0&&(o=new Map(c)),s.ok||this._rollback(a)}catch(c){throw this._rollback(a),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&i==="record"&&Ia(s.changes)){let c=Gl(this.coreRuntime.state,s.changes),l=o?new Map(Array.from(o.keys(),d=>[d,this.coreRuntime.state.getProgressFallback(d)])):void 0;this._undo.record(ga(Kl(s.changes),s.__beforeSnap,s.__beforeLinks,c.afterSnap,c.afterLinks,o,l),$l(t),Date.now())}if(s.ok)if(i==="checkpoint-on-success"){if(t.kind!=="persistence-acknowledge")throw new Error("checkpoint-on-success requires persistence acknowledge");let c=this.coreRuntime.state.getAllActivities(),l=this.coreRuntime.state.getAllLinks(),d=t.checkpoint,u=d?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(d?.activities??c,d?.links??l,t.activities,t.links,c,l),this._undo.discardThrough(u),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,c=>this.coreRuntime.state.getActivity(c)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,c=>this.coreRuntime.state.getActivity(c),c=>this.coreRuntime.state.getLink(c));return s=this._withReappliedViewState(t,s),s.ok?ji(t)&&Ia(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&de(t)),{result:zd(s),changedState:!0}):{result:zd(s),changedState:!1}:{result:s,changedState:!1}}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._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind==="visibility-set"&&this.coreRuntime.state.setFilterProjection(null),!Jo(t)))return r;let n=this._reapplyViewState(r.changes);return n===null?r:{...r,changes:n}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),n=this._emitTouchedBranchOrder(r??t);return this._reapplyActiveOrder(n.changes??r??t,n.touchedParents)??n.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=ed(t,a=>r.getParentId(a));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:n};if(n.size===0)return{changes:null,touchedParents:n};let i=$n(r,n);return i.length===0?{changes:null,touchedParents:n}:{changes:{...t,order:i},touchedParents:n}}_reapplyActiveOrder(t,r){let n=this.coreRuntime.state;if(n.getActiveOrder()===null)return null;if(n.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:Ie(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:Ie(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=$n(n,a);return s.length===0?null:{...t,order:s}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,n=r.getActiveFilter();if(n===null)return null;let i=te(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),s=nv(a,n,i),o=ev(t)?null:rv(t,r),c,l;if(o===null||!s){let f=mr({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:n,context:i});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=Ha(a,o,f=>r.getParentId(f)),l=a.visibleIds;let u=Ae(r,l,c);return u.length===0?null:{...t,viewState:[...t.viewState??[],...u]}}_recordScheduleMutation(t){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===bt.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},n=new je(_n(this.coreRuntime.state.getAllActivities().map(o=>X(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),i=()=>!r.cancelled&&this._status!==bt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let o=await Bi(n,this.coreRuntime.sector.hoursPerDay,i);return!i()||o===null?null:this._enqueue(async()=>{if(!i())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{for(let[l,d]of o.activities)Mi(this.coreRuntime.state,l,d);for(let[l,d]of o.links)Wi(this.coreRuntime.state,l,d);c=await W(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(l){throw this._rollback(),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:c}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let s=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(s,s),a}undo(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runUndo(t,a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),i}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let n=this._undo.takeUndo();if(!n)return null;Xl(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),va(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=Aa(this.coreRuntime.state,n,"before");return this._saveTracker.recordChanges(i.activities,i.links,a=>this.coreRuntime.state.getActivity(a),a=>this.coreRuntime.state.getLink(a)),this._reapplyViewState(i)??i}}redo(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runRedo(a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",s)})},()=>{}),i}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;Zl(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),va(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=Aa(this.coreRuntime.state,r,"after");return this._saveTracker.recordChanges(n.activities,n.links,i=>this.coreRuntime.state.getActivity(i),i=>this.coreRuntime.state.getLink(i)),this._reapplyViewState(n)??n}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=bt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new bn;assertReady(){if(this._status===bt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===bt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),t&&(this.coreRuntime.activityIdGenerator.restore(t[0]),this.coreRuntime.linkIdGenerator.restore(t[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(t[2]))}catch(r){throw this._status=bt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function zd(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var qd=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Jd={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 Xd=8;var K={ACTIVITY_CLIPBOARD_CLEAR:"activity-clipboard-clear",ACTIVITY_COPY:"activity-copy",CALENDAR_RECONCILE:"calendar-reconcile",ACTIVITY_PASTE_COPIED:"activity-paste-copied",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",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"},iv={[K.ACTIVITY_CLIPBOARD_CLEAR]:!0,[K.ACTIVITY_COPY]:!0,[K.CALENDAR_RECONCILE]:!0,[K.ACTIVITY_PASTE_COPIED]:!0,[K.PERSISTENCE_ACKNOWLEDGE]:!0,[K.BASELINE_APPLY]:!0,[K.PONDERATOR_CRITERION_SET]:!0,[K.STATUS_CRITERIA_SET]:!0,[K.INLINE_EDIT]:!0,[K.DATES_BATCH]:!0,[K.BULK_EDIT]:!0,[K.LINK_CREATE]:!0,[K.LINK_UPDATE]:!0,[K.LINK_DELETE]:!0,[K.LINKS_BATCH]:!0,[K.ACTIVITY_CREATE]:!0,[K.ACTIVITY_DELETE]:!0,[K.ACTIVITY_MOVE]:!0,[K.ACTIVITY_INDENT]:!0,[K.ACTIVITY_OUTDENT]:!0,[K.ACTIVITY_SET_PROGRESS]:!0,[K.SELECTION_TOGGLE]:!0,[K.SELECTION_REPLACE]:!0,[K.VISIBILITY_SET]:!0,[K.FILTER_SET]:!0,[K.SORT_SET]:!0,[K.SIR_SYNC]:!0,[K.ACTIVITY_LOOKAHEAD_SYNC]:!0},Zd=Object.keys(iv);var Qd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return su(av);})();
1
+ "use strict";var ScheduleCore=(()=>{var fn=Object.defineProperty;var Ou=Object.getOwnPropertyDescriptor;var bu=Object.getOwnPropertyNames;var Nu=Object.prototype.hasOwnProperty;var wu=(e,t)=>{for(var r in t)fn(e,r,{get:t[r],enumerable:!0})},Fu=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of bu(t))!Nu.call(e,n)&&n!==r&&fn(e,n,{get:()=>t[n],enumerable:!(i=Ou(t,n))||i.enumerable});return e};var xu=e=>Fu(fn({},"__esModule",{value:!0}),e);var $A={};wu($A,{ACTIVITY_BATCH_ACTION_KIND:()=>Fr,ACTIVITY_BATCH_MODE:()=>ot,ACTIVITY_DATE_EDGE:()=>sr,ACTIVITY_FIELD:()=>lt,ACTIVITY_PONDERATOR_CRITERION:()=>dt,ACTIVITY_TYPE:()=>Dt,CALENDAR_UNIT:()=>pt,CHANGE_SET_SOURCE_KIND:()=>Gt,COLUMN:()=>S,COMPLETED_PROGRESS:()=>ur,CONSTRAINT_TYPE:()=>H,CONSTRAINT_TYPE_TO_LABEL:()=>Eu,CONSTRAINT_WARNING_KIND:()=>yi,CREATION_KIND:()=>Pu,DATE_GESTURE_KIND:()=>nr,DEFAULT_HOURS_PER_DAY:()=>Ru,DISPATCH_ACTION_KIND:()=>P,DISPATCH_ACTION_KINDS:()=>po,DISPATCH_LINK_OPERATION_KIND:()=>tt,DISPATCH_TRACK_EVENT:()=>Ot,FILTER_FIELD:()=>B,FILTER_LOGIC:()=>Ur,FILTER_OPERATOR:()=>w,FILTER_REJECTION_REASON:()=>ft,FILTER_VALUE_KIND:()=>E,LINK_BATCH_OPERATION_KIND:()=>Ne,LINK_CODE_TO_TYPE:()=>me,LINK_REJECTION_REASON:()=>ut,LINK_RELATIONSHIP:()=>fe,LINK_TYPE:()=>U,LINK_TYPE_CODE:()=>es,NEW_ACTIVITY_DEFAULTS:()=>bi,NOT_STARTED_PROGRESS:()=>jo,ORDER_DIRECTION:()=>ye,REJECTION_REASON:()=>v,ROOT_PARENT_ID:()=>x,SCHEDULE_CORE_STATUS:()=>Bt,SCHEDULE_EFFECT_KIND:()=>fi,SIR_AUTO_REJECT_REASON:()=>pi,STATUS:()=>mt,STATUS_CRITERIA:()=>Jt,ScheduleCore:()=>ar,WORK_TIME_DIRECTION:()=>rt,checkNoUpdatedLinks:()=>Ud,computeExpectedProgress:()=>Hn,createSchedule:()=>Du,expectedProgressFromBaseline:()=>$e,getActiveBaseline:()=>gt,getUnsavedActivities:()=>_u,isRootParent:()=>N,normalizeParentKey:()=>Qt,parseFromBackend:()=>nn,willRunCriticalPath:()=>md,yieldToBrowser:()=>it});var rt={FUTURE:"future",PAST:"past"},pt={HOUR:"hour",DAY:"day"},dt={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},Jt={BASELINE:"Baseline",ACTUAL:"Actual"},mt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var H={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Mu={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 co(e,t,r){if(!t)return{violated:!1};let i=Mu[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Uu=new Set(["mso","snet","snlt"]);function or(e,t,r){return Uu.has(e)?t:r}function lo(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Bu={snet:{startOfDay:!0,direction:rt.FUTURE},snlt:{startOfDay:!0,direction:rt.PAST},fnet:{startOfDay:!1,direction:rt.FUTURE},fnlt:{startOfDay:!1,direction:rt.PAST},mso:{startOfDay:!0,direction:rt.FUTURE},mfo:{startOfDay:!1,direction:rt.PAST}},wr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),so=(e,t)=>new Date(e.getTime()+t*864e5),Wu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function pn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Bu[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:wr(i),dir:rt.FUTURE,task:e});if(Wu(n,i))return i.getTime()!==wr(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:so(wr(i),1),dir:rt.PAST,task:e});let a=wr(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:rt.FUTURE,task:e}):t.getClosestWorkTime({date:so(a,1),dir:rt.PAST,task:e})}function uo(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=pn(e,t);if(!n)return r;let a=s=>t.calculateEndDate({startDate:s,durationHours:e.durationHours,task:e}),o=s=>t.calculateEndDate({startDate:s,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:o(n),latestStart:null,earliestEnd:n,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:o(n),earliestEnd:null,latestEnd:n};case"mso":{let s=a(n);return{earliestStart:n,latestStart:n,earliestEnd:s,latestEnd:s}}case"mfo":{let s=o(n);return{earliestStart:s,latestStart:s,earliestEnd:n,latestEnd:n}}default:return r}}function fo(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function yn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var U={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Hu={TEXT:"text",DESCRIPTION:"description",DURATION:"duration",PROGRESS:"progress",COST:"cost",USED_COST:"used_cost",HH_WORK_TIME:"hhWorkTime",START_DATE:"start_date",END_DATE:"end_date",CONSTRAINT_TYPE:"constraint_type",CONSTRAINT_DATE:"constraint_date",CALENDAR_ID:"calendar_id",CUSTOM_ID:"custom_id",SUBCONTRACT_ID:"subcontractId",RESPONSABLES:"responsables",TAGS:"tags",CUSTOM_PREDECESSORS:"custom_predecessors",CUSTOM_SUCESSORS:"custom_sucessors"},ju={REAL_WORK:"real_work",REAL_COST:"real_cost",EXPECTED_PROGRESS:"expected_progress",EXPECTED_PROGRESS_BASE:"expected_progress_base",START_BASE:"start_base",END_BASE:"end_base",DURATION_BASE:"duration_base",COST_BASE:"cost_base",WORK_BASE:"work_base",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"is_critical",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",FREE_SLACK:"freeSlack",TOTAL_SLACK:"totalSlack",CORRELATIVE_ID:"correlative_id",UNIQUE_CORRELATIVE_ID:"unique_correlative_id",PONDERATOR:"ponderator",STATUS:"status"},S={...Hu,...ju};var be={CREATE:"create",UPDATE:"update",DELETE:"delete"},ut={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var P={ACTIVITY_CLIPBOARD_CLEAR:"activity-clipboard-clear",ACTIVITY_COPY:"activity-copy",CALENDAR_RECONCILE:"calendar-reconcile",ACTIVITY_PASTE_COPIED:"activity-paste-copied",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",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"},Fr="activity-batch",tt=be,po=Object.values(P);function gt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var lt={NAME:"name",DESCRIPTION:"description",DURATION_DAYS:"durationDays",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",WORK_HOURS:"workHours",START_DATE:"startDate",END_DATE:"endDate",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",CALENDAR_ID:"calendarId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds"},sr={START:"start",END:"end"},fe={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},Ne={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var Vu={[lt.NAME]:S.TEXT,[lt.DESCRIPTION]:S.DESCRIPTION,[lt.DURATION_DAYS]:S.DURATION,[lt.PROGRESS]:S.PROGRESS,[lt.COST]:S.COST,[lt.USED_COST]:S.USED_COST,[lt.WORK_HOURS]:S.HH_WORK_TIME,[lt.START_DATE]:S.START_DATE,[lt.END_DATE]:S.END_DATE,[lt.CONSTRAINT_TYPE]:S.CONSTRAINT_TYPE,[lt.CONSTRAINT_DATE]:S.CONSTRAINT_DATE,[lt.CALENDAR_ID]:S.CALENDAR_ID,[lt.CUSTOM_ID]:S.CUSTOM_ID,[lt.SUBCONTRACT_ID]:S.SUBCONTRACT_ID,[lt.RESPONSABLE_IDS]:S.RESPONSABLES,[lt.TAG_IDS]:S.TAGS};function hn(e,t){return{activityId:e,column:Vu[t.field],newValue:t.value}}var Ku={[fe.FINISH_TO_START]:U.FINISH_TO_START,[fe.START_TO_START]:U.START_TO_START,[fe.FINISH_TO_FINISH]:U.FINISH_TO_FINISH,[fe.START_TO_FINISH]:U.START_TO_FINISH};function cr(e){return Ku[e]}function Yu(e){return e.kind===Ne.CREATE?{kind:tt.CREATE,source:e.sourceId,target:e.targetId,type:cr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===Ne.UPDATE?{kind:tt.UPDATE,linkId:e.linkId,...e.relationship===void 0?{}:{type:cr(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===Ne.REMOVE?{kind:tt.DELETE,linkId:e.linkId}:e}function Gu(e){return e===sr.START?S.START_DATE:e===sr.END?S.END_DATE:e}function $u(e){return{kind:Fr,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:cr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function zu(e){return{get:t=>e.getActivityView(t),list:()=>e.getAllActivitiesView(),ids:()=>e.getAllIds(),forEachId:t=>e.forEachActivityId(t),property:(t,r)=>e.getProperty(t,r),children:t=>e.getChildrenView(t),childIds:t=>e.getChildrenIds(t),hasChildren:t=>e.hasChild(t),indentTargetParentIds:t=>e.getIndentTargetParentIds(t),isCustomIdInUse:(t,r)=>e.isCustomIdInUse(t,r??null),create:(t,r)=>e.dispatch({...t,kind:P.ACTIVITY_CREATE},r),applyBatch:(t,r)=>e.applyActivityBatch($u(t),r),editInline:(t,r,i)=>e.dispatch({...hn(t,r),kind:P.INLINE_EDIT},i),applyDragBatch:(t,r)=>e.dispatch({kind:P.DATES_BATCH,edits:t.map(i=>({activityId:i.activityId,column:Gu(i.edge),newValue:i.value}))},r),editFields:(t,r)=>e.dispatch({kind:P.BULK_EDIT,edits:t.map(i=>hn(i.activityId,i))},r),remove:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_DELETE,activityIds:t}),move:(t,r)=>e.dispatch({...t,kind:P.ACTIVITY_MOVE},r),indent:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_INDENT,activityIds:t}),outdent:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,r,i={})=>e.dispatch({...i,kind:P.ACTIVITY_SET_PROGRESS,activityId:t,newValue:r}),copy:(t={})=>e.dispatch({...t,kind:P.ACTIVITY_COPY}),paste:(t,r={})=>e.dispatch({...r,kind:P.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:P.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:P.ACTIVITY_LOOKAHEAD_SYNC}),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function qu(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,r)=>e.dispatch({kind:P.LINK_CREATE,source:t.sourceId,target:t.targetId,type:cr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},r),update:(t,r,i)=>e.dispatch({kind:P.LINK_UPDATE,linkId:t,...r.relationship===void 0?{}:{type:cr(r.relationship)},...r.lagDays===void 0?{}:{lag:r.lagDays}},i),remove:(t,r)=>e.dispatch({kind:P.LINK_DELETE,linkId:t},r),batch:(t,r)=>e.dispatch({kind:P.LINKS_BATCH,operations:t.map(Yu)},r)}}function yo(e){let t=(r,i)=>e.dispatch({kind:P.BASELINE_APPLY,points:r},i);return{activities:zu(e),links:qu(e),calendars:{get:r=>e.getCalendar(r),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:r=>e.dispatch({kind:P.CALENDAR_RECONCILE},r)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:r,...i})=>e.dispatch({...i,kind:P.SELECTION_TOGGLE,isChecked:r}),replace:(r,i={})=>e.dispatch({...i,kind:P.SELECTION_REPLACE,activityIds:r})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),filter:()=>e.getActiveFilter(),setFilter:r=>e.dispatch({...r,kind:P.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(r,i={})=>e.dispatch({...i,kind:P.SORT_SET,rules:r}),setVisibility:(r,i={})=>e.dispatch({...i,kind:P.VISIBILITY_SET,visibleIds:r}),setStatusCriteria:(r,i)=>e.dispatch({kind:P.STATUS_CRITERIA_SET,criteria:r},i)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(r,i)=>e.dispatch({kind:P.PONDERATOR_CRITERION_SET,criterion:r},i),activeFor:r=>gt(r)},impactRequests:{sync:r=>e.dispatch({...r,kind:P.SIR_SYNC})},persistence:{hasChanges:()=>e.hasUnsavedChanges(),modifiedActivities:()=>e.getModifiedActivities(),modifiedActivityFields:()=>e.getModifiedActivityFields(),newActivities:()=>e.getNewActivities(),deletedActivities:()=>e.getDeletedActivitiesSinceLastSave(),modifiedLinks:()=>e.getModifiedLinks(),newLinks:()=>e.getNewLinks(),deletedLinks:()=>e.getDeletedLinksSinceLastSave(),captureHistoryBoundary:()=>e.capturePersistenceHistoryBoundary(),readSnapshot:()=>({activities:e.getAllActivitiesView(),links:e.getAllLinksView(),historyBoundary:e.capturePersistenceHistoryBoundary()}),acknowledge:r=>e.dispatch({kind:P.PERSISTENCE_ACKNOWLEDGE,checkpoint:r})},history:{undo:r=>e.undo(r),redo:r=>e.redo(r),canUndo:()=>e.canUndo(),canRedo:()=>e.canRedo(),clear:()=>e.clearHistory(),depth:()=>e.undoDepth()},projection:{changeSetFrom:r=>e.createProjectionChangeSetFrom(r)},criticalPath:{get ready(){return e.criticalPathReady},recompute:()=>e.recomputeCriticalPath(),isSettled:()=>e.isCriticalPathSettled(),whenSettled:()=>e.whenCriticalPathSettled()},diagnostics:{auditEffectiveGraph:()=>e.auditEffectiveGraph(),revision:()=>e.getScheduleRevision(),canonicalDigest:()=>e.getCanonicalDigest()}}}var Tt=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 xr=e=>String(e);function ho(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:a,exists:o,autoCheckParents:s}=e,c=xr(t),l=new Set([...i].map(String)),d=new Set(l),u=Ju(c,n).filter(o),f=u.filter(y=>!a(y)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let y of f)r?d.add(y):d.delete(y);return p||Xu({id:c,isChecked:r,autoCheckParents:s,hierarchy:n,isFrozen:a,exists:o,next:d}),{nextSelection:d,changed:Qu(l,d),parentBlocked:p}}function Ju(e,t){let r=[],i=new Tt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let a=i.dequeue();for(let o of t.getChildrenIds(a)){let s=xr(o);n.has(s)||(n.add(s),r.push(s),i.enqueue(s))}}return r}function Xu(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:a,exists:o,next:s}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=xr(c);if(a(l))return;let d=n.getChildrenIds(l).map(xr).filter(o),u=d.some(a),f=d.filter(g=>!a(g)),y=f.length>0&&f.every(g=>s.has(g))&&!u;if(r){if(!i||!y||s.has(l))return;s.add(l)}else{if(y||!s.has(l))return;s.delete(l)}c=n.getParentId(l)}}function Qu(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 we(e){return(e.pendingRequestIds?.length??0)>0}var v={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",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",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",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var mo=(e,t)=>{let r=e.getActivity(t);return r!=null&&we(r)},go=(e,t,r)=>{let i=[],n=(a,o)=>{let s=t.isChecked(a);t.setChecked(a,o)&&i.push({activityId:a,checked:{before:s,after:o}})};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 Ao(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,a=n?s=>n.has(s):s=>mo(r,s),o=ho({clickedId:i,isChecked:e.isChecked,currentSelection:new Set(r.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>r.getChildren(s),getParentId:s=>{let c=r.getParentId(s);return!c||c==="0"?null:String(c)}},isFrozen:a,exists:s=>r.activityExists(s),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:go(e,r,o.changed)}}function Mr(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(o=>r.activityExists(o)).filter(o=>!mo(r,o))),n=new Set(r.checkedIds().map(String)),a={checked:[...i].filter(o=>!n.has(o)),unchecked:[...n].filter(o=>!i.has(o))};return{ok:!0,changes:go(e,r,a)}}function Fe(e,t,r=e.getAllIds()){let i=[];for(let n of r){let a=String(n),o=t.has(a),s=e.isVisible(a);s!==o&&(e.setVisible(a,o),i.push({activityId:a,visible:{before:s,after:o}}))}return i}function Io(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=Fe(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Dt={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},vo={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var E={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},B={NAME:"name",DESCRIPTION:"description",CUSTOM_ID:"customId",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",PROGRESS:"progress",DURATION_DAYS:"durationDays",CALENDAR_DURATION:"calendarDuration",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",FREE_SLACK_DAYS:"freeSlackDays",TOTAL_SLACK_DAYS:"totalSlackDays",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",BASELINE_DURATION_DAYS:"baselineDurationDays",BASELINE_COST:"baselineCost",BASELINE_WORK_HOURS:"baselineWorkHours",EXPECTED_PROGRESS:"expectedProgress",START_DATE:"startDate",END_DATE:"endDate",CONSTRAINT_DATE:"constraintDate",BASELINE_START_DATE:"baselineStartDate",BASELINE_END_DATE:"baselineEndDate",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",STATUS:"status",CONSTRAINT_TYPE:"constraintType",CALENDAR_ID:"calendarId",SUBCONTRACT_ID:"subcontractId",IS_CRITICAL:"isCritical"},w={INCLUDES:"includes",NOT_INCLUDES:"notIncludes",IS:"is",IS_NOT:"isNot",EQUALS:"equals",NOT_EQUALS:"notEquals",GREATER_THAN:"greaterThan",LESS_THAN:"lessThan",GREATER_OR_EQUAL:"greaterOrEqual",LESS_OR_EQUAL:"lessOrEqual",AFTER:"after",BEFORE:"before",BETWEEN:"between",SOME_OF:"someOf",NOT_SOME_OF:"notSomeOf"},Ur={AND:"and",OR:"or"};var Zu=2,tf=[mt.WAITING,mt.DONE,mt.DOING,mt.OVERDUE,mt.ADVANCEMENT],ef=[H.MFO,H.MSO,H.SNLT,H.SNET,H.ALAP,H.ASAP,H.FNET,H.FNLT],rf=1e3*60*60*24;function mn(e,t){return e===null||t<=0?null:e/t}function nf(e,t){let r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),i=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((i-r)/rf)+1}var af={[B.NAME]:{valueKind:E.STRING,extract:e=>e.name},[B.DESCRIPTION]:{valueKind:E.STRING,extract:e=>e.description},[B.CUSTOM_ID]:{valueKind:E.STRING,extract:e=>e.customId},[B.CORRELATIVE_ID]:{valueKind:E.NUMBER,extract:e=>e.correlativeId},[B.UNIQUE_CORRELATIVE_ID]:{valueKind:E.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[B.PROGRESS]:{valueKind:E.NUMBER,extract:e=>e.progress},[B.DURATION_DAYS]:{valueKind:E.NUMBER,extract:(e,t)=>mn(e.durationHours,t.hoursPerDay)},[B.CALENDAR_DURATION]:{valueKind:E.NUMBER,extract:e=>e.type===Dt.MILESTONE?0:nf(e.startDate,e.endDate)},[B.COST]:{valueKind:E.NUMBER,extract:e=>e.cost},[B.USED_COST]:{valueKind:E.NUMBER,extract:e=>e.usedCost},[B.REAL_COST]:{valueKind:E.NUMBER,extract:e=>e.realCost},[B.WORK_HOURS]:{valueKind:E.NUMBER,extract:e=>e.workHours},[B.REAL_WORK_HOURS]:{valueKind:E.NUMBER,extract:e=>e.realWorkHours},[B.PONDERATOR]:{valueKind:E.NUMBER,extract:e=>e.ponderator},[B.FREE_SLACK_DAYS]:{valueKind:E.NUMBER,extract:(e,t)=>mn(e.freeSlackHours,t.hoursPerDay)},[B.TOTAL_SLACK_DAYS]:{valueKind:E.NUMBER,extract:(e,t)=>mn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[B.EXPECTED_PROGRESS_BASELINE]:{valueKind:E.NUMBER,equalityPrecision:Zu,extract:e=>e.expectedProgressBaseline},[B.EXPECTED_PROGRESS]:{valueKind:E.NUMBER,extract:e=>e.expectedProgress},[B.BASELINE_DURATION_DAYS]:{valueKind:E.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[B.BASELINE_COST]:{valueKind:E.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[B.BASELINE_WORK_HOURS]:{valueKind:E.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[B.START_DATE]:{valueKind:E.DATE,extract:e=>e.startDate},[B.END_DATE]:{valueKind:E.DATE,extract:e=>e.endDate},[B.CONSTRAINT_DATE]:{valueKind:E.DATE,extract:e=>e.constraintDate},[B.BASELINE_START_DATE]:{valueKind:E.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[B.BASELINE_END_DATE]:{valueKind:E.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[B.EARLY_START]:{valueKind:E.DATE,extract:e=>e.criticalPath?.earlyStart??null},[B.EARLY_FINISH]:{valueKind:E.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[B.LATE_START]:{valueKind:E.DATE,extract:e=>e.criticalPath?.lateStart??null},[B.LATE_FINISH]:{valueKind:E.DATE,extract:e=>e.criticalPath?.lateFinish??null},[B.RESPONSABLE_IDS]:{valueKind:E.ID_ARRAY,extract:e=>e.responsableIds},[B.TAG_IDS]:{valueKind:E.ID_ARRAY,extract:e=>e.tagIds},[B.STATUS]:{valueKind:E.ENUM,order:tf,extract:e=>e.status},[B.CONSTRAINT_TYPE]:{valueKind:E.ENUM,order:ef,extract:e=>e.constraintType},[B.CALENDAR_ID]:{valueKind:E.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[B.SUBCONTRACT_ID]:{valueKind:E.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[B.IS_CRITICAL]:{valueKind:E.BOOLEAN,extract:e=>e.isCritical}};function Xt(e){return af[e]??null}function gn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function jt(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function of(e,t,r){let i=e===null;return r===w.INCLUDES?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r===w.NOT_INCLUDES?i||!String(e).toLowerCase().includes(t.toLowerCase()):r===w.IS?!i&&String(e)===t:r===w.IS_NOT?i||String(e)!==t:!1}function sf(e,t,r,i){if(e===null||typeof e!="number")return r===w.NOT_EQUALS;let n=i===void 0?e:Number(e.toFixed(i));return r===w.EQUALS?n===t:r===w.NOT_EQUALS?n!==t:r===w.GREATER_THAN?e>t:r===w.LESS_THAN?e<t:r===w.GREATER_OR_EQUAL?e>=t:r===w.LESS_OR_EQUAL?e<=t:!1}function cf(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function lf(e,t,r){if(!(e instanceof Date))return!1;let i=jt(e),n=jt(t);return r===w.AFTER?i>n:r===w.BEFORE?i<n:!1}function df(e,t,r){if(!(e instanceof Date))return!1;let i=jt(e);return i>=jt(t)&&i<=jt(r)}function uf(e,t,r){let n=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r===w.SOME_OF?n:r===w.NOT_SOME_OF?!n:!1}function ff(e,t,r){let i=e!==null&&t.has(String(e));return r===w.SOME_OF?i:r===w.NOT_SOME_OF?!i:!1}function Co(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function So(e,t,r){let i=Xt(t.field);if(i===null)return!1;let n=i.extract(e,r),{operator:a}=t;return a===w.BETWEEN?i.valueKind===E.NUMBER?cf(n,Number(t.value),Number(t.valueTo)):i.valueKind===E.DATE?df(n,gn(t.value),gn(t.valueTo)):!1:i.valueKind===E.STRING?of(n,String(t.value),a):i.valueKind===E.NUMBER?sf(n,Number(t.value),a,i.equalityPrecision):i.valueKind===E.DATE?lf(n,gn(t.value),a):i.valueKind===E.ID_ARRAY?uf(n,Co(t.value),a):ff(n,Co(t.value),a)}function pf(e,t,r){return t.criteria.length===0?!0:t.logic===Ur.OR?t.criteria.some(i=>So(e,i,r)):t.criteria.every(i=>So(e,i,r))}function yf(e,t){let r=jt(e.startDate),i=jt(e.endDate),n=jt(t.start),a=jt(t.end),o=r>=n&&i<=a,s=r>=n&&r<=a,c=n>=r&&n<=i;return o||s||c}function An(e,t,r){let i=pf(e,t,r),n=t.dateRange,a=n===void 0||yf(e,n);return i&&a}function hf(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function ko(e){let{activities:t,parentOf:r,filter:i,context:n}=e,a=new Set,o=[];for(let s of t)An(s,i,n)&&(a.add(String(s.id)),o.push(s.id));for(let s of o)hf(s,r,a);return a}function mf(e){let{activities:t,parentOf:r,filter:i,context:n}=e,a=new Set,o=new Map,s=new Map,c=new Map;for(let l of t){let d=String(l.id),u=r(d);s.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=An(l,i,n);o.set(d,f?1:0),f&&a.add(d)}return{matchedIds:a,visibleReferenceCounts:o,parentIds:s,remainingChildren:c}}function gf(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:i}=e,n=[];for(let a of r.keys())i.get(a)===0&&n.push(a);for(;n.length>0;){let a=n.pop();if(a===void 0)break;let o=r.get(a);if(o==null)continue;let s=t.get(a)??0;t.set(o,(t.get(o)??0)+s);let c=(i.get(o)??1)-1;i.set(o,c),c===0&&n.push(o)}}function Af(e){let t=new Set;for(let[r,i]of e)i>0&&t.add(r);return t}function Br(e){let t=mf(e);gf(t);let r=Af(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function To(e,t,r){let i=new Set;for(let n of t){let a=String(n.id);i.add(a);let o=e.matchedIds.has(a),s=An(n,e.filter,e.context);if(o===s)continue;s?e.matchedIds.add(a):e.matchedIds.delete(a);let c=s?1:-1,l=a;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(i.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return i}function pe(e){return{hoursPerDay:e,locale:"en"}}var ft={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},If={[E.STRING]:new Set([w.INCLUDES,w.NOT_INCLUDES,w.IS,w.IS_NOT]),[E.NUMBER]:new Set([w.EQUALS,w.NOT_EQUALS,w.GREATER_THAN,w.LESS_THAN,w.GREATER_OR_EQUAL,w.LESS_OR_EQUAL,w.BETWEEN]),[E.DATE]:new Set([w.AFTER,w.BEFORE,w.BETWEEN]),[E.ID_ARRAY]:new Set([w.SOME_OF,w.NOT_SOME_OF]),[E.ENUM]:new Set([w.SOME_OF,w.NOT_SOME_OF]),[E.BOOLEAN]:new Set([w.SOME_OF,w.NOT_SOME_OF]),[E.REFERENCE]:new Set([w.SOME_OF,w.NOT_SOME_OF])};function Do(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:ft.INVALID_VALUE};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:ft.INVALID_VALUE};let i=t.getTime(),n=r.getTime();return!Number.isFinite(i)||!Number.isFinite(n)||i>n?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(n)}}}function _o(e){let t=Xt(e.field);if(t===null)return{ok:!1,reason:ft.UNKNOWN_FIELD};if(!If[t.valueKind].has(e.operator))return{ok:!1,reason:ft.UNKNOWN_OPERATOR};if(e.operator===w.BETWEEN)return vf(e,t.valueKind);if(t.valueKind===E.NUMBER){let i=In(e.value);return i===null?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}if(t.valueKind===E.DATE){let i=vn(e.value);return i===null?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}let r=Cf(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind===E.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===E.ID_ARRAY||t.valueKind===E.ENUM||t.valueKind===E.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function vf(e,t){if(t===E.NUMBER){let r=In(e.value),i=In(e.valueTo);return r===null||i===null||r>i?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}if(t===E.DATE){let r=vn(e.value),i=vn(e.valueTo);return r===null||i===null||r.getTime()>i.getTime()?{ok:!1,reason:ft.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}return{ok:!1,reason:ft.UNKNOWN_OPERATOR}}function Cf(e,t){let{value:r}=e;return t===E.BOOLEAN?Array.isArray(r)&&r.every(i=>typeof i=="boolean")?null:ft.INVALID_VALUE:t===E.ID_ARRAY||t===E.ENUM||t===E.REFERENCE?Array.isArray(r)&&r.every(i=>typeof i=="string"||typeof i=="number")?null:ft.INVALID_VALUE:Array.isArray(r)?ft.INVALID_VALUE:null}function In(e){if(typeof e=="string"&&e.trim()===""||typeof e!="string"&&typeof e!="number")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function vn(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e=="string")t=new Date(e);else if(typeof e=="number")t=new Date(e);else return null;return Number.isFinite(t.getTime())?t:null}function O(e){return structuredClone(e)}function Eo(e){return e.criteria.length===0&&e.dateRange===void 0}function Sf(e,t,r){let i=e.getAllActivities();if(Eo(t))return{visibleIds:ko({activities:i,parentOf:a=>e.getParentId(a),filter:t,context:pe(r)}),projection:null};let n=Br({activities:i,parentOf:a=>e.getParentId(a),filter:t,context:pe(r)});return{visibleIds:n.visibleIds,projection:n}}function Ro(e,t){let{adapter:r,hoursPerDay:i}=t,n=[];for(let u of e.criteria){let f=_o(u);if(!f.ok)return{ok:!1,reason:f.reason};n.push(f.criterion)}let a=Do(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let o=O(a.dateRange===void 0?{criteria:n,logic:e.logic}:{criteria:n,logic:e.logic,dateRange:a.dateRange});r.setActiveFilter(Eo(o)?null:o);let{visibleIds:s,projection:c}=Sf(r,o,i);r.setFilterProjection(c);let l=Fe(r,s);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var ye={ASCENDING:"asc",DESCENDING:"desc"};var x="0";function N(e){return e==null||e===0||e==="0"}function Qt(e){return N(e)?"0":String(e)}var Cn=Number.MAX_SAFE_INTEGER;function Rt(e,t){let r=lr(e,t),i=t.getOrderComparator?.()??null;return r.sort(i===null?Wr:(n,a)=>i(n,a)||Wr(n,a)),r.map(n=>String(n.id))}function Lo(e){let t=[],r=n=>{t.push(n);let a=Rt(String(n.id),e);for(let o of a){let s=e.getActivity(o);s&&r(s)}},i=Rt("0",e);for(let n of i){let a=e.getActivity(n);a&&r(a)}return t}function Oo(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=bo(i),a=Rt(n,r),o=a.findIndex(s=>String(s)===String(e));if(o<=0)return null;for(let s=o-1;s>=0;s--){let c=a[s];if(c!==void 0&&!kf(t,c))return c}return null}function Sn(e,t){let r=t.getActivity(e);if(!r)return-1;let i=bo(r);return Rt(i,t).findIndex(a=>String(a)===String(e))}function lr(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),i=[];for(let n of r){let a=t.getActivity(n);a&&i.push(a)}return i}function Wr(e,t){let r=Po(e),i=Po(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function Po(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}function bo(e){let t=e.parentId;return t===null?"0":t}function kf(e,t){return e.has(t)?!0:e.has(String(t))}function xe(e){let t=[],r=i=>{let n=Rt(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let a of n)r(a)};return r("0"),t}function kn(e,t){let r=[];for(let i of t){let n=Rt(i,e);n.length>1&&r.push({parentId:i,childIds:n})}return r}function Tf(e){return Xt(e.field)===null?ft.UNKNOWN_FIELD:e.direction!==ye.ASCENDING&&e.direction!==ye.DESCENDING?ft.UNKNOWN_OPERATOR:null}function No(e,t){let{adapter:r}=t;for(let a of e.rules){let o=Tf(a);if(o!==null)return{ok:!1,reason:o}}let i=e.rules.length===0?null:O({rules:e.rules});return r.setActiveOrder(i),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:xe(r)}}}function wo(e,t){throw new Error(t)}function Fo(e,t){return()=>t()===e}var Tn=typeof window>"u",Df=!Tn&&typeof MessageChannel<"u";function it(){return Df?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 Hr(e,t){return performance.now()-e<vo.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await it(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function Me(e){return Tn||await it(),e()?{aborted:!1}:{aborted:!0}}function jr(e,t){let{inDegree:r,successors:i}=_f(e,t),n=Ef(r),a=Rf(n,r,i),o=a.length<e.length,s=o?Pf(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:o,cycleNodes:s}}function _f(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,o=n.target;!r.has(a)||!r.has(o)||(i.get(a).push(o),r.set(o,(r.get(o)??0)+1))}return{inDegree:r,successors:i}}function Ef(e){let t=new Tt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function Rf(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let a of r.get(n)??[]){let o=(t.get(a)??1)-1;t.set(a,o),o===0&&e.enqueue(a)}}return i}function Pf(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Vr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=jr(t,r),this.cached)}};function xo(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}var Dn={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 Mo(e){return e==="project"||e==="task"||e==="milestone"}function wt(e,t){return t||Mo(e)&&Dn[e].alwaysSummary}function Vt(e){return e==="milestone"}function Zt(e){return Mo(e)&&Dn[e].promotesToProjectOnFirstChild}var _n="project",Ue="task";function dr(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Kr(e,t){let r=t.getActivity(e);return r?wt(r.type,t.getChildren(e).length>0):!1}function Yr(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 En(e,t,r){let i=Kr(e,r);return Kr(t,r)&&Yr(e,t,r)||i&&Yr(t,e,r)}function Wo(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 o of a)i.push(o)}return r}function Lf(e){let t=new Map;for(let r of e)Uo(t,String(r.source),r),Uo(t,String(r.target),r);return t}function Uo(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function Of(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),a=[];for(let o of e)bf(o,n,t,r,i)||a.push(o);return a.length>0?a:e}function bf(e,t,r,i,n){let a=String(e),o=r.getActivity(e);if(!o||o.autoScheduling===!1)return!1;let s=i.get(a)??[];for(let c of s)if(Nf(c,a,o,t,r,n))return!0;return!1}function Nf(e,t,r,i,n,a){if(wf(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let s=Ff(e,t);if(!i.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&xf(e,r,c))}function wf(e){return e.source===e.target}function Ff(e,t){return String(e.source)===t?e.target:e.source}function xf(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 $r(e,t){let r=[],i=Lf(e),n=0;for(let a of e){let o=Kr(a.source,t),s=Kr(a.target,t);if(Mf(a,o,s,t))continue;if(!o&&!s){r.push(a);continue}let c=Bo(a.source,o,t,i,!0),l=Bo(a.target,s,t,i,!1);n=Kf(r,c,l,a,t,n,i)}return r}function Mf(e,t,r,i){return r&&Yr(e.source,e.target,i)||t&&Yr(e.target,e.source,i)}function Bo(e,t,r,i,n){return t?Of(Wo(e,r),r,i,n):[e]}function Uf(e,t,r){let i=Wo(e,t);if(i.length===0)return null;let n=null,a=null;for(let o of i){let s=r(o);if(!s)continue;(n===null||s.startDate<n)&&(n=s.startDate),(a===null||s.endDate>a)&&(a=s.endDate)}return n===null||a===null?null:{startDate:n,endDate:a}}function Gr(e,t){return Uf(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function Bf(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Wf(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 Hf(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function jf(e,t,r,i,n){if(Hf(e,n))return 0;let a=i.getActivity(e);return!t||!a||!r?0:i.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Vf(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Gr(e.source,t),a=Gr(e.target,t),o=e.type===U.START_TO_START||e.type===U.START_TO_FINISH,s=e.type===U.FINISH_TO_FINISH||e.type===U.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:a?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:o,targetLag:s?-Bf(i,a,t):0,summarySourceId:e.type===U.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&a?e.target:void 0}}function Kf(e,t,r,i,n,a,o){let s=Vf(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:y,finishAnchoredSummaryTargetId:g}=s,C=a;for(let R of t){let A=f?Wf(R,c,l,n):0;for(let k of r){if(String(R)===String(k))continue;let m=jf(k,d,c,n,o);e.push(Yf(i,R,k,C,A,p,u+m,y,g??(m!==0&&p===0?i.target:void 0))),C+=1}}return C}function Yf(e,t,r,i,n,a,o,s,c){return{id:`virtual_${e.id}_${i}`,source:t,target:r,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1,_sourceLag:n,_targetLag:a,_trueLag:o,...s===void 0?{}:{_summarySourceId:s},...c===void 0?{}:{_summaryTargetId:c}}}var zr=class{invalidate(){}get(t,r){return $r(t,r)}};function Gf(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 $f(e,t,r){let i=new Set,n=new Map,a=new Tt;for(a.enqueue(e);!a.isEmpty();){let o=a.dequeue(),s=String(o);if(i.has(s))continue;i.add(s);let c=r.neighbors.get(o);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)===s?d.target:d.source;i.has(String(f))||a.enqueue(f)}}return Array.from(n.values())}function Ho(e,t){let r=new Map;for(let o of t)r.set(o.id,o);let i=Gf(t),n=$f(e,r,i),a=new Set([String(e)]);for(let o of n)a.add(String(o.source)),a.add(String(o.target));return{activityIds:a,links:n}}var jo=0,ur=100;function he(e){return e===0}function Vo(e,t,r){let i=r.type===U.FINISH_TO_START,n=r.type===U.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 U.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case U.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case U.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:i,isFF:n,isZeroDurationCase:!1};case U.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 zf(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Gr(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function qf(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 Ko(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:o,isFS:s,isFF:c}=Vo(e,t,r),l=zf(r,e,i)??n,d=l+a+o;if(!(t.durationHours===0?d!==0:l!==0||a!==0||o!==0))return qf(e,t,r,i,s||c);let p=s?t:e,y=i.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(y=i.calculateEndDate({startDate:y,durationHours:l,task:e})),a!==0&&(y=i.calculateEndDate({startDate:y,durationHours:a,task:t})),o!==0&&(y=i.calculateEndDate({startDate:y,durationHours:o,task:t})),t.durationHours===0){if(s||c)return{successorStart:i.getClosestWorkTime({date:y,dir:"past",task:t}),link:r};let g=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:y,dir:"future",task:t}),link:r}}function Yo(e,t,r,i){let{sourceLag:n,targetLag:a,trueLag:o}=Vo(t,e,r),s=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return o!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-o,task:e})),a!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-a,task:e})),n!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-n,task:t})),s}function Go(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let a=n.constraintType;if(!a||a===H.ASAP||a===H.ALAP)continue;let o=uo(n,t);!o.earliestStart&&!o.latestStart&&!o.earliestEnd&&!o.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:o.earliestStart,latestStart:o.latestStart,earliestEnd:o.earliestEnd,latestEnd:o.latestEnd})}}function qr(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=yn(e.startDate,i):fo(n,i)?a=n:a=yn(n,i),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function $o(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case H.MSO:case H.MFO:return new Date(i);case H.SNET:case H.FNET:return i>t?new Date(i):t;case H.SNLT:case H.FNLT:return i<t?new Date(i):t;default:return t}}function Jf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function zo(e,t,r){return Rn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Rn(e,t,r){return t.dragWithMultiple&&Jf(e,r)}async function qo(e,t,r,i,n,a){let o=new Map;for(let u of t){let f=String(u.target);o.has(f)||o.set(f,[]),o.get(f).push(u)}let s=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 Hr(d,n);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Xf(p,r))continue;let y=o.get(String(u))??[],g=null,C=null,R=!1;for(let F of y){let T=r.getActivity(F.source);if(!T)continue;let I=s(F.source),_=I.startDate.getTime()!==T.startDate.getTime()||I.endDate.getTime()!==T.endDate.getTime(),j={...T,startDate:I.startDate,endDate:I.endDate},W=zo(j,c,l),Z={...j,startDate:W.startDate,endDate:W.endDate},J=Rn(F.source,c,l)?{...F,lag:0}:F,ht=Ko(Z,p,J,r);(!g||ht.successorStart>g)&&(g=ht.successorStart,C=String(F.id),R=F._summaryTargetId!==void 0&&!_&&(F._targetLag===0||i.preventSummaryTargetPullback===!0))}g!==null&&R&&g<p.startDate&&(g=new Date(p.startDate));let k=a.get(u),m=k?{...k}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},L=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!g&&!L)){if(g){let F=g;p.type===Dt.MILESTONE&&(F=$o(p,g)),m.drivingLinkId=C,m.startDate=F,m.endDate=r.calculateEndDate({startDate:F,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=F,m.earliestSchedulingEnd=m.endDate}else p.constraintType===H.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===H.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));qr(p,m,r),a.set(u,m)}}return a}function Xf(e,t){return wt(e.type,t.getChildren(e.id).length>0)}async function Jo(e,t,r,i,n,a){let o=new Map(r),s=i.getAllActivities(),c=s.length,l=[];for(let C of s)C.constraintType===H.ALAP&&l.push(C.id);if(l.length===0)return o;let d=new Map,u=new Map;for(let C of t){let R=String(C.source);d.has(R)||d.set(R,[]),d.get(R).push(C);let A=String(C.target);u.has(A)||u.set(A,[]),u.get(A).push(C)}let f=C=>{let R=o.get(C);if(R)return{startDate:R.startDate,endDate:R.endDate};let A=i.getActivity(C);return A?{startDate:A.startDate,endDate:A.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||N(C.parentId)?i.getProjectEnd():f(C.parentId).endDate,y=(C,R)=>{let A=C,k=0;for(;A&&!N(A)&&k++<c+1;){if(String(A)===String(R))return!0;let m=i.getActivity(A);if(!m||!m.parentId)break;A=m.parentId}return!1},g=performance.now();for(let C of e){let R=await Hr(g,a);if(R.aborted)return o;g=R.newSliceStart;let A=i.getActivity(C);if(!A||A.constraintType!==H.ALAP||!A.autoScheduling||A.progress===100||wt(A.type,i.getChildren(C).length>0))continue;let k=p(A);if(!k)continue;let m=k,L=null,F=!1,T=d.get(String(C))??[];for(let Nt of T){if((Nt.lag??0)<0)continue;let Oe=i.getActivity(Nt.target);if(!Oe||Oe.autoScheduling===!1)continue;let oo=f(Nt.target),Lu={...Oe,startDate:oo.startDate,endDate:oo.endDate},Nr=Yo(Lu,A,Nt,i);Nr<m&&(m=Nr),(L===null||Nr<L)&&(L=Nr,F=A.parentId&&!N(A.parentId)?y(Nt.target,A.parentId):!1)}if(L!==null)if(F)m=L;else{let Nt=f(C).endDate,Oe=Nt.getTime()>k.getTime()?Nt:k;m=L<Oe?L:Oe}else m>k&&(m=k);let _=(u.get(String(C))??[]).some(Nt=>Nt.type===U.FINISH_TO_START||Nt.type===U.FINISH_TO_FINISH),j=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),W=()=>i.getClosestWorkTime({date:j,dir:"past",task:A}),Z=i.getClosestWorkTime({date:m,dir:"future",task:A}).getTime()===m.getTime(),J;A.durationHours===0&&L===null?J=_&&Z?W():i.getClosestWorkTime({date:m,dir:"past",task:A}):A.durationHours===0?_?J=W():J=i.getClosestWorkTime({date:m,dir:"future",task:A}):J=i.getClosestWorkTime({date:m,dir:"future",task:A});let ht=i.calculateEndDate({startDate:J,durationHours:-A.durationHours,task:A}),kt=o.get(C),ct=kt?{...kt}:{activityId:C,startDate:ht,endDate:J,drivingLinkId:null,kind:"alap",conflict:!1};ct.startDate=ht,ct.endDate=J,ct.drivingLinkId=null,ct.kind="alap";let Pe=ct.earliestSchedulingStart??null;ct.earliestSchedulingStart=null,ct.earliestSchedulingEnd=null;let Le=Pe!==null&&Pe.getTime()>ht.getTime()?Pe:ht;ct.latestSchedulingStart=Le,ct.latestSchedulingEnd=Le===ht?J:i.calculateEndDate({startDate:Le,durationHours:A.durationHours,task:A}),qr(A,ct,i),o.set(C,ct)}return o}var Be={warn(){},error(){}};function Wt(e){if(e.type==="milestone")return 0;let t=e.startDate?.getTime(),r=e.endDate?.getTime();return t==null||r==null||Number.isNaN(t)||Number.isNaN(r)?null:Math.floor((r-t)/864e5)+1}function fr(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,n.calendarDuration=Wt(n),e.updateActivity(r))}})}function Pn(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 o=String(a.source),s=String(a.target),c=n.get(o)??[];c.push(s),n.set(o,c)}return Qf(n,i,r)}function pr(e){let t=new Map,r=new Map;for(let a of e){let o=String(a.source),s=String(a.target),c=t.get(o)??[];c.push(s),t.set(o,c),r.set(o,r.get(o)??0),r.set(s,(r.get(s)??0)+1)}let i=new Tt;for(let[a,o]of r)o===0&&i.enqueue(a);let n=0;for(;!i.isEmpty();){let a=i.dequeue();n+=1;for(let o of t.get(a)??[]){let s=r.get(o)-1;r.set(o,s),s===0&&i.enqueue(o)}}return n!==r.size}function Qf(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new Tt;for(n.enqueue(t);!n.isEmpty();){let a=n.dequeue(),o=e.get(a)??[];for(let s of o){if(s===r)return!0;i.has(s)||(i.add(s),n.enqueue(s))}}return!1}function Jr(e){let t=Zf(e);for(let r of t.adjacency.keys())t.records.has(r)||tp(r,t);return t.components}function Zf(e){let t=new Map,r=new Set;for(let i of e){let n=String(i.source),a=String(i.target),o=Xo(t,n);if(Xo(t,a),n===a){r.add(n);continue}o.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Xo(e,t){let r=e.get(t);if(r)return r;let i=[];return e.set(t,i),i}function tp(e,t){let r=[];for(r.push({node:e,record:Qo(e,t),neighborCursor:0});r.length>0;){let i=r[r.length-1];if(i===void 0)break;let n=t.adjacency.get(i.node)??[];if(i.neighborCursor<n.length){let s=n[i.neighborCursor];if(i.neighborCursor+=1,s===void 0)continue;ep(i,s,r,t);continue}r.pop();let a=r[r.length-1];a&&i.record.lowLink<a.record.lowLink&&(a.record.lowLink=i.record.lowLink),i.record.lowLink===i.record.visitIndex&&rp(i.node,t)}}function ep(e,t,r,i){let n=i.records.get(t);if(!n){r.push({node:t,record:Qo(t,i),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function Qo(e,t){let r={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,r),t.componentStack.push({node:e,record:r}),r}function rp(e,t){let r=[];for(;;){let o=t.componentStack.pop();if(o===void 0||(o.record.onStack=!1,r.push(o.node),o.node===e))break}let i=r[0],n=r.length===1&&i!==void 0&&t.selfLooped.has(i);(r.length>1||n)&&t.components.push(r)}function yr(e,t,r){let i=r?new Ln(e,r):e;return $r([...t],i)}var Ln=class{constructor(t,r){this.base=t;for(let[i,n]of r.reparented){let a=String(i),o=n===null||N(n)?null:n,s=t.getActivity(i)?.parentId??null,c=s===null||N(s)?null:String(s),l=o===null?null:String(o);if(c!==l){if(this.reparented.set(a,o),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(a),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(i),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),i=this.movedOutByParent.get(r),n=this.base.getChildren(t),a=i?n.filter(s=>!i.has(String(s))):[...n],o=this.movedInByParent.get(r);return o&&a.push(...o),a}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let i=String(r),n=new Set,a=this.getActivity(t);for(;a;){let o=a.parentId;if(o===null||N(o))return!1;let s=String(o);if(s===i)return!0;if(n.has(s))return!1;n.add(s),a=this.getActivity(o)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function hr(e){let{port:t,currentLinks:r,proposedLinks:i,proposal:n}=e,a=yr(t,i,n);if(!pr(a))return{ok:!0};let o=yr(t,r),s=Zo(o),l=[...Zo(a)].filter(d=>!s.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function Zo(e){let t=new Set;for(let r of Jr(e))for(let i of r)t.add(i);return t}function te(e,t){switch(e.kind){case be.CREATE:return ip(e,t);case be.UPDATE:return mr(e,t.port);case be.DELETE:return np(e,t)}}function Qr(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),i=new Map,n=[];for(let l of r){let d=ts(l);i.has(d)||i.set(d,l.id),n.push({source:l.source,target:l.target})}let a=pr(n),o=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){o={applied:!1,rejected:ut.SELF_LINK};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){o={applied:!1,rejected:ut.ACTIVITY_MISSING};break}if(En(l.source,l.target,t.port)){o={applied:!1,rejected:ut.HIERARCHY_LINK};break}let u=ts(l),f=i.get(u);if(f!==void 0){o={applied:!1,rejected:ut.DUPLICATE,linkId:f};break}if(i.set(u,d),a&&Pn(n,{source:l.source,target:l.target}))return{applied:!1,rejected:ut.CYCLE};n.push({source:l.source,target:l.target})}if(!a&&pr(n))return{applied:!1,rejected:ut.CYCLE};if(o)return o;let s=[...r,...e.map(({operation:l,linkId:d})=>({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1}))];if(!hr({port:t.port,currentLinks:r,proposedLinks:s}).ok)return{applied:!1,rejected:ut.CYCLE};for(let{operation:l,linkId:d}of e){let u=t.preserved?.get(d);t.port.addLink({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1,...u?.ganttId===void 0?{}:{ganttId:u.ganttId},...u?.sectorId===void 0?{}:{sectorId:u.sectorId},...u?.proplannerId===void 0?{}:{proplannerId:u.proplannerId}})}return{applied:!0}}function ts(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function ip(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:ut.SELF_LINK};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:ut.ACTIVITY_MISSING};if(En(e.source,e.target,r))return{applied:!1,rejected:ut.HIERARCHY_LINK};let a=r.getAllLinks();for(let d of a)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:ut.DUPLICATE,linkId:d.id};let o=a.map(d=>({source:d.source,target:d.target}));if(Pn(o,{source:e.source,target:e.target}))return{applied:!1,rejected:ut.CYCLE};let s=(t.newLinkId??ap)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return hr({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:ut.CYCLE}}function mr(e,t){return t.getLink(e.linkId)?(e.lag!==void 0&&t.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&t.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:ut.LINK_MISSING}}function np(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:ut.LINK_MISSING}}var Xr=null;function ap(){return Xr===null&&(Xr=Date.now()),Xr+=1,String(Xr)}var es={[U.FINISH_TO_START]:"fs",[U.START_TO_START]:"ss",[U.FINISH_TO_FINISH]:"ff",[U.START_TO_FINISH]:"sf"},me={fs:U.FINISH_TO_START,ss:U.START_TO_START,ff:U.FINISH_TO_FINISH,sf:U.START_TO_FINISH},rs="fs";function is(e){if(e in me)return me[e]}var ns=";",as=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Zr(e){let t=[],r=[],i=e.replace(/\s+/g,"");if(i.length===0)return{specs:t,errors:r};for(let n of i.split(ns)){if(n.length===0)continue;let a=op(n);a?t.push(a):r.push(n)}return{specs:t,errors:r}}function op(e){let t=e.toLowerCase(),r=as.exec(t);if(!r)return null;let[,i,n,a,o]=r,s=n?me[n]:me[rs],c=0;if(o!==void 0){let l=Number(o);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:i,type:s,lag:c}}function ei(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=ti(l,c.type);a.has(d)||a.set(d,{source:l,type:c.type,lag:c.lag})}let o=new Map;for(let c of r)String(c.target)===String(t)&&o.set(ti(c.source,c.type),c);let s=[];for(let[c,l]of o)a.has(c)||s.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=o.get(c);d&&d.lag!==l.lag&&s.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)o.has(c)||s.push({kind:"create",source:l.source,target:t,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function ti(e,t){return`${String(e)}::${t}`}function ri(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=ti(l,c.type);a.has(d)||a.set(d,{target:l,type:c.type,lag:c.lag})}let o=new Map;for(let c of r)String(c.source)===String(t)&&o.set(ti(c.target,c.type),c);let s=[];for(let[c,l]of o)a.has(c)||s.push({kind:"delete",linkId:l.id});for(let[c,l]of a){let d=o.get(c);d&&d.lag!==l.lag&&s.push({kind:"update",linkId:d.id,lag:l.lag})}for(let[c,l]of a)o.has(c)||s.push({kind:"create",source:t,target:l.target,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function ii(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Pt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var os={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:rt.FUTURE,date:e,unit:pt.HOUR}):t.isWorkTime(e,pt.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function On(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 bn=os;var We=class{adapter;reporter;currentCalculationId=0;topoCache=new Vr;expandedLinksCache=new zr;constructor(t,r=Be){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=Fo(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{lp(this.adapter);let a=ee("schedule.total"),o=ee("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);Kt(o);let l=c;if((await Me(i)).aborted)return{...n,cancelled:!0};let d=ee("schedule.scoping"),u=this.adapter.getAllIds(),f=dp(t,l,this.adapter),p=f.links,y=f.idSet;Kt(d);let g=ee("schedule.topologicalSort"),C=fp(this.topoCache,u,l,y);if(Kt(g),C.hasCycles)return Kt(a),{...n,cycles:[C.cycleNodes]};if((await Me(i)).aborted)return{...n,cancelled:!0};let R=ee("schedule.processConstraints"),A=new Map;if(Go(C.ordered,this.adapter,A),Kt(R),(await Me(i)).aborted)return{...n,cancelled:!0};let k=ee("schedule.asapPass"),m=await qo(C.ordered,p,this.adapter,t,i,A);if(Kt(k),(await Me(i)).aborted)return{...n,cancelled:!0};let L=ee("schedule.alapPass"),F=await Jo(C.reversed,p,m,this.adapter,t,i);if(Kt(L),(await Me(i)).aborted)return{...n,cancelled:!0};let T=ee("schedule.diff"),I=[];for(let[_,j]of F){let W=this.adapter.getActivity(_);if(!W)continue;let Z=W.startDate.getTime()!==j.startDate.getTime(),J=W.endDate.getTime()!==j.endDate.getTime();(Z||J)&&I.push(_)}return Kt(T),Kt(a),{plans:F,updatedIds:I,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),n}}},sp=!1;function cp(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:sp}function ee(e){return{name:e,startedAt:performance.now()}}function lp(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Kt(e){if(!cp())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function dp(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=Ho(i,t);return up(n,t,r)}function up(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let o of r.getAllActivities()){let s=String(o.id);o.constraintType===H.ALAP&&!i.has(s)&&(n.add(s),i.add(s))}if(n.size===0)return{idSet:i,links:e.links};let a=[...e.links];for(let o of t)(n.has(String(o.source))||n.has(String(o.target)))&&a.push(o);return{idSet:i,links:a}}function fp(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let o=i?Array.from(i):t;return jr(o,r)}if(!i)return n;let a=xo(n.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function ss(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 o of t.getIncomingLinkIds(e)){let s=t.getLink(o);if(!s)continue;let c=t.getActivity(s.source);if(!c||c.constraintType==="alap"||Vt(i.type)&&(s.type===U.START_TO_FINISH||s.type===U.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=On(c,n,s.type),f=bn.computeLagBetweenTasks(d,u,a);f!==s.lag&&mr({kind:"update",linkId:s.id,lag:f},t)}}function cs(e,t){let r=t.getActivity(e);r&&Vt(r.type)&&(r.durationHours=0)}function ni(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 ls(e){return Number(e.toFixed(2))}function gr(e){for(let t of pp(e))us(t,e)}function ds(e,t){for(let r of e)us(r,t)}function pp(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,yp(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function yp(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function us(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let n of r){let a=t.getActivity(n);a&&i.push({progress:Number(a.progress??0),ponderator:Number(a.ponderator??0)})}Nn(e,i,t)}function Nn(e,t,r){let i=r.getActivity(e);if(!i)return;let n=ni(t);if(n===null){let a=r.getProgressFallback(e);a!==null&&r.setActivityField(e,S.PROGRESS,a);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(i.progress??0)),r.setActivityField(e,S.PROGRESS,ls(n))}function fs(e,t,r){let i=[e];for(;i.length>0;){let n=i.pop();if(n===void 0)continue;let a=r.getChildren(n);a.length!==0&&(r.setProgressFallback(n,t),i.push(...a))}}function Ct(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function He(e,t,r=!0,i={}){let n=t?Ar(e,t):vp(e),a=r?i.progressMode??"freeze-when-no-contribution":"skip";await hp(n,e,a,{recomputeRealWork:i.recomputeRealWork??!1})}function ai(e,t){ps(e,t,"skip")}async function hp(e,t,r,i={recomputeRealWork:!1}){let a=0;for(let o of e)ps(o,t,r,i.recomputeRealWork),a+=1,a%200===0&&await it()}function Ar(e,t){let r=new Set,i=new Map;for(let o of t)mp(o,e,r,i);if(r.size===0)return[];let n=Array.from(r),a=gp(n,i);return ys(n,a)}function mp(e,t,r,i){let n=t.getParentId(e);for(;n&&!N(n);){if(r.has(n))return;r.add(n);let a=t.getParentId(n);i.set(n,a),n=a}}function gp(e,t){let r=new Map;for(let i of e){if(r.has(i))continue;let n=[],a=new Set,o=i;for(;o&&!N(o)&&!r.has(o)&&!a.has(o);)n.push(o),a.add(o),o=t.get(o)??null;let s=o?r.get(o)??0:0;for(let c=n.length-1;c>=0;c-=1)s+=1,r.set(n[c],s)}return r}function Ap(e,t,r){let i=null,n=null,a=0,o=[];for(let s of e){let c=t.getActivity(s);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+=Ip(c,t.getChildren(s).length>0)),o.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:a,weightedChildren:o}}function ps(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 o=Ap(a,t,i);if(o.minStart===null||o.maxEnd===null)return;let s=String(n.calendarId??""),c=t.calendarReader.getCalendar(s),l=new Date(o.minStart),d=new Date(o.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u),r!=="skip"&&Nn(e,o.weightedChildren,t),i&&t.setActivityField(e,"realWorkHours",o.realWorkSum)}function Ip(e,t){return t?Number(e.realWorkHours)||0:Ct(e.workHours,e.progress)}function vp(e){let t=Cp(e),r=Sp(t,e);return ys(t,r)}function Cp(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Sp(e,t){let r=new Map;for(let i of e)r.set(i,kp(i,t));return r}function kp(e,t){let r=0,i=e;for(;i&&!N(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function ys(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var hs={updateActivityDuration:cs,updateTaskTiming:Dp("updateTaskTiming"),adjustLinkLagOnTaskMove:ss,recordLastStartDate:Tp};function Tp(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function re(e,t,r,i){for(let n of t){let a=n in hs?hs[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 Dp(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function M(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function V(e){return{ok:!1,reason:e}}function $(){return{valid:!0}}function nt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function Y(){return{allowed:!0}}function X(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function G(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 ms={targetField:"name",canEdit(){return Y()},parseInput(e){return typeof e!="string"?V("not_a_string"):M(e)},validate(){return $()},transform(e,t){return G({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var gs={targetField:"description",canEdit(){return Y()},parseInput(e){return typeof e!="string"?V("not_a_string"):M(e.trim())},validate(){return $()},transform(e,t){return G({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Ft(e){return e.constraintType??H.ASAP}var oi=100;function ie(e){return e.progress>=oi}function at(e,t){return wt(e.type,t.hasChildren(e.id))}function As(e){return e.progress>0}function Is(e){return e.hasLookaheadTasks}function ge(e,t){return Math.round(Math.ceil(e*t*60)/60)}var je=e=>({endDate:e});function ne(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 ci(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"),o=i("day"),s=Date.UTC(n,a-1,o,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(s)),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"))-s;return new Date(s-u)}function _p(e,t){let r=ne(t,"UTC");for(;!e.isWorkTime(r,pt.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=ne(r,"UTC");return r}function wn(e,t){return e.getClosestWorkTime({direction:rt.FUTURE,date:t,unit:pt.HOUR})}function Fn(e,t){let r=_p(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:rt.PAST,date:i,unit:pt.HOUR})}var si=new Set(["snet","snlt","mso"]),xn=new Set(["fnet","fnlt","mfo"]),ae=new Set(["asap","alap"]),li="snet";function Yt(e,t,r){let i=ne(e,"UTC");if(!si.has(r)&&!xn.has(r))return i;let n=si.has(r)?wn(t,i):Fn(t,i),a=new Date(i);return a.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),a}var oe=()=>({constraintType:li});var Ae=e=>({constraintDate:e}),vs=e=>({constraintDate:e});var Cs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ss={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 Ve(e,t,r){return co(e,t,r)}function Ke(e,t,r){return lo(e,t,r)}var Ts={targetField:"durationHours",canEdit(e,t){return ie(e)?X("completed","cant_edit_completed_activity"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isFinite(i)?M(ge(i,r.hoursPerDay)):V("not_a_number")},validate(e,t,r){return ks(r)?nt(Ss.NEGATIVE_DURATION):Ep(t,r)?nt("unchanged"):$()},transform(e,t,r){if(ks(t))return G({},{autoSchedule:!1,postProcessors:[]});let i=Rp(e,t,r),n=Pp(e,t,r,i.violated);return{...G(n,{autoSchedule:!0,postProcessors:[Cs.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:Ke(i.constraintType,i.constraintDate,Ds(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ks(e){return Math.sign(e)===-1}function Ep(e,t){return e===t}function Rp(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 Ve(n,e.constraintDate,a)}function Pp(e,t,r,i=!1){let n={};i&&Object.assign(n,oe(),Ae(e.startDate));let a=dr(e.durationHours,t);a&&(n.type=a),n.durationHours=t;let o=Ds(e,t,r);return o&&Object.assign(n,je(o)),n}function Ds(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var Ye=e=>({realWorkHours:e});var Lp=0,Op=oi,_s={targetField:"progress",canEdit(e,t){return Is(e)?X("has_lookahead_tasks","cant_edit_actvity_with_task"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(e,t,r){return bp(r)?nt("out_of_range"):$()},transform(e,t,r){let i=he(t),n=e.progress!==t&&i,a=Np(t),o=xp(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...Ye(o.get(e.id)??0)},c=a?wp(e,t,i,r.hierarchy,o):[],l=a?Up(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=a?Wp(e,t):void 0;return G(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:"activity_progress_entry"};function bp(e){return e<Lp||e>Op}function Np(e){return e===oi||he(e)}function wp(e,t,r,i,n){return i.getDescendantIds(e.id).map(o=>({activityId:o,fields:Fp(t,r,n.get(o)??0)}))}function Fp(e,t,r){return{progress:e,autoScheduling:t,...Ye(r)}}function xp(e,t,r){let i=new Map,n=o=>{let s=0;for(let c of r.getChildHhInfo(o)){let l=r.hasChildren(c.id)?n(c.id):Ct(c.workHours,t);i.set(c.id,l),s+=l}return s},a=r.hasChildren(e.id)?n(e.id):Ct(e.workHours,t);return i.set(e.id,a),i}function Mp(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=a=>t.getChildProgressInfo(a).some(o=>t.hasChildren(o.id)),n=a=>t.getAncestorIds(a).length;return r.filter(a=>i(String(a))).map(String).sort((a,o)=>n(o)-n(a))}function Up(e,t,r){let i=new Map;i.set(e.id,t);for(let o of r.getDescendantIds(e.id))i.set(o,t);let n=[...Mp(e,r),...r.getAncestorIds(e.id)],a=[];for(let o of n){let s=Bp(o,i,r);s!==null&&(i.set(o,s),a.push({activityId:o,fields:{progress:s}}))}return a}function Bp(e,t,r){let i=r.getChildProgressInfo(e).map(a=>({progress:t.has(a.id)?t.get(a.id):a.progress,ponderator:a.ponderator??0})),n=ni(i);return n===null?null:Number(n.toFixed(2))}function Wp(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Es={targetField:"cost",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(String(e).trim()==="")return M(0);let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(){return $()},transform(e,t,r){let i=Hp(e,t,r.hierarchy);return G({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_budgeted_entry"};function Hp(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let o=0;for(let s of r.getChildCostInfo(a))o+=i.has(s.id)?i.get(s.id):s.cost;i.set(a,o),n.push({activityId:a,fields:{cost:o}})}return n}var Rs={targetField:"usedCost",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(String(e).trim()==="")return M(0);let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(){return $()},transform(e,t,r){let i=jp(e,t,r.hierarchy);return G({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:"activity_cost_spent_entry"};function jp(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let a of r.getAncestorIds(e.id)){let o=0;for(let s of r.getChildUsedCostInfo(a))o+=i.has(s.id)?i.get(s.id):s.usedCost;i.set(a,o),n.push({activityId:a,fields:{usedCost:o}})}return n}var Ps={targetField:"workHours",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(String(e).trim()==="")return M(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?V("not_a_number"):M(t)},validate(){return $()},transform(e,t,r,i){let n=Ls(t,e.progress),a=String(i).trim()===""?[]:Vp(e,t,n,r.hierarchy);return G({workHours:t,...Ye(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Ls(e,t){return Ct(e,t)}function Vp(e,t,r,i){let n=new Map,a=new Map;n.set(e.id,t),a.set(e.id,r);let o=[];for(let s of i.getAncestorIds(e.id)){let c=0,l=0;for(let d of i.getChildHhInfo(s)){let u=n.has(d.id)?n.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??Ls(d.workHours,d.progress);c+=u,l+=f}n.set(s,c),a.set(s,l),o.push({activityId:s,fields:{workHours:c,...Ye(l)}})}return o}function Ir(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Mn(e,t){return e.getTime()<t.getTime()}function Ie(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var di=e=>({durationHours:e});var Kp="sir-apply",Os={targetField:"startDate",canEdit(e,t,r){return at(e,t)?X("summary","summary_column_value"):As(e)?r?.eventSource!==Kp?X("has_progress","cant_edit_activity_with_progress"):ie(e)?X("completed","cant_edit_completed_activity"):Ie(r.newValue)?Ir(e.startDate,r.newValue)?Y():r.newValue.getTime()>e.startDate.getTime()?X("sir_start_after_progress","sir_cant_move_start_after_progress"):Y():Y():Y()},parseInput(e,t,r){return Ie(e)?M(ne(e,"UTC")):V("invalid_date")},validate(e,t,r,i){if(Ir(t,r))return nt("unchanged");let n=Yp(e,r,i);return n||$()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=wn(i,t),a=e.type==="milestone",o=a?n:i.calculateEndDate(n,e.durationHours),s=n;return{...G({startDate:n,...je(o),...a?di(0):{},...oe(),...Ae(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Gp(e,n,i)}},trackEvent:"activity_start_date_entry"};function Yp(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=ne(i,"UTC");return t.getTime()<n.getTime()?nt("before_parent_start"):null}function Gp(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=or(Ft(e),t,i),a=Ve(Ft(e),e.constraintDate,n);if(a.violated)return Ke(a.constraintType,a.constraintDate,n)}var $p=99.999,Ns={targetField:"endDate",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):zp(e)?X("completed","cant_edit_completed_activity"):Y()},parseInput(e,t,r){if(!Ie(e))return V("invalid_date");let i=ne(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,pt.DAY)?M(Fn(n,i)):M(n.getClosestWorkTime({direction:"past",date:i,unit:pt.HOUR})):M(i)},validate(e,t,r,i){if(Ir(e.endDate,r))return nt("unchanged");if(qp(r,e))return nt("before_date_origin");if(Jp(r,e))return nt("before_start_date");let n=Xp(r,e,i);return n||$()},transform(e,t,r){let i=Qp(e,t),n=Zp(e,t,r,!!i);return{...G(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:"activity_end_date_entry"};function zp(e){return e.progress>=$p}function qp(e,t){return t.dateOrigin?Mn(e,t.dateOrigin):!1}function Jp(e,t){return Mn(e,t.startDate)}function Xp(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,pt.DAY)?null:nt("not_working_day"):null}function Qp(e,t){if(Ft(e)===H.MSO)return;let i=or(Ft(e),e.startDate,t),n=Ve(Ft(e),e.constraintDate,i);if(n.violated)return Ke(n.constraintType,n.constraintDate,i)}function Zp(e,t,r,i=!1){let n={};Vt(e.type)&&!i&&bs(e)?Object.assign(n,Ae(e.startDate)):(i||bs(e))&&Object.assign(n,oe(),Ae(e.startDate));let s=ty(e,t,r),c=dr(e.durationHours,s);return c&&(n.type=c),Object.assign(n,di(s)),n.endDate=t,n}function bs(e){return ae.has(Ft(e))}function ty(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var ey=new Set(Object.values(H)),ws={targetField:"constraintType",canEdit(e,t){return ie(e)?X("completed","cant_edit_completed_activity"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){let t=String(e).toLowerCase();return ry(t)?M(t):V("invalid_constraint_type")},validate(){return $()},transform(e,t,r){let i=iy(e,t,r);return G(i,{autoSchedule:!0})}};function ry(e){return ey.has(e)}function iy(e,t,r){let i=ay(e,t);return{constraintType:t,...vs(ny(e,t,i,r))}}function ny(e,t,r,i){if(e.type!=="milestone"||!r)return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?Yt(r,n,t):r}function ay(e,t){return ae.has(t)?null:si.has(t)?e.startDate:xn.has(t)?e.endDate:e.constraintDate}var Fs={targetField:"constraintDate",canEdit(e,t){return ie(e)?X("completed","cant_edit_completed_activity"):at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){return Ie(e)?M(e):V("invalid_date")},validate(){return $()},transform(e,t,r){let i=xs(e)?li:Ft(e),n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=Yt(t,n,i),o=oy(e,a);return G(o,{autoSchedule:!0})}};function oy(e,t){return{constraintDate:t,...xs(e)?oe():{}}}function xs(e){return ae.has(Ft(e))||!e.constraintType}var Ms={targetField:"calendarId",canEdit(){return Y()},parseInput(e){let t=String(e).trim();return sy(t)?V("empty_calendar"):M(t)},validate(e,t,r,i){return cy(e.calendarId,r)?nt("unchanged"):i.calendars.getCalendar(r)?$():nt("unknown_calendar")},transform(e,t,r){return G(ly(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function sy(e){return e===""}function cy(e,t){return e===t}function ly(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let a=e.durationHours===0,o=a?dy(e.startDate):e.startDate,s=n.getClosestWorkTime({date:o,direction:"future",unit:"hour"});if((!e.autoScheduling||a||n.getWorkHours(e.startDate).length===0)&&(i.startDate=s),!e.autoScheduling)return i;let c=i.startDate??e.startDate;Object.assign(i,je(n.calculateEndDate(c,e.durationHours)))}return i}function dy(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Us={targetField:"customId",canEdit(e,t){return at(e,t)?X("summary","summary_column_value"):Y()},parseInput(e){if(e==null)return V("empty_custom_id");if(typeof e!="string")return V("not_a_string");let t=e.trim();return t.length===0?V("empty_custom_id"):t.length>20?V("exceeds_max_length"):M(t)},validate(){return $()},transform(e,t){return G({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var Bs={targetField:"subcontractId",canEdit(){return Y()},parseInput(e){if(e==null)return M(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return M(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?V("not_an_integer"):M(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?V("not_an_integer"):M(e):V("not_an_integer")},validate(){return $()},transform(e,t){return G({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function vr(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 ui(e){return e.some(t=>vr(t)===null)}var Ws={targetField:"responsableIds",canEdit(){return Y()},parseInput(e){return e==null?M([]):Array.isArray(e)?M(e):V("not_an_array")},validate(e,t,r){return ui(r)?nt("missing_id"):$()},transform(e,t){let r=t.map(vr).filter(i=>i!==null);return G({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Hs={targetField:"tagIds",canEdit(){return Y()},parseInput(e){return e==null?M([]):Array.isArray(e)?M(e):V("not_an_array")},validate(e,t,r){return ui(r)?nt("missing_id"):$()},transform(e,t){let r=t.map(vr).filter(i=>i!==null);return G({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var uy=new Map([[S.TEXT,ms],[S.DESCRIPTION,gs],[S.DURATION,Ts],[S.PROGRESS,_s],[S.COST,Es],[S.USED_COST,Rs],[S.HH_WORK_TIME,Ps],[S.START_DATE,Os],[S.END_DATE,Ns],[S.CONSTRAINT_TYPE,ws],[S.CONSTRAINT_DATE,Fs],[S.CALENDAR_ID,Ms],[S.CUSTOM_ID,Us],[S.SUBCONTRACT_ID,Bs],[S.RESPONSABLES,Ws],[S.TAGS,Hs]]);function se(e){return uy.get(e)}var ot={APPEND:"append",REPLACE:"replace"},fi={SIR_AUTO_REJECT:"sir-auto-reject"},pi={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},yi={VIOLATION:"constraint_violation"},Gt={INIT:"init",UNDO:"undo",REDO:"redo"};function Ge(e,t){if(!t||t.type!=="constraint")return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:yi.VIOLATION,activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var fy=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],js=new Set(fy);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",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Cr={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",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"};function st(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function Vs(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function $t(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Ht(e.constraintDate),dateOrigin:Ht(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Ht(t.startDate),endDate:Ht(t.endDate)})),baselineSnapshot:py(e.baselineSnapshot),criticalPath:yy(e.criticalPath)}}function Ht(e){return e===null?null:new Date(e)}function py(e){return e===null?null:{...e,startDate:Ht(e.startDate),endDate:Ht(e.endDate)}}function yy(e){return e===null?null:{...e,earlyStart:Ht(e.earlyStart),earlyFinish:Ht(e.earlyFinish),lateStart:Ht(e.lateStart),lateFinish:Ht(e.lateFinish)}}var Gs=200;function ce(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%Gs===0&&await it();let a=e.getActivity(n);a&&r.set(n,et(a))}return r}function et(e){return $t(e)}function hi(e,t){let r=e.getActivity(t);return r?$t(r):null}function le(e,t,r){Ks(e,t,r.patch);for(let i of r.cascadeMutations??[])Ks(e,i.activityId,i.fields)}function Ks(e,t,r){for(let[i,n]of Object.entries(r)){if(!js.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);st(e,t,i,n)}}async function mi(e,t,r,i){let n=[],a=0;for(let o of r){a+=1,a%Gs===0&&await it();let s=hy(e,t,o,i);s&&n.push(s)}return n}function hy(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 my(r,i.get(r),n);let o=Bn(a,n);return gy(o,i,r,n),a&&Object.keys(o).length===0?null:{id:r,kind:a?"updated":"created",fields:o,after:et(n)}}function my(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:et(r)}}function gy(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 Bn(e,t){let r={},i=e??{},n=t,a=new Set([...Object.keys(i),...Object.keys(n)]);a.delete(b.CALENDAR_DURATION);for(let o of a)(Object.hasOwn(i,o)!==Object.hasOwn(n,o)||!Un(i[o],n[o]))&&(r[o]={before:Ys(i[o]),after:Ys(n[o])});return r}function Ys(e){return e===null||typeof e!="object"?e:O(e)}function Un(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((o,s)=>Un(o,t[s]));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(o=>Object.hasOwn(i,o)&&Un(r[o],i[o]))}function gi(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 Wn(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 Ai(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 o=e.getActivity(a.activityId);if(!o)continue;let s=et(o);a.before!==void 0&&(s.correlativeId=a.before),i.set(a.activityId,s)}}var Ay=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function zt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let s=new Date(e);if(Number.isNaN(s.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return s}let t=e.match(Ay);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,a,o]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(a),Number(o)))}function $e(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 Iy=e=>e.type==="project",vy=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let a=o=>o instanceof Date?o:zt(String(o));return $e(a(e.startDate),a(e.endDate),t,n)};function Cy(e,t,r){let i=[],n=(o,s)=>{let c=r.getActivity(o);c&&c.expectedProgress!==s&&(r.setActivityField(o,"expectedProgress",s),i.push(String(o)))},a=o=>{let s=r.getActivity(o);if(!s)return 0;if(!Iy(s)){let d=vy(s,t,r);return n(o,d),d}let c=0;for(let d of r.getChildren(o)){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(o,l),l};for(let o of e)a(o);return i}function Ce(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Cy(r,t,e)}var Sy=e=>e.type==="project",ky=e=>gt(e),Ty=(e,t,r,i)=>{let n=ky(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:$e(n.startDate,n.endDate,t,a)};function Hn(e,t,r,i=null){let n=[],a=(s,c)=>{let l=r.getActivity(s);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(s,"expectedProgressBaseline",c),n.push(s))},o=s=>{let c=r.getActivity(s);if(!c)return 0;if(!Sy(c)){let u=Ty(c,t,r,i);return a(s,u),u}let l=0;for(let u of r.getChildrenIds(s)){let f=o(u),p=r.getActivity(u),y=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*y}let d=l/100;return a(s,d),d};for(let s of e)o(s);return n}function ze(e,t,r=null){let i={getChildrenIds:a=>e.getChildren(String(a)).map(o=>String(o)),getActivity:a=>e.getActivity(a),setActivityField:(a,o,s)=>st(e,a,o,s),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},n=[];return e.forEachActivity((a,o)=>{a.parentId===null&&n.push(o)}),Hn(n,t,i,r)}var jn=Jt.BASELINE;function Ii(e){return e===Jt.ACTUAL?Jt.ACTUAL:jn}var $s=e=>Math.round(e*100)/100;function Dy(e,t){return(t===Jt.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function _y(e,t){let r=$s(e),i=$s(t);return r>99.99?mt.DONE:i>r?mt.OVERDUE:e>0&&r>i?mt.ADVANCEMENT:e===0&&t===0?mt.WAITING:e>0&&r<i?mt.DOING:mt.WAITING}function qt(e,t){let r=[];return e.forEachActivity((i,n)=>{let a=typeof i.progress=="number"?i.progress:0,o=_y(a,Dy(i,t));i.status!==o&&(st(e,n,S.STATUS,o),r.push(n))}),r}function Vn(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)=>o=>o===void 0?t[n]():(t[a](o),i),i={__isMomentShim:!0,clone:()=>Vn(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}Vn.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Lt=Vn;function Ey(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function vi(e){return Ey(e)&&!isNaN(e.getTime())}function D(e,t,r,i){if(!vi(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 _t(e){if(!vi(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 Ry=e=>e?e.$level===1:!1,Py=e=>e.type==="project",Ly=e=>e.$level!==0,Oy=e=>e.type==="task",by=e=>e.type==="task"||e.type==="milestone",vt={byFirstLevel:Ry,filterByParentType:Py,avoidSubproject:Ly,byTaskType:Oy,byTaskTypeAndMilestone:by};var h=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var z=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function Se(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function zs(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let a=Ny({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let o=wy({gantt:t,subprojectsWithNoLinks:a}),s=Fy({gantt:t,childrenIds:o,linkProperty:n,getArrayOfLinkedActivities:xy,calculations:i});return new Set(s.map(c=>c.id))}catch(a){throw a}}function Ny(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(vt.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function wy(e){let{gantt:t,subprojectsWithNoLinks:r}=e,i=new Set;for(let n of r)t.getChildren(n).filter(s=>{let c=t.getTask(s),l=vt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>i.add(s));return[...i]}function Fy(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:a}=e,o=[];for(let s of r){let c=t.getTask(s),l=c[i]||[];n({gantt:t,links:l,linkDirection:i==="$source"?"target":"source"}).every(f=>a.has(f))&&o.push(c)}return o}function xy(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let a of r){let o=t.getLink(a);if(!o){`${a}`;continue}let s=Number(o[i]);n.push(s)}return n}function qs({gantt:e,linkProperty:t,direction:r}){try{let i=My(e,t);if(r==="forward")return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Uy(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function My(e,t){return e.getTaskByTime().filter(vt.avoidSubproject).filter(vt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Uy(e,t,r){let i=[],n=new Set;return e.forEach(a=>{let o=Number(a.parent),s=t.getTask(o);s&&(s[r].length>0?n.add(a.id):s.constraint_type!=="fnlt"&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function Js({gantt:e,direction:t,linkProperty:r}){try{let i=By(e),n=new Set,a=new Set,o=new Set;t==="backward"&&jy(i).forEach(d=>{n.add(d.id)});let s=Wy(i,t,r),c=Hy(i,s);return s.forEach(l=>{a.add(l.id)}),c.forEach(l=>{o.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:a,pendingParentsWithLinks:o}}catch(i){throw i}}function By(e){return e.getTaskByTime().filter(vt.filterByParentType).filter(vt.avoidSubproject)}function Wy(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let a=n.length>0,o=i.constraint_type||"",s=o!=="fnlt";return t==="forward"?!a&&s&&o!=="snet":!a&&s})}function Hy(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function jy(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Xs({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let a=t.getTask(n),o=Vy(r),s=Ky(r),c=a[o];if(!Array.isArray(c))return;Yy(t,c,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Vy(e){return e==="forward"?"$source":"$target"}function Ky(e){return e==="forward"?"target":"source"}function Yy(e,t,r){return t.map(i=>{let a=e.getLink(i)[r];return Number(a)})}var Sr={identifySecondLevelActivities:zs,identifyInitialActivities:qs,identifyParentsWithAndWithoutLinks:Js,identifyForbiddenActivities:Xs};function Ci(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Kn({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===z.FS&&t===0?_t({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):kr(r,e,i,n)}function Qs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:D(r,n,e,i),ef:n}}function Zs({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),a=D(r,n,e,i);return{es:n,ef:a}}function kr(e,t,r,i){if(![z.FS,z.SS,z.FF].includes(t))return e;let a=[z.FS,z.SS].includes(t)?"future":"past";return _t({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:i})}var Yn=class{constructor(t,r,i,n){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=i,this.linkCandidates=n,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=Ci(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=Se(i),a=r.linkLag,o=r.es,s=r.ef,c=null;if(n==="ss")c=this.calculateSSLink({lag:a,predecessorEs:o});else if(n==="ff")c=this.calculateFFLink({lag:a,predecessorEf:s});else if(n==="fs")c=this.calculateFSLink({lag:a,predecessorEf:s});else if(n==="sf")c=this.calculateSFLink({lag:a,predecessorEs:o,predecessorEf:s});else continue;c&&(this.linkCandidates?.set(r.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let r=Zs({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=Qs({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=Kn({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=D(this.activityCalendar,i,t,this.activity);t>0&&(n=kr(n,"ss",this.activityCalendar,this.activity));let a=D(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let i=Kn({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=D(this.activityCalendar,i,t,this.activity),a=D(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(a=kr(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=_t({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=D(this.activityCalendar,i,t,this.activity),a=D(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let i=D(this.activityCalendar,r,t,this.activity),n=D(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=kr(n,"sf",this.activityCalendar,this.activity)),{es:n,ef:i}}},tc=Yn;var Gn=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=Se(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,o=r.lf;if(i==="ss"){let s={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(s);t.push({ls:c,lf:l})}if(i==="ff"){let s={lag:n,workTime:o,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(s);t.push({ls:c,lf:l})}if(i==="fs"){let s={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(s);t.push({ls:c,lf:l})}if(i==="sf"){let s={lag:n,workTime:o,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(s);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:D(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,o=null;if(t===0)return a=D(this.activityCalendar,r,n,this.activity),o=D(this.activityCalendar,a,i,this.activity),{ls:o,lf:a};let s=r;return t>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),a=D(this.activityCalendar,s,n,this.activity),o=D(this.activityCalendar,a,i,this.activity),{ls:o,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let o=null,s=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return o=D(this.activityCalendar,l,n,this.activity),o=this.getLastWorkingHour(o,this.activityCalendar,"past"),s=D(this.activityCalendar,o,i,this.activity),{ls:s,lf:o}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),o=D(this.activityCalendar,c,n,this.activity),s=D(this.activityCalendar,o,i,this.activity),a||(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),{ls:s,lf:o}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let a=null,o=null,s=r;return o=D(this.activityCalendar,s,i,this.activity),a=D(this.activityCalendar,o,n,this.activity),{ls:o,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:a=!1}){let o=null,s=null;if(t===0)return s=D(this.activityCalendar,r,i,this.activity),o=D(this.activityCalendar,s,n,this.activity),{ls:s,lf:o};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),s=D(this.activityCalendar,c,i,this.activity),o=D(this.activityCalendar,s,n,this.activity),{ls:s,lf:o}}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:D(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=Lt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),_t({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 o=a.split("-")[0];if(!o.includes(":"))return!1;let s=o.split(":");return s.length<2?!1:(o=parseInt(s[0],10),Lt.isMoment(r)?r.hours()===o:i.getUTCHours()===o)}},ec=Gn;function rc(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:a,direction:o,linkCandidates:s}=e,c=t[r],l=Gy(t),d=null;if(o==="forward"){let u=$y(c,i,n,a);d=new tc(u,t,a,s),d=d.calculate()}else{let u=zy(c,i,n,a);d=new ec({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function Gy(e){return{duration:e.duration,calendarId:e.calendar_id}}function $y(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 o=Number(a[t]),s=r.get(o);return s?{linkId:String(a.id),es:s.es,ef:s.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${o}`),null)}).filter(Boolean)}function zy(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 o=Number(a[t]),s=r.get(o);if(!s)return null;let c=i.getTask(o);return c?{ls:s.ls,lf:s.lf,linkLag:a.lag||0,linkType:a.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function ac(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if(qy(t.id,r))return null;let a=Jy(t.id,i),o=Xy(a,r);return o.length===0?null:Qy(o,n)}function qy(e,t){return t.has(e)}function Jy(e,t){let r=t.get(e);return r?r.childrens:[]}function Xy(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Qy(e,t){if(t==="forward"){let r=ic(e,"es"),i=nc(e,"ef");return{es:r,ef:i}}else{let r=ic(e,"ls"),i=nc(e,"lf");return{ls:r,lf:i}}}function ic(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function nc(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var $n={parentWithLinks:rc,parentWithNoLinks:ac};var zn=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.linkCandidates=t.linkCandidates,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let i=[h.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=$n.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});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=$n.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(o=>t.includes(o[0])).map(o=>o[1]),{minEs:n,maxEf:a}=i.reduce((o,{es:s,ef:c})=>({minEs:new Date(Math.min(o.minEs.getTime(),new Date(s).getTime())),maxEf:new Date(Math.max(o.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(o=>t.includes(o[0])).map(o=>o[1]),{minLs:n,maxLf:a}=i.reduce((o,{ls:s,lf:c})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(s).getTime())),maxLf:new Date(Math.max(o.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)})}},oc=zn;var qn=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),o=this.getDeepestLevel(a),s=this.createResult(r,i,o,a);this.structureOfParents.set(r.id,s)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(vt.byFirstLevel).filter(vt.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),o=Number(t.parent);i.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(o);o!=null&&c&&this.addChildToParent(o,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),o={level:n,hasLink:a,childrens:[]};r.add(i),this.singleParents.set(i,o)}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:o,allTasks:s}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:o,allChildrens:s,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},sc=qn;var Jn=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[o,s]of a)if(s.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(o);this.calculateParentWithNoLinks(l,s);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(vt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=Sr.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=Sr.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 sc({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((o,s)=>{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),o({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:a})})}identifySecondLevelActivities(){try{let t=Sr.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}=Sr.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,o)=>{if(i.has(o))return;let s=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);s.push(u)}}),s=s.filter(l=>n.has(l)||i.has(l)),r.set(o,s)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,a=[],o=s=>{if(n.has(s))throw new Error("Cyclical dependency detected",{cause:{nodeId:s}});if(!i.has(s)&&!r.has(s)){n.add(s);let c=t.get(s)||[];for(let l of c)o(l);n.delete(s),i.add(s),a.push(s)}};for(let s of t.keys())!i.has(s)&&!r.has(s)&&o(s);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 s=i.start_date,c=i.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:Lt(i.start_date).clone(),lf:Lt(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=Lt(t.start_date).clone(),n=Lt(t.end_date).clone(),a=t.duration,o=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=t.constraint_type||h.ASAP;if(o.includes(s))n=this.projectDates.end_date,i=D(r,n,-a,t);else{let c=[h.SNLT,h.MSO],l=[h.FNLT,h.MFO];c.includes(s)&&(i=t.constraint_date,n=D(r,i,a,t)),l.includes(s)&&(n=t.constraint_date,i=D(r,n,-a,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||h.ASAP,a=this.projectDates.end_date,o=[h.ASAP,h.ALAP,h.SNET,h.FNET],s=[h.SNLT,h.FNLT];if(o.includes(n))i=Math.max(t.end_date,a);else if(n===h.MSO)i=t.end_date;else if(n===h.MFO||s.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 oc({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,linkCandidates:this.linkCandidates,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},de=Jn;function Zy(e,t,r){let i={es:null,ef:null};if(!e)return i;if([h.SNET,h.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=D(r,n,e.duration,e)}else if([h.FNLT,h.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=D(r,n,-e.duration,e),i.ef=n}else if(t===h.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=D(r,n,e.duration,e)}else if(t===h.MFO){let n=new Date(e.constraint_date);i.es=D(r,n,-e.duration,e),i.ef=n}return i}var Si=Zy;var Xn=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,this.linkCandidates=t.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,i=0,n,a=z.FS){let o=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${this.referenceActivity.calendar_id}`);let s=t,c=null,l=null,d=this.referenceActivity.type==="milestone";return d||(a===z.FS&&n===0?s=_t({dateBaseToCalculate:s,activityCalendar:o,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,o)),[z.FF,z.SF].includes(a)?(l=D(o,s,i,this.referenceActivity),c=D(o,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,o))):(c=D(o,s,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,o)),l=D(o,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,o=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,o,z.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,o=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,o,z.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,a=this.referenceActivity.duration,o=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,o,z.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,a=t.lag||0,o=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,o,z.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![z.FS,z.SS,z.FF].includes(r))return t;let a=[z.FS,z.SS].includes(r)?"future":"past";return _t({dateBaseToCalculate:t,activityCalendar:i,direction:a,activity:this.referenceActivity})}},cc=Xn;var Tr=class extends cc{constructor(t){super(t)}calculate(){if(this.links.length===0)return new de(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}});let a=this.calculateLink(n);return this.linkCandidates?.set(String(n.id),{targetId:String(this.referenceActivity.id),...a}),a}),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=D(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:a})}return Ci(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Qn=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),o=this.pendingParentsWithLinks.has(t),s=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(o&&s){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}o&&!s&&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(o=>this.calculations.has(o))}handleNonProjectActivity(t,r,i,n){let a=Number(r.parent),o=this.pendingParentsWithLinks.has(a),s=this.calculationOfParentsFromLinks.has(a);if(o&&!s||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!s)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)&&s){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],o=this.gantt.getTask(a);o&&r.push(o)}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}},ki=Qn;var Zn=(e,t)=>()=>t()===e;var ta=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var th=16,ke=async e=>performance.now()-e>th?(await it(),performance.now()):e;var Dr=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:a,isCurrent:o})=>{let s=new Set(e),c=performance.now();for(;s.size>0;){if(!o())return;c=await ke(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!o())return;c=await ke(c),r([u])}for(let u of l){if(!o())return;i(u)&&d.add(u),a(u),n(u)&&d.delete(u)}s=d}};var ea=class extends de{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.linkCandidates=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 ki({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 Dr({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||h.ASAP,o=[h.SNET,h.SNLT,h.FNLT,h.FNET],s=[h.ASAP,h.ALAP,h.SNET,h.FNET,h.SNLT,h.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&&s.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),f=new Tr({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===h.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:i.text})):{es:d,ef:u}=new Tr({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===h.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let p=Si(i,a,c);if(o.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})),[h.MSO,h.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 y=i.end_date;a===h.MFO&&(y=Math.max(p.ef,i.end_date)),d=i.start_date,u=y}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=[h.SNET,h.FNET].includes(t)?"greater":"less",{es:a,ef:o}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:a,ef:o}}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)}},lc=ea;var ra=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===h.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,a=z.FS){let o=this.gantt.getCalendar(this.activity.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let s=t,c=this.activity.type==="milestone";if(c&&n===0){let d=D(o,s,r,this.activity),u=D(o,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:s,activityCalendar:o,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(a===z.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===z.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===z.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===z.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,o=t.lag;return this.calculateSuccessorTimes(i,n,a,o,z.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===h.ALAP?"ef":"lf",a=i[n],o=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,o,s,c,z.FF)}calculateFS(t,r){let i="ls";i=r===h.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,o=t.lag||0,s=-t.lag||0;return this.calculateSuccessorTimes(n[i],a,s,o,z.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,o=t.lag;return this.calculateSuccessorTimes(i,n,a,o,z.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=Lt(r).clone();return D(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i="past"){let n=t instanceof Date?t:new Date(t),a=Lt(n).clone();return this.isActivityInInitHour(r,n)&&i==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),_t({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 o=a.split("-")[0];if(!o.includes(":"))return!1;let s=o.split(":");return s.length<2?!1:(o=parseInt(s[0],10),Lt.isMoment(r)?r.hours()===o:i.getUTCHours()===o)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:o=!1}){let s=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,"past");return s=D(i,d,a,this.activity),s=this.getLastWorkingHour(s,i,"past"),c=D(i,s,n,this.activity),{ls:c,lf:s}}let l=r;return o||(l=this.getLastWorkingHour(r,i)),s=D(i,l,a,this.activity),c=D(i,s,n,this.activity),o||(s=this.getLastWorkingHour(s,i,"past",!0)),{ls:c,lf:s}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let o=null,s=null;if(t===0)return o=D(i,r,a,this.activity),s=D(i,o,n,this.activity),{ls:s,lf:o};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,"past")),o=D(i,c,a,this.activity),s=D(i,o,n,this.activity),{ls:s,lf:o}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a,isMilestone:o=!1}){let s=null,c=null;if(t===0)return c=D(i,r,n,this.activity),s=D(i,c,a,this.activity),{ls:c,lf:s};let l=r;return t<0&&!o&&(l=this.getLastWorkingHour(l,i,"future")),c=D(i,l,n,this.activity),s=D(i,c,a,this.activity),{ls:c,lf:s}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:a}){let o=null,s=null;return t===0?(s=D(i,r,n),o=D(i,s,a,this.activity),{ls:s,lf:o}):(s=D(i,r,n,this.activity),o=D(i,s,a,this.activity),{ls:s,lf:o})}},dc=ra;var ia=class extends dc{constructor(t){super(t),this.constraint=t.constraint||h.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new de(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(o=>{let s=this.gantt.getLink(o);if(!s)throw new Error("Link not found",{cause:{linkId:o}});if(!this.parentsWithFullProgress.has(Number(s.target)))return this.calculateLink(s)}).filter(o=>o);if(n.length!==0){let o=this.getMinLfFromLinks(n);if(n.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));n.push(this.calculateTheLsAndLfForTheActivity(d))}let s=this.getMinDateFromLinks(n),c=s.ls,l=s.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(s)),{ls:c,lf:l,minFromLinks:o}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=D(this.gantt.getCalendar(this.activity.calendar_id),s,-this.activity.duration,this.activity);n.push({ls:c,lf:s});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:D(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===h.ALAP)return h.ALAP;if(this.constraint===h.FNET||this.constraint===h.SNET)return"snet-fnet";if(this.constraint===h.FNLT)return h.FNLT}getSpecialParamForSf(){return!![h.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![h.MFO,h.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===h.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===h.SNET||this.constraint===h.SNLT||this.constraint===h.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===h.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===h.ALAP||this.constraint===h.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===h.ASAP)return new Date(Math.max(i,n));if(r===h.FNET||r===h.FNLT){let o=Math.min(i,a);return new Date(Math.max(i,o))}if(r===h.ALAP)return new Date(Math.min(i,n))}},uc=ia;function eh(e,t,r){let i={ls:null,lf:null};return r===h.MSO&&(i.ls=t.constraint_date,i.lf=D(e,i.ls,t.duration,t)),r===h.MFO&&(i.lf=t.constraint_date,i.ls=D(e,i.lf,-t.duration,t)),i}var fc=eh;var na=class extends de{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 ki({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 Dr({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(s=>r.includes(s[0])).map(s=>s[1]),{minLs:a,maxLf:o}=n.reduce((s,{ls:c,lf:l})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(s.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:o})}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||h.ASAP,o=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(o===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(o>0&&o<100&&(a===h.MSO||a===h.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===h.MSO||a===h.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===h.SNLT||a===h.FNLT)&&({ls:s,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:s,lf:c},a)),this.setCalculations(i,s,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),o=this.gantt.getCalendar(a.calendar_id);n=Si(a,i,o)}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===h.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===h.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 uc({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=fc(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([h.ASAP,h.ALAP,h.SNET,h.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=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([h.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=D(this.gantt.getCalendar(t.calendar_id),l.lf,-t.duration,t),u=t.constraint_date??d;n=new Date(Math.min(u.getTime(),d.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([h.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=t.constraint_date??l.lf;n=new Date(Math.min(d.getTime(),l.lf.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[h.MSO].includes(t.constraint_type)&&(n=t.constraint_date,a=D(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[h.MFO].includes(t.constraint_type)&&(a=t.constraint_date,n=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let o=this.projectDates.end_date,s=[{ls:n,lf:a}];s.push({ls:D(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t),lf:o});let c=this.getMinLfFromLinks(s);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}},pc=na;function yc(){return null}var hc=({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 aa=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=h.ASAP),t===h.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===h.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===h.SNET||t===h.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===h.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===h.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===h.MSO||t===h.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===h.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===h.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)})}},mc=aa;var oa=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===h.MSO||t===h.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=h.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:a}=this.getLinkData(i),o=this.gantt.getTask(n.target);if(!o)return{linkId:n.id,freeFloat:null,hasProgress:!1};let s=Number(o.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,o),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:s}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=h.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=0;return[h.SNLT,h.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=h.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===h.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),o=new Date,s=new Date;return o=a[t].sucessor,s=a[t].predecessor,{sucessorDateToCalculate:o,predecessorDateToCalculate:s}}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){let r=t===h.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===h.ALAP?r?.lf:r?.ef))}calculateFreeFloatOfRestriction(t){let r=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===h.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Se(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let a=(r?this.backwardMap:this.forwardMap).get(i),o=(t===h.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===h.ALAP?o?.ls:o?.es,c=t===h.ALAP?o?.lf:o?.ef;return{fs:{sucessor:a?.ls??a?.es,predecessor:c},ss:{sucessor:a?.ls??a?.es,predecessor:s},ff:{sucessor:a?.lf??a?.ef,predecessor:c},sf:{sucessor:a?.lf??a?.ef,predecessor:s}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=this.forwardMap.get(this.activity.id),n=t===h.MSO?i?.es:i?.ef,a=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(a))}getMinValue(...t){let r=t.filter(i=>i!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){if(!(t instanceof Date)||!(r instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime()))return Number.NaN;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==null?0:t/this.gantt.config.hoursPerDay}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)}},gc=oa;var Ac=e=>({totalFloat:new mc(e.totalFloat).getTotalFloat(),freeFloat:new gc(e.freeFloat).getFreeFloat()});var sa=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:a})=>{let o=performance.now(),s=new Map,c=new Map;for(let l of e){if(a&&!a())return{totalFloatMap:s,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=hc({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:f,freeFloat:p}=Ac(u);s.set(l,f),c.set(l,p),o=await ke(o)}return{totalFloatMap:s,freeFloatMap:c}};var ca=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.linkResidualHours=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let i=++this.currentCalculationId,n=Zn(i,this.getCurrentCalculationId),a=()=>n()&&r();try{let o=t||this.gantt;if(this.gantt=o||yc(),ta(this.gantt))return!1;let s=new lc(this.gantt);if(await s.calculateAsync(a),!a())return!1;let c=s.calculations,l=s.constraintsMap,d=new pc(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(s.linkCandidates,c,a);if(!u||!a())return!1;this.linkResidualHours=u;let{totalFloatMap:f,freeFloatMap:p}=await this.calculateFloatsAsync(s,d,a);return a()?(this.totalFloat=f,this.freeFloat=p,this.gantt.refreshData(),!0):!1}catch(o){throw this.forwardPathCalculations?.size,o}}async calculateLinkResidualHours(t,r,i=()=>!0){let n=new Map,a=performance.now();for(let[o,s]of t){if(a=await ke(a),!i())return null;let c=Number(s.targetId),l=this.gantt.getTask(c),d=r.get(c),u=s.ef,f=d?.ef,p=l&&this.gantt.getCalendar(l.calendar_id);if(!p||!(u instanceof Date)||!(f instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(f.getTime())){n.set(o,null);continue}let y=u.getTime(),C=f.getTime()>=y?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});n.set(o,Number.isFinite(C)?Object.is(C,-0)?0:C:null)}return n}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await sa({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){throw this.forwardPathCalculations?.size,n}}},Ic=ca;var rh=e=>e==="fnet"||e==="fnlt"||e==="mfo",ih=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function nh(e,t){let r=e.constraintDate;if(!r||!rh(e.constraintType))return r;let i=ih(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()?pn(e,t):r}function ah(e){let t=new Map,r=new Map,i=new Map;return{calculateEndDate:({start_date:n,duration:a})=>{let o=`${n.getTime()}|${a}`,s=t.get(o);if(s!==void 0)return new Date(s);let c=e.calculateEndDate(n,a);return t.set(o,c.getTime()),c},calculateDuration:({start_date:n,end_date:a})=>{let o=`${n.getTime()}|${a.getTime()}`,s=r.get(o);if(s!==void 0)return s;let c=e.calculateDuration(n,a);return r.set(o,c),c},getWorkHours:n=>e.getWorkHours(n),$gantt:{getClosestWorkTime:({date:n,dir:a,unit:o})=>{let s=o??"hour",c=`${n.getTime()}|${a}|${s}`,l=i.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:n,direction:a,unit:s});return i.set(c,d.getTime()),d}}}}function oh(e){let t=new Map;e.forEachActivity((n,a)=>t.set(String(a),n));let r=new Map,i=(n,a)=>{let o=r.get(n);if(o!=null)return o;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 sh(e){let t=new Set;e.forEachActivity((s,c)=>{t.add(String(c)),s.parentId!==null&&t.add(String(s.parentId))});let r=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&r.set(c,(r.get(c)??0)+1)}let i=new Map,n=new Map;for(let s of t){let c=Number(s);Number.isSafeInteger(c)&&c!==0&&r.get(c)===1&&(i.set(s,c),n.set(c,s))}let a=1,o=s=>{let c=String(s),l=i.get(c);if(l!==void 0)return l;for(;n.has(a);)a+=1;return i.set(c,a),n.set(a,c),a++};for(let s of t)o(s);return{toLegacy:o,toCanonical:s=>typeof s=="number"?n.get(s)??null:i.has(String(s))?String(s):null}}function ch(e,t){let r=oh(e),i=new Map;return e.forEachActivity((n,a)=>{let o=String(a);i.set(o,{id:t.toLegacy(o),parent:n.parentId===null?0:t.toLegacy(n.parentId),$level:r.get(o)??0,$source:e.getOutgoingLinkIds(o),$target:e.getIncomingLinkIds(o),start_date:n.startDate,end_date:n.endDate,duration:n.durationHours,progress:n.progress,type:n.type,calendar_id:n.calendarId,constraint_type:n.constraintType,constraint_date:nh(n,e)})}),i}function lh(e){let t=new Map;for(let o of e.values()){let s=t.get(o.parent);s?s.push(o):t.set(o.parent,[o])}let r=[],i=new Set,n=[],a=o=>{if(o)for(let s=o.length-1;s>=0;s-=1)n.push(o[s])};for(a(t.get(0));n.length>0;){let o=n.pop();i.has(o)||(i.add(o),r.push(o),a(t.get(o.id)))}if(r.length<e.size)for(let o of e.values())i.has(o)||r.push(o);return r}function dh(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 vc(e,t){let r=new Map,i=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=ah(f);return r.set(d,p),p},n=dh(e);await it();let a=sh(e),o=ch(e,a);await it();let s=[...o.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await it();let c=lh(o);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=a.toCanonical(l);return d===null?null:o.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:a.toLegacy(d.source),target:a.toLegacy(d.target),lag:d.lag}:null},getCalendar:i,getChildren:l=>{let d=a.toCanonical(l);return d===null?[]:e.getChildren(d).map(a.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>s,getSubtaskDates:()=>n,getCanonicalActivityId:a.toCanonical,refreshData:()=>{}}}var da=1e3,uh=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,fh=(e,t)=>typeof e!="number"||e<0?null:la(e,t);function ph(e){let t=fh(e.freeFloatDays,e.hoursPerDay),r=uh(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function yh(e,t){let r=new Map,i=0;for(let n of e.values())for(let a in n.linksFreeFloat)if(Object.hasOwn(n.linksFreeFloat,a)){if(++i>=da&&(i=0,await it(),!t()))return null;r.set(String(a),n.linksFreeFloat[a])}return t()?r:null}async function hh(e,t,r,i,n){let a=new Map,o=0;for(let s of t.forward?.keys()??[]){if(++o>=da&&(o=0,await it(),!n()))return null;let c=i(s);if(c===null)continue;let l=e.getActivity(c);l&&a.set(String(c),gh(s,Number(l.progress??0),t,r))}return n()?a:null}async function mh(e,t,r,i,n,a){let o=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=da&&(s=0,await it(),!a()))return null;o.set(String(c.id),ph({freeFloatDays:t.get(String(c.id)),residualHours:r.get(String(c.id)),hoursPerDay:n,sourceIsCritical:i.get(c.source)?.isCritical===!0,targetIsCritical:i.get(c.target)?.isCritical===!0,targetProgress:e.getActivity(c.target)?.progress}))}return a()?o:null}var la=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=e*t;return Number.isFinite(r)?Object.is(r,-0)?0:r:null};function gh(e,t,r,i){let n=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},a=r.forward?.get(e),o=r.backward?.get(e),s=la(r.totalFloat.get(e),i);return{criticalPath:{earlyStart:n(a?.es),earlyFinish:n(a?.ef),lateStart:n(o?.ls),lateFinish:n(o?.lf),totalSlackHours:s},isCritical:t<100&&s!==null&&s<=0,freeSlackHours:la(r.freeFloat.get(e)?.activityFreeFloat,i)}}var Ti=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function ua(e,t,r){let i=e.getActivity(t),n=i?.criticalPath,a=r.criticalPath;i&&n&&Ti(n.earlyStart,a.earlyStart)&&Ti(n.earlyFinish,a.earlyFinish)&&Ti(n.lateStart,a.lateStart)&&Ti(n.lateFinish,a.lateFinish)&&Object.is(n.totalSlackHours,a.totalSlackHours)&&Object.is(i.isCritical,r.isCritical)&&Object.is(i.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function fa(e,t,r){let i=e.getLink(t);!i||Object.is(i.freeSlackHours,r.freeSlackHours)&&Object.is(i.isCritical,r.isCritical)||(e.setLinkField(t,"freeSlackHours",r.freeSlackHours),e.setLinkField(t,"isCritical",r.isCritical))}async function pa(e,t,r=()=>!0){if(!r())return null;let i=await vc(e,t);if(!r())return null;let n=new Ic(i);if(!await n.calculate(i,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let o={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},s=await hh(e,o,t,i.getCanonicalActivityId,r);if(!s)return null;let c=await yh(o.freeFloat,r);if(!c)return null;let l=await mh(e,c,n.linkResidualHours,s,t,r);return l?{activities:s,links:l}:null}async function Cc(e,t,r=()=>!0){let i=await pa(e,t,r);if(!i||!r())return!1;for(let[n,a]of i.activities){if(!r())return!1;ua(e,n,a)}for(let[n,a]of i.links){if(!r())return!1;fa(e,n,a)}return!0}function qe(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 o=[...e.getChildren(String(n))],s;if(o.length===0){let c=gt(a),l=c&&Number(c.cost)||0;s=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of o)c+=i(String(l));s=c}return e.setActivityField(String(n),b.REAL_COST,s),r.push(String(n)),s};for(let n of t)i(n);return r}var Sc=new Set;var kc=new Set(["activity-outdent","activity-indent"]);var _r=new Set([S.TEXT,S.DESCRIPTION,S.COST,S.USED_COST,S.CUSTOM_ID,S.RESPONSABLES,S.SUBCONTRACT_ID,S.TAGS]),Ah=new Set(["activity-clipboard-clear","activity-copy","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"]),Ih=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Dc(e){return!Ih.has(e.kind)}var vh=new Set;function Ch(e){return e.kind==="inline-edit"?_r.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>_r.has(t.column)):!1}function ya(e,t){return!(Ah.has(e.kind)||t.has(e.kind)||Ch(e))}function ha(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:ya(e,vh)}function Te(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:ya(e,Sc)}function _c(e){return ya(e,kc)}function ma(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===S.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===S.PROGRESS):!1}function Sh(e){return _c(e)&&ma(e)}var Tc=new Set([S.PROGRESS,S.HH_WORK_TIME,S.DURATION,S.COST,S.USED_COST,S.REAL_COST]);function kh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?Tc.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>Tc.has(t.column)):!1}var yt={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 Ec(e,t,r){let i=new Set;t.ran&&i.add(yt.AUTOSCHEDULE),i.add(yt.PARENT_BOUNDS),kh(e)&&i.add(yt.PARENT_PROGRESS),ma(e)&&i.add(yt.REAL_WORK);let n=!r.skipAutoSchedule;return n&&_c(e)&&i.add(yt.EXPECTED_PROGRESS),n&&Sh(e)&&i.add(yt.REAL_COST),n&&Te(e)&&!r.skipCriticalPath&&i.add(yt.CRITICAL_PATH),i}async function q(e,t){let r=Dh(e.adapter),i=Th(t,r);i.has(yt.AUTOSCHEDULE)&&await Oh(e.adapter,t);let n=i.has(yt.AUTOSCHEDULE)?await Rh(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):Lh();return await bh(e.adapter,t,n.scheduledIds,i,r),await wh(e,i,t.now),n}function Th(e,t){let r=e.autoscheduleFrom!==null,i=!e.options.skipAutoSchedule&&r,n=new Set(Ec(e.action,{requested:r,ran:i},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(yt.PARENT_PROGRESS),n}function Dh(e){let t=new Set,r=new Set,i=e.peekWriteCapture();if(!i)return{affectedParents:t,dirtySeeds:r};let n=a=>{if(a===null||N(a))return;let o=String(a);t.add(o);let s=e.getChildren(o)[0];s!==void 0&&r.add(s)};return _h(e,i.ops,n),Eh(e,i.before,r,n),{affectedParents:t,dirtySeeds:r}}function _h(e,t,r){for(let i of t)if(i.kind==="insert"){let n=e.getActivity(i.activityId);n&&r(n.parentId)}else i.kind==="remove"&&r(i.before.parentId)}function Eh(e,t,r,i){for(let[n,a]of t){let o=e.getActivity(n);if(!o)continue;let s=!Object.is(a.progress,o.progress),c=!Object.is(a.ponderator,o.ponderator),l=!Object.is(a.parentId,o.parentId);(s||c)&&(i(o.parentId),r.add(String(n))),l&&(i(a.parentId),i(o.parentId),r.add(String(n)))}}async function Rh(e,t,r=!1){let i=t==="roots"?{}:{triggerId:t};r&&(i.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(i),a=Ph(e.adapter,n.updatedIds);return fr(e.adapter,n),a}function Ph(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 Lh(){return{scheduledIds:[]}}async function Oh(e,t){let r=t.collectDirty?t.collectDirty([]):Wn(t.recomputeParentsFrom,[]);r.size!==0&&await He(e,r,!1)}async function bh(e,t,r,i,n){i.has(yt.PARENT_PROGRESS)&&Nh(e,n.affectedParents);let a=t.collectDirty?t.collectDirty(r):Wn(t.recomputeParentsFrom,r);for(let o of n.dirtySeeds)a.add(o);await He(e,a,i.has(yt.PARENT_PROGRESS),{recomputeRealWork:i.has(yt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function Nh(e,t){for(let r of t){if(e.hasChildren(r))continue;let i=e.getProgressFallback(r);i!==null&&(e.setActivityField(r,"progress",i),e.setProgressFallback(r,null))}}async function wh(e,t,r){t.has(yt.EXPECTED_PROGRESS)&&r!==null&&(Fh(e.adapter)&&ze(e.adapter,r,e.defaultBaseCalendarId??null),Ce(e.adapter,r),qt(e.adapter,e.sector.statusCriteria)),t.has(yt.REAL_COST)&&qe(e.adapter),t.has(yt.CRITICAL_PATH)&&await Cc(e.adapter,e.sector.hoursPerDay)}function Fh(e){let t=!1;return e.forEachActivity(r=>{gt(r)&&(t=!0)}),t}var xh=new Set([S.CONSTRAINT_TYPE,S.CONSTRAINT_DATE]),Mh=new Set(["mso","mfo"]);function Di(e){return xh.has(e)}function _i(e){return e===S.CONSTRAINT_DATE}function Ei(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let a=n.constraintType;if(!a||ae.has(a)||Mh.has(a))return!1;let o=ga(n.startDate),s=ga(r.getLastStartDate(e));if(!s||!o||o.getTime()!==s.getTime())return!1;let c=Uh(t,a,String(n.calendarId??""),i),l=ga(n.constraintDate);return Bh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Uh(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?Yt(e,n,t):e}function ga(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 Bh(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function Ri(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await q(e,Rc(t)),a=!1;for(let{activityId:o,priorConstraintDate:s}of r){let c=i(o,s);a=a||c}if(a){let o=await q(e,Rc(t));n=Hh(n,o.scheduledIds)}return Te(t.action)&&await q(e,Wh(t)),{scheduledIds:n}}function Rc(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Wh(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Hh(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function Aa(e,t,r){let i=[];for(let n of r){let a=e.get(n);if(!a)continue;let o=a.pendingRequestIds??[];if(we({pendingRequestIds:o})&&t.getActivity(n)==null)for(let s of o)i.push({kind:fi.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:pi.ACTIVITY_DELETED})}return i}function St(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag),freeSlackHours:typeof e.freeSlackHours=="number"&&Number.isFinite(e.freeSlackHours)?e.freeSlackHours:null,isCritical:e.isCritical===!0};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}async function K(e,t){let r=Yh(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let f=$h(n);Gh(e,n,f,i,r)}let a=t.sirDetection,o=a==="before-diff"?Aa(i,e,r):[],s=Kh(t.correlativeShifts,r),c=await mi(e,i,r,s),l=a==="after-diff"?Aa(i,e,r):o,d=t.warnings??[],u=Vh(t.links??[],n?jh(e,n):[]);return{source:t.source,activities:c,links:u,calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}function jh(e,t){let r=[];for(let i of t.ops){if(i.kind!=="link-field")continue;let n=e.getLink(i.linkId);if(!n)continue;let a={};for(let o of["freeSlackHours","isCritical"])Object.is(i.before[o],n[o])||(a[o]={before:i.before[o],after:n[o]});Object.keys(a).length!==0&&r.push({id:i.linkId,kind:"updated",fields:a,after:St(n)})}return r}function Vh(e,t){let r=[],i=new Map;for(let n of e){let a=i.get(n.id);if(a===void 0){i.set(n.id,r.length),r.push(n);continue}let o=r[a];if((o.kind==="updated"||o.kind==="created")&&n.kind==="updated"){r[a]={...o,fields:{...o.fields,...n.fields},after:n.after};continue}r[a]=n}for(let n of t){let a=i.get(n.id);if(a===void 0){i.set(n.id,r.length),r.push(n);continue}let o=r[a];if(o.kind==="deleted")continue;let s=o.kind==="created"?Object.fromEntries(Object.entries(n.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):n.fields;r[a]={...o,fields:{...o.fields,...s},after:n.after}}return r}function Kh(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 Yh(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 Gh(e,t,r,i,n){for(let a of t.dirty){if(r.has(a)||i.has(a))continue;let o=t.before.get(a),s=e.getActivity(a);!o||!s||Object.keys(Bn(o,s)).length!==0&&(i.set(a,o),n.add(a))}}function $h(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function Je(e,t,r){let i=[];for(let{op:n,finalLinkId:a,rejected:o}of e){if(o!==null)continue;if(n.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;let u=t.get(a);if(u){let f={};String(u.source)!==String(d.source)&&(f.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(f.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(f.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(f.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(f).length>0&&i.push({id:String(a),kind:"updated",fields:f,after:St(d)});continue}i.push({id:String(a),kind:"created",fields:{source:{before:void 0,after:String(d.source)},target:{before:void 0,after:String(d.target)},type:{before:void 0,after:d.type},lag:{before:void 0,after:Number(d.lag)}},after:St(d)});continue}if(n.kind==="delete"){if(r.getLink(n.linkId))continue;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 s=t.get(n.linkId),c=r.getLink(n.linkId);if(!c)continue;let l={};s&&s.type!==c.type&&(l.type={before:s.type,after:c.type}),s&&Number(s.lag)!==Number(c.lag)&&(l.lag={before:Number(s.lag),after:Number(c.lag)}),i.push({id:String(n.linkId),kind:"updated",fields:l,after:St(c)})}return i}function Xe(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 Qe(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 o=e.get(String(a.id));o===void 0||o===Number(a.lag)||i.push({id:String(a.id),kind:"updated",fields:{lag:{before:o,after:Number(a.lag)}},after:St(a)})}return i}function Pi(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Pc(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:o}=r,s=se(e.column);if(!s)return{ok:!1,reason:v.NO_PIPELINE_FOR_COLUMN};e.column===S.DURATION&&a.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??v.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??v.PARSE_ERROR};let u=Reflect.get(c,s.targetField),f=s.validate(c,u,d.value,n);if(!f.valid)return{ok:!1,reason:f.reason??v.INVALID,alertKey:f.notification?.messageKey};if(e.column===S.CUSTOM_ID&&d.value!==null){let I=i.getActivity(e.activityId),_=I?I.customId:null,j=typeof _=="string"?_:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),j))return{ok:!1,reason:v.CUSTOM_ID_DUPLICATE}}let p=s.transform(c,d.value,n,d.raw),y=ce(e.activityId,p),g=await Q(i,y),C=Xe(i,String(e.activityId)),R=c.constraintDate;le(i,e.activityId,p),re(e.activityId,p.postProcessors??[],i,g.get(String(e.activityId))??null);let A=Qe(C,i,String(e.activityId));if(e.column===S.CUSTOM_ID){let I=g.get(String(e.activityId)),_=I?I.customId:null,j=typeof _=="string"?_:null,W=typeof d.value=="string"?d.value:null;j!==W&&r.customIdTracker.trackCustomIdChange(j,W)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:I=>gi(e.activityId,y,I),now:r.now,options:t}),m=Di(e.column),{scheduledIds:L}=await(m?Ri({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:_i(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:R}],revert:(I,_)=>Ei(I,_,i,n.calendars)}):q({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),F=(p.trackingEvents??[]).map(I=>({name:I.name,properties:I.properties??{}})),T=Ge(e.activityId,p.constraintWarning);return{ok:!0,changes:await K(i,{source:e,beforeSnap:g,touchedIds:y,scheduledIds:L,sirDetection:"before-diff",links:A,trackingEvents:F,...T?{warnings:[T]}:{},hoursPerDay:o.hoursPerDay})}}var zh=new Set(Object.values(U));function Li(e){return typeof e=="string"&&zh.has(e)}function Oi(e,t){return Object.hasOwn(e,t)}function qh(e){if(e.kind===P.LINK_CREATE)return Li(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:v.INVALID_LINK_LAG:v.INVALID_LINK_TYPE;if(e.kind===P.LINK_UPDATE){if(Oi(e,"type")&&!Li(e.type))return v.INVALID_LINK_TYPE;if(Oi(e,"lag")&&!Number.isFinite(e.lag))return v.INVALID_LINK_LAG}return null}function Jh(e){return e.kind===tt.CREATE?Li(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:v.INVALID_LINK_LAG:v.INVALID_LINK_TYPE:e.kind===tt.UPDATE?Oi(e,"type")&&!Li(e.type)?v.INVALID_LINK_TYPE:!Oi(e,"lag")||Number.isFinite(e.lag)?null:v.INVALID_LINK_LAG:e.kind===tt.DELETE?null:v.INVALID_VALUE}function Xh(e){for(let t of e){let r=Jh(t);if(r!==null)return r}return null}function Qh(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind===tt.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 Zh(e,t,r,i){return e.map((n,a)=>{let o=n.kind===tt.CREATE?i?.get(a):void 0,s=te(n,{port:t,newLinkId:o?()=>o:r.next});return{op:n,finalLinkId:s.applied?s.linkId:null,rejected:s.applied?null:s.rejected??v.INVALID}})}function tm(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Lc(e,t,r){let i=qh(e);return i!==null?{ok:!1,reason:i}:Ia([om(e,r.sector.hoursPerDay)],e,t,r,e.kind===P.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function Oc(e,t,r){let i=Xh(e.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:n}=r.sector,a=e.operations.map(s=>im(s,n)),o=em(e.operations);return Ia(a,e,t,r,o)}function em(e){let t=new Map;return e.forEach((r,i)=>{r.kind===tt.CREATE&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function rm(e,t){if(e===void 0)return;let r=new Map,i=new Set,n=()=>{let a=t.linkIdGen.next();for(;t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||i.has(String(a));)a=t.linkIdGen.next();return a};for(let[a,o]of e){let s=t.adapter.getLink(o)!==null||t.isLinkIdReserved(String(o))||i.has(String(o)),c=s?n():o;s||t.linkIdGen.bump(o),i.add(String(c)),r.set(a,c)}return r}function im(e,t){return e.kind===tt.CREATE?{kind:tt.CREATE,source:e.source,target:e.target,type:e.type,lag:Pt(e.lag??0,t)}:e.kind===tt.UPDATE?{kind:tt.UPDATE,linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:Pt(e.lag,t)}:{kind:tt.DELETE,linkId:e.linkId}}async function Ia(e,t,r,i,n){let{adapter:a,scheduler:o,sector:s,linkIdGen:c}=i;o.invalidateAllCaches();let{activityIds:l,links:d}=Qh(e,a),u=await Q(a,l),f=Zh(e,a,c,rm(n,i));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!==P.INLINE_EDIT)return{ok:!1,reason:f[0].rejected};let p=nm(f,d,a),{scheduledIds:y}=await q({adapter:a,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:i.now,options:r}),g=Je(f,d,a);return{ok:!0,linkVerdicts:f.map((C,R)=>C.rejected===null?{operationIndex:R,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:R,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:tm(d),changes:await K(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:g,hoursPerDay:s.hoursPerDay})}}function nm(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=am(i.op,t,r);if(n!==null)return r.hasChildren(n)?"roots":String(n)}return null}function am(e,t,r){return e.kind===tt.CREATE?e.target:e.kind===tt.DELETE?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function om(e,t){return e.kind===P.LINK_CREATE?{kind:tt.CREATE,source:e.source,target:e.target,type:e.type,lag:Pt(e.lag??0,t)}:e.kind===P.LINK_UPDATE?{kind:tt.UPDATE,linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:Pt(e.lag,t)}:{kind:tt.DELETE,linkId:e.linkId}}async function bc(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:v.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let o=e.column===S.CUSTOM_PREDECESSORS,{specs:s}=Zr(e.newValue),c=s.map(y=>({...y,lag:Pt(ii(y.lag),n.hoursPerDay)})),l=new Map;i.forEachActivity(y=>{y.correlativeId!=null&&l.set(String(y.correlativeId),y.id)});let d=y=>l.get(y)??null,u=o?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let y of u){let g=i.getLink(y);g&&f.push(g)}let p=o?ei({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):ri({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Ia(p.operations,e,t,r)}var Ot={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 At(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{N(a.parentId)&&t.push(a)}),t.sort(Fc);let r=[];Nc(r,t);let i=[],n=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==n){let s=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:s}),s!==void 0&&e.noteCorrelativeBefore?.(String(a.id),s),sm(a,n)}n+=1;let o=lr(String(a.id),e);o.sort(Fc),Nc(r,o)}return i}function Nc(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function wc(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}var Fc=(e,t)=>wc(e)-wc(t);function sm(e,t){e.correlativeId=t}function va(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:i,realWorkHours:n}=Uc(r,t);t.setActivityField(r,b.WORK_HOURS,i),t.setActivityField(r,b.REAL_WORK_HOURS,n);let a=t.getActivity(r);if(!a)break;let o=a.parentId;if(!o||N(o))break;r=o}}function xc(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||N(i)||va(i,t)}function Mc(e,t,r){for(let i of e){if(r.hasChildren(i))continue;let n=r.getActivity(i);n&&r.setActivityField(i,b.REAL_WORK_HOURS,Ct(Er(n,b.WORK_HOURS),Er(n,b.PROGRESS)))}for(let i of t)r.setActivityField(i,b.REAL_WORK_HOURS,Uc(i,r).realWorkHours)}function Uc(e,t){let r=0,i=0;for(let n of t.getChildren(e)){let a=t.getActivity(n);if(!a)continue;let o=Er(a,b.WORK_HOURS);r+=o,i+=cm(n,a,o,t)}return{workHours:r,realWorkHours:i}}function Er(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function cm(e,t,r,i){return i.hasChildren(e)?Er(t,b.REAL_WORK_HOURS):Ct(r,Er(t,b.PROGRESS))}function Ca(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let s of i){let c=t.getActivity(s);c&&(n+=lm(c,b.USED_COST))}t.setActivityField(r,b.USED_COST,n);let a=t.getActivity(r);if(!a)break;let o=a.parentId;if(!o||N(o))break;r=o}}function Bc(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||N(i)||Ca(i,t)}function lm(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Sa(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let i=t.getChildren(r),n=0;for(let s of i){let c=t.getActivity(s);c&&(n+=dm(c,b.COST))}t.setActivityField(r,b.COST,n);let a=t.getActivity(r);if(!a)break;let o=a.parentId;if(!o||N(o))break;r=o}}function Wc(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||N(i)||Sa(i,t)}function dm(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var bi=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}),Hc="New Master Plan",jc="New Activity";var um=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Ni=new Set(um);function fm(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"||!Ni.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Vc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=fm(e.activityOverrides??{}),n=e.numTasksInGantt===0?Hc:jc,a=i.name??n,o=i.durationHours??e.sector.hoursPerDay,s=i.calendarId??e.sector.defaultCalendar,c=pm(r,e.fallbackStartDate,i.startDate),l={...bi,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:o,calendarId:s,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:rt.FUTURE,task:l});if(!i.startDate&&r&&Vt(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let y=new Date(d);y.setUTCHours(0,0,0,0),y.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:rt.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:Wt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function pm(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function ym(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 Ze(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Zt(t.type):hm(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(o=>String(o)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=_n,(e.promotionSource??"create")==="create"&&(a.constraintType=H.ASAP,a.constraintDate=null)),{parentId:e.parentId,fields:a,promotionSnapshot:ym(t)}}function hm(e){return Zt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function wi(e,t,r,i){let n=t,a=n==="0",o=ka(e,n);if(i!==void 0){let c=o.find(l=>l.id===i);if(c){let l=It(c),d=o.map(It).filter(f=>f<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=o.find(l=>l.id===r);if(c){let l=It(c),d=o.map(It).filter(f=>f>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return o.length===0?0:Math.max(...o.map(It))+1}var De=Number.MAX_SAFE_INTEGER,Kc=Number.MAX_SAFE_INTEGER-1;function It(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:De}function ka(e,t){return lr(t,e)}function Yc(e,t,r){let i=e,n=ue(e,r);for(;n!=null&&t.has(n);)i=n,n=ue(n,r);return i}function Fi(e,t,r){let i=new Set([e]),n=Qt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=Qt(r.getActivity(n)?.parentId)}return!1}function ue(e,t){let r=t.getActivity(e);if(!r)return null;let i=Qt(r.parentId),n=Rt(i,t),a=n.findIndex(o=>String(o)===String(e));return a<=0?null:n[a-1]??null}function Gc(e,t,r,i){let n=Rt(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(It);if(r<=0)return a[0]-1;if(r>=a.length)return a[a.length-1]+1;let o=a[r-1],s=a[r];return(o+s)/2}var mm=new Set([...[...Ni].filter(e=>e!=="durationHours"),"durationDays"]);function xi(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:v.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!mm.has(a))return{ok:!1,reason:v.INVALID_VALUE};let{durationDays:i,...n}=e;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:v.INVALID_VALUE}:{ok:!0,value:{...n,...i===0&&(n.type===void 0||n.type==="task")?{type:"milestone"}:{},...i===void 0?{}:{durationHours:ge(i,t)}}}}async function Rr(e,t,r={}){let{adapter:i,scheduler:n,sector:a,calendars:o,activityIdGen:s,uidGen:c}=t;r.skipCacheInvalidation||n.invalidateAllCaches();let l=gm(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Im(e.activityId,i,s,t.isActivityIdReserved),y=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Dm(o)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},R=Vc(g,{getActivity:I=>i.getActivity(I),calculateEndDate:I=>i.calculateEndDate(I),getClosestWorkTime:I=>i.getClosestWorkTime(I)}).newTask;R.realWorkHours=Ct(R.workHours,R.progress),Cm(R,e,t,u,d,r);let A=r.insertionCorrelativeId??wi(i,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);R.correlativeId=A;let k=new Set([p]);d&&k.add(d.id);let m=d!==null&&i.getChildren(d.id).length===0,L=m?d?.customId:null,F=r.skipBeforeSnap?new Map:await Q(i,k);i.addActivity(R),Sm(e,p,d,i,m),L&&t.customIdTracker.releaseCustomId(L),r.skipRollupCascades||(xc(p,i),Bc(p,i),Wc(p,i));let T=km(i,p,k,r);return{ok:!0,newId:p,parent:d,newActivity:R,beforeSnap:F,initialTouched:k,correlativeShifts:T}}function gm(e,t){let r=N(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:v.PARENT_NOT_FOUND};if(i!==null&&we(i))return{ok:!1,reason:v.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:v.ANCHOR_SIBLING_CONFLICT};let o=e.afterSiblingId??e.beforeSiblingId,s=Am(e,t,r,o);return s||{ok:!0,parent:i,anchorSiblingId:o,isRoot:r}}function Am(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:v.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==a?{ok:!1,reason:v.ANCHOR_SIBLING_WRONG_PARENT}:null}function Im(e,t,r,i){let n=()=>{let a=r.next();for(;t.activityExists(a)||i(String(a));)a=r.next();return a};return e===void 0||t.activityExists(e)||i(String(e))?n():(r.bump(e),e)}function vm(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Cm(e,t,r,i,n,a){let{adapter:o,customIdTracker:s}=r,c=vm(t);if(c!==void 0){if(c.length===0)return;if(!s.isCustomIdInUse(c)){s.registerCustomId(c);return}}let l=a.customIdReferenceId??i,d=l!==void 0,u=d?o.getActivity(l):n;e.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Sm(e,t,r,i,n){if(!r)return;let a=Ze({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:n,getParent:o=>i.getActivity(o)??null});if(a){for(let[o,s]of Object.entries(a.fields))st(i,a.parentId,o,s);a.promotionSnapshot&&i.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function km(e,t,r,i){if(i.skipCorrelativeRecompute)return[];let n=At(e).filter(a=>a.activityId!==String(t));for(let a of n)r.add(a.activityId);return n}async function Tm(e,t,r,i,n){let{newId:a,newActivity:o,beforeSnap:s,initialTouched:c,correlativeShifts:l}=r,d={name:Ot.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:o.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),K(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:i,correlativeShifts:l,trackingEvents:[d],hoursPerDay:n})}async function $c(e,t,r){let{adapter:i,scheduler:n,sector:a}=r,o=xi(e.overrides,a.hoursPerDay);if(!o.ok)return o;let s=await Rr({...e,overrides:o.value},r);if(!s.ok)return s;let{newId:c}=s,l=s.newActivity.autoScheduling;i.setActivityField(c,"autoScheduling",!1);let d;try{d=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:r.now,options:t})}finally{i.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await Tm(i,e,s,u,a.hoursPerDay)}}function Dm(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 xt(e,t){va(e,t),Ca(e,t),Sa(e,t)}function zc(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 o of a){let s=String(o);r.has(s)||(r.add(s),i.push(s))}}return r}function qc(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 _m(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 Em(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function tr(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=_m(e.promotionSnapshot)??(i?{type:Ue,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Em(t,r,e.computeEndDate)}:{type:Ue});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let o=a.filter(s=>!e.idsRemoved.has(s)&&!e.idsRemoved.has(String(s)));o.length!==a.length&&(n.newActivityIds=o)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Jc(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 Xc=200;async function Qc(e,t,r){let{adapter:i,scheduler:n,customIdTracker:a,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:v.ACTIVITY_IDS_EMPTY};for(let I of e.activityIds)if(!i.getActivity(I))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(I=>{let _=i.getActivity(I);return!(_?.correlativeId===0&&_.type===Dt.PROJECT)}),c=zc(s,i),l=qc(c,i),d=new Set;for(let I of e.activityIds){let _=i.getActivity(I);if(!_)continue;let j=_.parentId;if(N(j))continue;let W=String(j);c.has(W)||d.add(W)}let u=new Set([...c,...d]),f=await Q(i,u),p=new Map;for(let I of l){let _=i.getLink(I);_&&p.set(I,{..._})}let y=new Set,g=0;for(let I of c){g+=1,g%Xc===0&&await it();let _=i.getActivity(I);if(!_)continue;let j=N(_.parentId)?null:i.getActivity(String(_.parentId)),W=j?.hasNewActivities===!0&&j.newActivityIds.some(J=>String(J)===String(I));(_.isNewActivity===!0||W)&&y.add(I);let Z=_.customId;typeof Z=="string"&&Z.length>0&&a.releaseCustomId(Z)}for(let I of l)i.removeLink(I);let C=Ta(i,c),R=0;for(let I of c)R+=1,R%Xc===0&&await it(),i.removeActivity(I);for(let I of d){let _=i.getActivity(I);if(!_)continue;Pm(_,y,i);let j=i.getChildren(I),W=tr({parent:_,remainingChildIds:j.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(I),computeEndDate:(Z,J)=>i.calculateEndDate({startDate:Z,durationHours:J,task:_}),idsRemoved:c});if(!W){ai(I,i);continue}for(let[Z,J]of Object.entries(W.fields))st(i,I,Z,J);if(_.customId==null||_.customId===""){let Z=ue(I,i),J=Z?i.getActivity(Z)?.customId:null,ht=a.generateCustomIdForRestoredChild(typeof J=="string"&&J?J:null);i.setActivityField(I,b.CUSTOM_ID,ht)}}for(let I of d)xt(I,i);let A=At(i),{scheduledIds:k}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:d,now:r.now,options:t}),m={name:Ot.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let L=new Map;for(let[I,_]of p)L.set(I,_);let F=new Map;for(let I of c){let _=f.get(String(I));_&&F.set(String(I),_)}let T=await K(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:k,sirDetection:"after-diff",links:Lm(p),trackingEvents:[m],hoursPerDay:o.hoursPerDay,correlativeShifts:A});return{ok:!0,changes:C.length>0?{...T,viewState:C}:T,__beforeSnap:F,__beforeLinks:L}}function Pm(e,t,r){let i=Jc({parent:e,idsRemoved:t});if(i)for(let[n,a]of Object.entries(i.fields))st(r,i.parentId,n,a)}function Ta(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 Lm(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}async function el(e,t,r){let i=Om(e,r);if(i)return{ok:!1,reason:i};let n=Nm(e,r);if(!n.ok)return n;let a=e.mode===ot.REPLACE?new Set(r.adapter.getAllIds().map(m=>String(m))):new Set,o=e.mode===ot.REPLACE?await Q(r.adapter,a):new Map,s=e.mode===ot.REPLACE?Bm(r):new Map,c=e.mode===ot.REPLACE?Ta(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode===ot.REPLACE){for(let m of s.keys()){let L=te({kind:tt.DELETE,linkId:m},{port:r.adapter});if(!L.applied)return{ok:!1,reason:L.rejected??v.INVALID};l.push({op:{kind:tt.DELETE,linkId:m},finalLinkId:m,rejected:null})}for(let m of a){let L=r.adapter.getActivity(m)?.customId;typeof L=="string"&&L.length>0&&r.customIdTracker.releaseCustomId(L),r.adapter.removeActivity(m)}}let d=await Um(e,n.plan.items,r);if(!d.ok)return d;let u=rl(e)?[]:At(r.adapter),f=new Set(n.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),y=e.mode===ot.REPLACE?new Set(a):new Set;Ai(r.adapter,u,f,o,y);for(let m of n.plan.items)y.add(String(m.activityId));let g=n.plan.links.map(m=>({operation:{kind:tt.CREATE,source:m.source,target:m.target,type:m.type,lag:Pt(m.lag??0,r.sector.hoursPerDay)},linkId:m.linkId})),C=Qr(g,{port:r.adapter,preserved:s});if(!C.applied)return{ok:!1,reason:C.rejected??v.INVALID};for(let{operation:m,linkId:L}of g)l.push({op:m,finalLinkId:L,rejected:null});let R=n.plan.items.map(m=>m.activityId),{scheduledIds:A}=await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?"roots":null,recomputeParentsFrom:R,now:r.now,options:t}),k=await K(r.adapter,{source:e,beforeSnap:o,touchedIds:y,scheduledIds:A,links:Je(l,s,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode===ot.REPLACE?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...k,viewState:c}:k,...e.mode===ot.REPLACE?{__beforeSnap:o,__beforeLinks:Wm(s)}:{}}}function Om(e,t){if(e.mode!==ot.APPEND&&e.mode!==ot.REPLACE)return v.INVALID;let r=new Set,i=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return v.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return v.INVALID;if(a.activityId!==void 0){let o=String(a.activityId);if(o.length===0||o==="0"||i.has(o))return v.INVALID;i.add(o)}}for(let a of e.items)if(!Da(a.parent,!0,e.mode,r,t))return v.PARENT_NOT_FOUND;if(bm(e.items))return v.INVALID;let n=new Set;for(let a of e.links){if(!Object.values(U).includes(a.type))return v.INVALID_LINK_TYPE;if(a.lag!==void 0&&!Number.isFinite(a.lag))return v.INVALID_LINK_LAG;if(!Da(a.source,!1,e.mode,r,t)||!Da(a.target,!1,e.mode,r,t))return v.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let o=String(a.linkId);if(o.length===0||n.has(o))return v.INVALID;n.add(o)}}return null}function Da(e,t,r,i,n){return typeof e=="string"?e==="0"?t:r===ot.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&i.has(e.batchId)}function bm(e){let t=new Map;for(let i of e)typeof i.parent!="string"&&t.set(i.batchId,i.parent.batchId);let r=new Set;for(let i of e){let n=new Set,a=i.batchId;for(;a!==void 0&&!r.has(a);){if(n.has(a))return!0;n.add(a),a=t.get(a)}for(let o of n)r.add(o)}return!1}function Nm(e,t){let r=new Map;for(let d of e.items){let u=xi(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let i=new Map,n=new Set;for(let d of e.items){let u=wm(d.activityId,e.mode,n,t);n.add(String(u)),i.set(d.batchId,u)}let a=new Set,o=e.links.map(d=>{let u=Fm(d.linkId,e.mode,a,t);return a.add(String(u)),u}),s=xm(e,i,t),c=[];for(let d of e.items){let u=i.get(d.batchId),f=s.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:v.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,y=typeof d.parent=="string"?d.parent:i.get(d.parent.batchId);if(y===void 0)return{ok:!1,reason:v.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:y,parentBatchId:p,insertionCorrelativeId:f,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=tl(u.source,i),p=tl(u.target,i),y=o[d];if(f===null||p===null||y===void 0)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:c,links:l}}}function wm(e,t,r,i){if(e!==void 0&&(t===ot.REPLACE||i.adapter.getActivity(e)===null&&!i.isActivityIdReserved(String(e)))&&!r.has(String(e)))return i.activityIdGen.bump(e),e;let a=i.activityIdGen.next();for(;r.has(String(a))||t===ot.APPEND&&(i.adapter.getActivity(a)!==null||i.isActivityIdReserved(String(a)));)a=i.activityIdGen.next();return a}function Fm(e,t,r,i){if(e!==void 0&&(t===ot.REPLACE||i.adapter.getLink(e)===null&&!i.isLinkIdReserved(String(e)))&&!r.has(String(e)))return i.linkIdGen.bump(e),e;let a=i.linkIdGen.next();for(;r.has(String(a))||t===ot.APPEND&&(i.adapter.getLink(a)!==null||i.isLinkIdReserved(String(a)));)a=i.linkIdGen.next();return a}function xm(e,t,r){if(rl(e)){let s=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,s+l]))}let i=new Set(Array.from(t.values(),s=>String(s))),n=new Map;for(let s of e.items){let c=t.get(s.batchId);if(c===void 0)continue;let l=typeof s.parent=="string"?s.parent:t.get(s.parent.batchId);if(l===void 0)continue;let d=String(l),u=n.get(d);u||(u={existing:e.mode===ot.REPLACE||typeof s.parent!="string"&&t.has(s.parent.batchId)?[]:ka(r.adapter,d).sort((g,C)=>It(g)-It(C)||String(g.id).localeCompare(String(C.id))).map(g=>String(g.id)),newIdsByTarget:new Map},n.set(d,u));let f=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),p=u.newIdsByTarget.get(f)??[];p.push(String(c)),u.newIdsByTarget.set(f,p)}let a=new Map,o=new Map(Array.from(t,([s,c])=>[String(c),s]));for(let s of n.values()){let c=[];for(let d=0;d<=s.existing.length;d+=1){for(let f of s.newIdsByTarget.get(d)??[])c.push(f);let u=s.existing[d];u!==void 0&&c.push(u)}let l=0;for(;l<c.length;){if(!i.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&i.has(c[l]);)l+=1;let u=l-d,f=d>0?Zc(c[d-1],r):null,p=l<c.length?Zc(c[l],r):null;for(let y=0;y<u;y+=1){let g=c[d+y],C=o.get(g);C!==void 0&&a.set(C,Mm(f,p,y+1,u))}}}return a}function rl(e){return e.mode===ot.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Zc(e,t){let r=t.adapter.getActivity(e);return r?It(r):0}function Mm(e,t,r,i){return e!==null&&t!==null&&t>e?e+(t-e)*r/(i+1):e!==null?e+r:t!==null?t-(i-r+1):r-1}async function Um(e,t,r){let i=new Map,n=[];for(let o of t){if(o.parentBatchId===null){n.push(o);continue}let s=i.get(o.parentBatchId)??[];s.push(o),i.set(o.parentBatchId,s)}for(let o=0;o<n.length;o+=1){let s=n[o],c=await Rr({kind:P.ACTIVITY_CREATE,parentId:s.parentId,activityId:s.activityId,overrides:s.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:s.insertionCorrelativeId});if(!c.ok)return c;for(let l of i.get(s.input.batchId)??[])n.push(l)}if(n.length!==t.length)return{ok:!1,reason:v.INVALID};let a=new Set;for(let o=n.length-1;o>=0;o-=1){let s=n[o].parentId;s==="0"||a.has(String(s))||(a.add(String(s)),xt(s,r.adapter))}return{ok:!0}}function tl(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Bm(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Wm(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function il(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let a=n.pendingRequestIds??[],o=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",o);let s=r.getActivity(i);if(!s)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let c={id:i,kind:"updated",fields:{pendingRequestIds:{before:a,after:o}},after:et(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function nl(e){let t=new Map;for(let r of e){let i=r.proplannerId;typeof i=="number"&&Number.isSafeInteger(i)&&i>0&&t.set(i,String(r.id))}return t}function al(e,t,r){let i=new Set(t.map(({id:n})=>String(n)));for(let n of e)if((n.proplannerId==null||n.proplannerId===0)&&!i.has(String(n.id)))throw new Error(`persistence-acknowledge: missing ${r} proplannerId for "${String(n.id)}"`)}function Hm(e,t,r,i,n,a){let o=String(e.id);if(o.length===0||n.has(o))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${o}"`);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 s=r(o);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${o}"`);if(s.current!==null&&s.current!==0&&s.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${o}" already has proplannerId ${String(s.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==o)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(o),a.add(e.proplannerId)}function ol(e,t,r,i){let n=new Set,a=new Set;for(let o of e)Hm(o,t,r,i,n,a)}async function sl(e,t){let r=e.filter(s=>{let c=t.adapter.getActivity(String(s.activityId));return c!==null&&c.progress!==s.progress}),i=new Set(r.map(s=>String(s.activityId))),n=Ar(t.adapter,i),a=new Set(i);for(let s of n)a.add(String(s));let o=await Q(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let s of r){let c=String(s.activityId);t.adapter.setActivityField(c,"progress",s.progress),t.adapter.setActivityField(c,"autoScheduling",he(s.progress))}ds(n,t.adapter),Mc(i,n,t.adapter)}),[...await mi(t.adapter,o,a)]}async function cl(e,t){let r=e.activities??[],i=e.links??[],n=t.adapter.getAllActivities(),a=t.adapter.getAllLinks(),o=e.checkpoint?.activities??n,s=e.checkpoint?.links??a,c=new Map(o.map(y=>[String(y.id),y])),l=new Map(s.map(y=>[String(y.id),y])),d=nl(o),u=nl(s);ol(r,"activity",y=>{let g=c.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},d),ol(i,"link",y=>{let g=l.get(y);return{exists:g!==void 0,current:g?.proplannerId??null}},u),al(o,r,"activity"),al(s,i,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let y of r){let g=t.adapter.getActivity(y.id);if(!g||g.proplannerId===y.proplannerId)continue;let C=g.proplannerId;t.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),f.push({id:y.id,kind:"updated",fields:{proplannerId:{before:C,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}for(let y of i){let g=t.adapter.getLink(y.id);if(!g||g.proplannerId===y.proplannerId)continue;let C=g.proplannerId;t.adapter.setLinkProplannerId(y.id,y.proplannerId),p.push({id:y.id,kind:"updated",fields:{proplannerId:{before:C,after:y.proplannerId}},after:{...g,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function ll(e,t,r){if(jm(e))return{ok:!1,reason:v.INVALID_VALUE};let i=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&i.some(s=>!r.isActivityIdReserved(s)))return{ok:!1,reason:v.INVALID};let a=i.map(s=>r.adapter.getActivity(s));if(a.some(s=>!s))return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let o=[];for(let[s,c]of i.entries()){let l=a[s];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},r.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},r.adapter.setActivityField(c,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(d).length!==0&&o.push({id:c,kind:"updated",fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await sl([{activityId:i[0],progress:e.persistedProgress}],r)).length>0?(await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.persistedProgress===0?i[0]:null,recomputeParentsFrom:[],now:r.now,options:t}),{ok:!0,changes:await K(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:o,links:[],calendars:[],trackingEvents:[]}}}function jm(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function Mi(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),o=String(n.target);!r.has(a)&&!r.has(o)||(dl(o,a,t)||dl(a,o,t))&&i.push(String(n.id))}return i}function dl(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 o=a.parentId;if(o===null||N(o))return!1;let s=o;if(s===t)return!0;i=s}return!1}function Ui(e,t){let r=e.getAllLinks();return!hr({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function Bi(e,t){let r=new Set;if(e.length===0)return r;let i=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!Ui(t,i))return r;let n=new Map;for(let a of e){let o=new Map(n);if(o.set(a.activityId,a.newParentId),Ui(t,o)){r.add(a.activityId);continue}n.set(a.activityId,a.newParentId)}return r}async function ul(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;n.invalidateAllCaches();let o=i.getActivity(e.activityId);if(!o)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let s=N(e.parentId);if(!s&&!i.getActivity(e.parentId))return{ok:!1,reason:v.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:v.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:v.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let L=i.getActivity(c);if(!L)return{ok:!1,reason:v.ANCHOR_SIBLING_NOT_FOUND};if((L.parentId===null?"0":String(L.parentId))!==e.parentId)return{ok:!1,reason:v.ANCHOR_SIBLING_WRONG_PARENT}}let l=o.parentId,d=Qt(l),u=String(e.parentId),f=d!==u;if(f){let L=new Map([[e.activityId,s?null:e.parentId]]);if(Ui(i,L))return{ok:!1,reason:v.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let y=await Q(i,p);f&&i.setActivityField(e.activityId,b.PARENT,u);let g=wi(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,b.CORRELATIVE_ID,g),f){if(!s){let L=i.getActivity(e.parentId);if(L){let F=L.customId,T=Zt(L.type)&&i.getChildren(e.parentId).filter(_=>_!==e.activityId).length===0,I=Ze({parentId:e.parentId,newChildId:e.activityId,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:T,promotionSource:"reparent"});if(I){for(let[_,j]of Object.entries(I.fields))st(i,I.parentId,_,j);I.promotionSnapshot&&i.setPromotionSnapshot(I.parentId,I.promotionSnapshot),I.fields.customId===null&&Pi(F,r.customIdTracker)}}}if(d!=="0"){let L=i.getActivity(d);if(L){let F=i.getChildren(d),T=tr({parent:L,remainingChildIds:F.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(I,_)=>i.calculateEndDate({startDate:I,durationHours:_,task:L}),idsRemoved:new Set([e.activityId])});if(T){for(let[Z,J]of Object.entries(T.fields))st(i,d,Z,J);let I=ue(d,i),_=I?i.getActivity(I)?.customId:null,j=typeof _=="string"&&_?_:null,W=r.customIdTracker.generateCustomIdForRestoredChild(j);i.setActivityField(d,b.CUSTOM_ID,W)}}}}f&&(d!=="0"&&xt(d,i),s||xt(e.parentId,i));let C=At(i);for(let L of C){if(p.add(L.activityId),y.has(L.activityId))continue;let F=i.getActivity(L.activityId);if(!F)continue;let T=et(F);L.before!==void 0&&(T.correlativeId=L.before),y.set(L.activityId,T)}let R=f&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:A}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...R],now:r.now,options:t,recomputeParentProgress:f}),k=f?Mi([e.activityId],i):[],m={name:Ot.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:k.map(String)}};return e.eventSource!==void 0&&(m.properties.event_source=e.eventSource),{ok:!0,changes:await K(i,{source:e,beforeSnap:y,touchedIds:p,scheduledIds:A,sirDetection:"before-diff",trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function Wi(e,t){let r=new Set(e),i=[],n=[],a=new Set,o=new Set(r),s=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),y=f?It(f):De,g=p?It(p):De;return y-g});for(let d of s){if(!t.getActivity(d)){i.push({activityId:d,reason:v.ACTIVITY_NOT_FOUND}),o.delete(d);continue}if(Fi(d,a,t))continue;let f=Oo(d,o,t);if(f==null){i.push({activityId:d,reason:v.INDENT_NO_ELIGIBLE_SIBLING}),o.delete(d);continue}let p=t.getActivity(d)?.parentId,y=N(p)?"0":String(p);n.push({activityId:d,newParentId:f,oldParentId:y}),a.add(d)}let c=Bi(n,t);for(let d of c)i.push({activityId:d,reason:v.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:i}}async function fl(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:v.ACTIVITY_IDS_EMPTY};let o=new Set,s=[],c=Wi(e.activityIds,i),l=[...c.failed];for(let A of c.moves)o.add(String(A.activityId)),o.add(String(A.newParentId)),A.oldParentId!=="0"&&o.add(String(A.oldParentId));let d=c.allowedMoves,u=await Q(i,o);for(let{activityId:A,newParentId:k}of d)i.setActivityField(A,b.PARENT,k),i.setActivityField(A,b.CORRELATIVE_ID,Kc),s.push(A);let f=new Set;for(let{activityId:A,newParentId:k}of d){if(f.has(k))continue;f.add(k);let m=i.getActivity(k);if(!m)continue;let L=m.customId,F=Zt(m.type)&&i.getChildren(k).filter(_=>!s.includes(_)).length===0,T=m.hasNewActivities&&m.newActivityIds.some(_=>String(_)===String(A)),I=Ze({parentId:k,newChildId:A,getParent:_=>i.getActivity(_)??null,isCurrentlyLeaf:F,promotionSource:"reparent"});if(I){for(let[_,j]of Object.entries(I.fields))st(i,I.parentId,_,j);I.promotionSnapshot&&i.setPromotionSnapshot(I.parentId,I.promotionSnapshot),T||(i.setActivityField(k,b.HAS_NEW_ACTIVITIES,!1),i.setActivityField(k,b.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(k,b.CONSTRAINT_TYPE,"asap"),i.setActivityField(k,b.CONSTRAINT_DATE,null),i.setActivityField(k,b.CUSTOM_ID,null),Pi(L,r.customIdTracker)}let p=new Set;for(let A of d)A.oldParentId!=="0"&&p.add(A.oldParentId),p.add(A.newParentId);for(let A of p)xt(A,i);let y=At(i);for(let A of y){if(o.add(A.activityId),u.has(A.activityId))continue;let k=i.getActivity(A.activityId);if(!k)continue;let m=et(k);A.before!==void 0&&(m.correlativeId=A.before),u.set(A.activityId,m)}let{scheduledIds:g}=await q({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:r.now,options:t}),C=Mi(s,i),R={name:Ot.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(A=>({activity_id:A.activityId,reason:A.reason})),invalid_link_ids:C}};return e.eventSource!==void 0&&(R.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(A=>{let k=l.find(m=>String(m.activityId)===String(A));return k?{activityId:String(A),ok:!1,reason:k.reason}:{activityId:String(A),ok:!0}}),changes:await K(i,{source:e,beforeSnap:u,touchedIds:o,scheduledIds:g,trackingEvents:[R],hoursPerDay:a.hoursPerDay})}}async function pl(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:v.ACTIVITY_IDS_EMPTY};let o=new Set(e.activityIds),s=new Map,c=new Map;for(let T of e.activityIds){let I=T;i.getActivity(I)&&(s.set(I,Sn(I,i)),c.set(I,Yc(I,o,i)))}let l=new Set,d=[],u=[],f=new Set,p=[],y=new Set,g=[...e.activityIds].sort((T,I)=>{let _=i.getActivity(T),j=i.getActivity(I),W=_?It(_):De,Z=j?It(j):De;return W-Z});for(let T of g){let I=T,_=i.getActivity(I);if(!_){d.push({activityId:I,reason:v.ACTIVITY_NOT_FOUND});continue}if(Fi(I,y,i))continue;let j=_.parentId;if(N(j)){d.push({activityId:I,reason:v.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let W=String(j),Z=i.getActivity(W);if(!Z){d.push({activityId:I,reason:v.ACTIVITY_NOT_FOUND});continue}let J=Z.parentId;if(N(J)){d.push({activityId:I,reason:v.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let ht=String(J),kt=Sn(W,i)+1,ct=c.get(I);if(ct!=null&&o.has(ct)){let Pe=s.get(ct)??-1,Le=s.get(I)??-1;Pe>=0&&Le>=0&&(kt+=Le-Pe)}p.push({activityId:I,grandparentKey:ht,oldParentKey:W,targetIndexInGrandparent:kt}),y.add(I),l.add(String(I)),l.add(String(W)),ht!=="0"&&l.add(String(ht)),f.add(W)}let C=Bi(p.map(T=>({activityId:T.activityId,newParentId:T.grandparentKey})),i);for(let T of C)d.push({activityId:T,reason:v.HIERARCHY_CYCLE});let R=p.filter(T=>!C.has(T.activityId)),A=await Q(i,l);for(let T of R){i.setActivityField(T.activityId,b.PARENT,T.grandparentKey);let I=Gc(i,T.grandparentKey,T.targetIndexInGrandparent,T.activityId);i.setActivityField(T.activityId,b.CORRELATIVE_ID,I),u.push(T.activityId)}for(let T of f){let I=i.getActivity(T);if(!I)continue;let _=i.getChildren(T),j=tr({parent:I,remainingChildIds:_.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(T),computeEndDate:(kt,ct)=>i.calculateEndDate({startDate:kt,durationHours:ct,task:I}),idsRemoved:new Set(R.filter(kt=>kt.oldParentKey===T).map(kt=>kt.activityId))});if(!j){ai(T,i);continue}for(let[kt,ct]of Object.entries(j.fields))st(i,T,kt,ct);let W=ue(T,i),Z=W?i.getActivity(W)?.customId:null,J=typeof Z=="string"&&Z?Z:null,ht=r.customIdTracker.generateCustomIdForRestoredChild(J);i.setActivityField(T,b.CUSTOM_ID,ht)}let k=new Set;for(let T of f)k.add(String(T));for(let T of R)T.grandparentKey!=="0"&&k.add(String(T.grandparentKey));for(let T of k)xt(T,i);let m=At(i);for(let T of m){if(l.add(T.activityId),A.has(T.activityId))continue;let I=i.getActivity(T.activityId);if(!I)continue;let _=et(I);T.before!==void 0&&(_.correlativeId=T.before),A.set(T.activityId,_)}let{scheduledIds:L}=await q({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}),F={name:Ot.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(T=>({activity_id:String(T.activityId),reason:T.reason}))}};return e.eventSource!==void 0&&(F.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(T=>{let I=d.find(_=>String(_.activityId)===String(T));return I?{activityId:String(T),ok:!1,reason:I.reason}:{activityId:String(T),ok:!0}}),changes:await K(i,{source:e,beforeSnap:A,touchedIds:l,scheduledIds:L,trackingEvents:[F],hoursPerDay:a.hoursPerDay})}}async function yl(e,t,r){let{adapter:i,ctx:n,scheduler:a,sector:o}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:v.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:v.ACTIVITY_NOT_FOUND};let c=se(S.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.canEdit(s,n.hierarchy);if(!l.allowed&&!(e.origin==="action-button"&&(l.reason==="has_lookahead_tasks"||l.reason==="summary")))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=ce(e.activityId,d),f=await Q(i,u);le(i,e.activityId,d),fs(e.activityId,e.newValue,i),re(e.activityId,d.postProcessors??[],i);let{scheduledIds:p}=await q({adapter:i,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:g=>gi(e.activityId,u,g),now:r.now,options:t}),y=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await K(i,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:y,hoursPerDay:o.hoursPerDay})}}function Vm(e){return e===S.START_DATE||e===S.END_DATE}async function hl(e,t,r){if(e.edits.some(y=>!Vm(y.column)))return{ok:!1,reason:v.INVALID_VALUE};let{adapter:i,scheduler:n,sector:a}=r,o=[],s=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let y of e.edits){let g=Km(y,r);if(o.push(g.verdict),!g.verdict.ok||!g.changes)continue;let C=ce(y.activityId,g.changes);Ym(s,C,r);for(let m of C)c.add(m);let R=Xe(i,y.activityId),A=hi(i,String(y.activityId));le(i,y.activityId,g.changes),re(y.activityId,g.changes.postProcessors??[],i,A),d.push(...Qe(R,i,y.activityId)),f||=!!g.changes.needsAutoSchedule;for(let m of g.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=Ge(y.activityId,g.changes.constraintWarning);k&&u.push(k)}let{scheduledIds:p}=await q({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:o,changes:await K(i,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Km(e,t){let{ctx:r}=t,i=e.activityId,n=se(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 o=n.canEdit(a,r.hierarchy);if(!o.allowed)return{verdict:{activityId:i,ok:!1,reason:o.reason??v.CANNOT_EDIT,...o.alertKey?{alertKey:o.alertKey}:{}},changes:null};let s=n.parseInput(e.newValue,a,r);if(!s.ok)return{verdict:{activityId:i,ok:!1,reason:s.reason??v.PARSE_ERROR},changes:null};let c=Reflect.get(a,n.targetField),l=n.validate(a,c,s.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??v.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(a,s.value,r,s.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function Ym(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,et(a))}}var _a=S.CUSTOM_ID;async function ml(e,t,r){let{adapter:i,scheduler:n,sector:a}=r;e.edits.some(k=>k.column===S.DURATION)&&n.invalidateExpandedLinksCache();let s=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],y=[],g=!1;for(let k of e.edits){let m=Gm(k,r,e.eventSource);if(s.push(m.verdict),!m.verdict.ok||!m.changes)continue;let L=Ge(k.activityId,m.changes.constraintWarning);L&&y.push(L);let F=ce(k.activityId,m.changes);Jm(c,F,r);for(let W of F)u.add(W);qm(l,k,c),_i(k.column)&&d.add(String(k.activityId));let T=Xe(i,k.activityId),I=hi(i,String(k.activityId)),_=$m(k,r),j=m.changes;le(i,k.activityId,j),re(k.activityId,m.changes.postProcessors??[],i,I),zm(k,_,r),p.push(...Qe(T,i,k.activityId)),g||=!!m.changes.needsAutoSchedule;for(let W of m.changes.trackingEvents??[])f.push({name:W.name,properties:W.properties??{}})}let C={action:e,autoscheduleFrom:g?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},R=l.size>0,{scheduledIds:A}=await(R?Ri({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([k])=>!d.has(k)).map(([k,m])=>({activityId:k,priorConstraintDate:m})),revert:(k,m)=>Ei(k,m,i,r.ctx.calendars)}):q({adapter:i,scheduler:n,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},C));return{ok:!0,verdicts:s,changes:await K(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:A,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:y,hoursPerDay:a.hoursPerDay})}}function Gm(e,t,r){let{ctx:i}=t,n=e.activityId,a=se(e.column);if(!a)return{verdict:{activityId:n,ok:!1,reason:v.NO_PIPELINE_FOR_COLUMN},changes:null};let o=i.activityReader.getActivity(e.activityId);if(!o)return{verdict:{activityId:n,ok:!1,reason:v.ACTIVITY_NOT_FOUND},changes:null};let s=a.canEdit(o,i.hierarchy,{eventSource:r,newValue:e.newValue});if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??v.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let c=a.parseInput(e.newValue,o,i);if(!c.ok)return{verdict:{activityId:n,ok:!1,reason:c.reason??v.PARSE_ERROR},changes:null};let l=Reflect.get(o,a.targetField),d=a.validate(o,l,c.value,i);if(!d.valid)return{verdict:{activityId:n,ok:!1,reason:d.reason??v.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===_a&&c.value!==null){let f=t.adapter.getActivity(e.activityId),p=f?f.customId:null,y=typeof p=="string"?p:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),y))return{verdict:{activityId:n,ok:!1,reason:v.CUSTOM_ID_DUPLICATE},changes:null}}let u=a.transform(o,c.value,i,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function $m(e,t){if(e.column!==_a)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function zm(e,t,r){if(e.column!==_a)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 qm(e,t,r){if(!Di(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 Jm(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,et(a))}}function gl(e){return typeof e=="string"&&e.length>0?zt(e):e instanceof Date?e:null}function Ea(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 Hi(e,t){let r=Ea(e.duration),i=Ea(e.cost),n=Ea(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:gl(e.start_date),endDate:gl(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 Al(e,t,r){let i=new Map;e.forEachActivity((o,s)=>{let c=o.proplannerId;typeof c=="number"&&i.set(c,s)});let n=new Map;for(let o of t){let s=o.activityId;if(typeof s!="number")continue;let c=i.get(s);if(c===void 0)continue;let l=n.get(c);l?l.push(o):n.set(c,[o])}let a=[];for(let[o,s]of n)e.setActivityField(o,"baselinePoints",s.map(c=>Hi(c,r)).filter(c=>c!==null)),a.push(o);return e.forEachActivity((o,s)=>{if(n.has(s))return;let c=o.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(s,"baselinePoints",[]),a.push(s))}),a}function Xm(e){let t=gt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Il(e){let t=[];return e.forEachActivity((r,i)=>{let n=Xm(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 ji(e,t,r,i,n=null){let a=new Set;for(let o of Al(e,t,i))a.add(o);if(r)for(let o of ze(e,r,n))a.add(o);for(let o of Il(e))a.add(o);for(let o of qe(e))a.add(o);return[...a]}function vl(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 s of i){let c=Qm(String(s),t,r);n.set(String(s),c),a+=c}let o=a?100/a:0;for(let s of i){let c=r.getActivity(s);if(!c)continue;let l=c.baselinePoints;if(gt(c)){let u=n.get(String(s))??0;r.setActivityField(s,S.PONDERATOR,o*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(s,S.PONDERATOR,0)}}function Qm(e,t,r){let i=r.getActivity(e);if(!i)return 0;let n=gt(i);if(!n)return 0;if(t===dt.COST)return Vi(n.cost);if(t===dt.WORK_HOURS)return Vi(n.workHours);let{type:a}=i;return a===Dt.PROJECT?Cl(e,r):a===Dt.MILESTONE?0:Vi(n.durationDays)}function Cl(e,t){let r=0;for(let i of t.getChildren(e)){let n=t.getActivity(i);if(!n)continue;let a=gt(n);if(!a)continue;let{type:o}=n;o===Dt.PROJECT?r+=Cl(String(i),t):o!==Dt.MILESTONE&&(r+=Vi(a.durationDays))}return r}function Vi(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Sl(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,S.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&vl(String(i),e,t)})}function Ki(e,t){Sl(t,e.adapter),gr(e.adapter),e.now&&(ze(e.adapter,e.now,e.defaultBaseCalendarId??null),Ce(e.adapter,e.now)),qe(e.adapter),e.now&&qt(e.adapter,e.sector.statusCriteria)}function kl(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 Tl(e,t){let r=await Q(t.adapter,new Set(t.adapter.getAllIds())),i=kl(t),n=ji(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return kl(t)!==i&&Ki(t,t.sector.activityCreter??dt.DURATION),{ok:!0,changes:await K(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function Zm(e){return Object.values(dt).includes(e)}async function Dl(e,t){if(!Zm(e.criterion))return{ok:!1,reason:v.INVALID_VALUE};let r=new Set(t.adapter.getAllIds()),i=await Q(t.adapter,r);return Ki(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await K(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function _l(e,t){let r=Ii(e.criteria),i=new Set(t.adapter.getAllIds()),n=await Q(t.adapter,i),a=qt(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await K(t.adapter,{source:e,beforeSnap:n,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Rl(e,t,r){let i=new Map,n=new Set;for(let o of r.adapter.getAllActivities()){if(!tg(o,r))continue;let s=r.ctx.calendars.getCalendar(o.calendarId);if(!s)continue;let c=s.getClosestWorkTime({date:o.startDate,direction:rt.FUTURE,unit:pt.HOUR}),l=s.calculateEndDate(c,o.durationHours);if(El(c,o.startDate)&&El(l,o.endDate))continue;let d=String(o.id);i.set(d,et(o)),n.add(d),r.adapter.setActivityFields(d,{startDate:c,endDate:l})}let{scheduledIds:a}=await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await K(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:a,hoursPerDay:r.sector.hoursPerDay})}}function tg(e,t){return e.progress===0&&!wt(e.type,t.adapter.hasChildren(e.id))}function El(e,t){return e.getTime()===t.getTime()}var Pl=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function eg(e){let t={};for(let r of Pl)Object.assign(t,{[r]:O(e[r])});return t}function rg(e,t){let r=[],i=n=>{t.has(String(n))&&r.push(n);for(let a of e.getChildren(n))i(a)};for(let n of e.getRootIds())i(n);return r}function Ll(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:v.NO_ACTIVITY_SELECTION};let i=rg(t.adapter,r);t.clipboard.value={activities:i.map(a=>{let o=t.adapter.getActivity(a);if(o===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:o.parentId??"0",overrides:eg(o)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>O(a))};let n=Mr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function Ol(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function ig(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id}:{ok:!0,parentId:"0",afterSiblingId:e}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:v.ANCHOR_SIBLING_NOT_FOUND}}var bl=()=>({ok:!1,reason:v.ACTIVITY_PASTE_INVARIANT_FAILED});async function Nl(e,t,r){let i=r.activityClipboard.value;if(i===null)return{ok:!1,reason:v.CLIPBOARD_EMPTY};let n=ig(e.destination.afterSiblingId,r.adapter);if(!n.ok)return n;let a=await Q(r.adapter,new Set),o=new Set,s=new Map,c=[],l;for(let g of i.activities){let C=s.get(g.originalParentId),R=C===void 0?l??n.afterSiblingId:void 0,A=await Rr({kind:"activity-create",parentId:C??n.parentId,...R===void 0?{}:{afterSiblingId:R},overrides:O(g.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!A.ok)return A;s.set(g.originalId,A.newId),c.push(A.newId),C===void 0&&(l=A.newId)}let d=At(r.adapter),u=new Set(c.map(String));Ai(r.adapter,d,u,a,o);for(let g of c)o.add(String(g));let f=[];for(let g of i.links){let C=s.get(g.source),R=s.get(g.target);if(C===void 0||R===void 0)return bl();let A={kind:"create",source:C,target:R,type:g.type,lag:g.lag},k=te(A,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return bl();f.push({op:A,finalLinkId:k.linkId,rejected:null})}let{scheduledIds:p}=await q({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:r.now,options:t}),y=Je(f,new Map,r.adapter);return{ok:!0,changes:await K(r.adapter,{source:e,beforeSnap:a,touchedIds:o,scheduledIds:p,links:y,hoursPerDay:r.sector.hoursPerDay})}}async function wl(e,t,r){return e.kind==="activity-copy"?Ll(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="calendar-reconcile"?Rl(e,t,r):e.kind==="activity-clipboard-clear"?Ol(e,r.activityClipboard):e.kind==="activity-paste-copied"?Nl(e,t,r):e.kind==="activity-batch"?el(e,t,r):e.kind==="persistence-acknowledge"?cl(e,r):e.kind==="baseline-apply"?Tl(e,r):e.kind==="ponderator-criterion-set"?Dl(e,r):e.kind==="status-criteria-set"?_l(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Lc(e,t,r):e.kind==="links-batch"?Oc(e,t,r):e.kind==="activity-create"?$c(e,t,r):e.kind==="activity-delete"?Qc(e,t,r):e.kind==="activity-move"?ul(e,t,r):e.kind==="activity-indent"?fl(e,t,r):e.kind==="activity-outdent"?pl(e,t,r):e.kind==="activity-set-progress"?yl(e,t,r):e.kind==="dates-batch"?hl(e,t,r):e.kind==="bulk-edit"?ml(e,t,r):e.kind==="selection-toggle"?Ao(e,Ra(r)):e.kind==="selection-replace"?Mr(e,Ra(r)):e.kind==="visibility-set"?Io(e,Ra(r)):e.kind==="filter-set"?Ro(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?No(e,{adapter:r.adapter}):e.kind==="sir-sync"?il(e,r):e.kind==="activity-lookahead-sync"?ll(e,t,r):e.kind==="inline-edit"&&(e.column===S.CUSTOM_PREDECESSORS||e.column===S.CUSTOM_SUCESSORS)?bc(e,t,r):e.kind!=="inline-edit"?wo(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Pc(e,t,r)}function Ra(e){return{adapter:e.adapter}}var ng=new Set(["startDate","endDate","constraintDate"]);function Fl(e,t){return ng.has(e)&&typeof t=="string"?new Date(t):t}function xl(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(i){let n=e.getCalendar(String(i));return n?ag(n,r):null}}}function ag(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 og(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function _e(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Ee(e){return _e(e)&&!isNaN(e.getTime())}var sg={}.constructor.toString();function cg(e){var t=e.constructor.toString();return t!==sg}function lg(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Mt(e){var t,r;if(e&&typeof e=="object")switch(!0){case _e(e):r=new Date(e);break;case og(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Mt(e[t]);break;default:if(cg(e))r=Object.create(e);else{if(lg(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Mt(e[t]));break}return r||e}function er(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function Ml(e){return typeof e<"u"}var Yi;function Pa(){return Yi||(Yi=new Date().valueOf()),Yi++,Yi}function Et(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var ug=(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)},fg=(e,t,r)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",n=e.match(/%[a-zA-Z]/g);for(let s=0;s<n.length;s++)switch(n[s]){case"%j":case"%d":i+=`set[2]=temp[${s}]||1;`;break;case"%n":case"%m":i+=`set[1]=(temp[${s}]||1)-1;`;break;case"%y":i+=`set[0]=temp[${s}]*1+(temp[${s}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":i+=`set[3]=temp[${s}]||0;`;break;case"%i":i+=`set[4]=temp[${s}]||0;`;break;case"%Y":i+=`set[0]=temp[${s}]||0;`;break;case"%a":case"%A":i+=`set[3]=set[3]%12+((temp[${s}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":i+=`set[5]=temp[${s}]||0;`;break;case"%M":i+=`set[1]=locale.date.month_short_hash[temp[${s}]]||0;`;break;case"%F":i+=`set[1]=locale.date.month_full_hash[temp[${s}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let o=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${a});`);return s=>o(s,r.locale)},Ul={date_to_str:ug,str_to_date:fg},pg=(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}}),yg=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),o=e.match(/%[a-zA-Z]/g);for(let s=0;s<o.length;s++)switch(o[s]){case"%j":case"%d":n[2]=a[s]||1;break;case"%n":case"%m":n[1]=(a[s]||1)-1;break;case"%y":n[0]=a[s]*1+(a[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=a[s]||0;break;case"%i":n[4]=a[s]||0;break;case"%Y":n[0]=a[s]||0;break;case"%a":case"%A":n[3]=n[3]%12+((a[s]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=a[s]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[a[s]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[a[s]]||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])},Bl={date_to_str:pg,str_to_date:yg};function Wl(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(s){var c=new Date(s);return isNaN(c.getTime())?null:c}var i=null;function n(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var s=!1;return e.config.csp==="auto"?(i===null&&n(),s=i):s=e.config.csp,s}var o={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(s){return s.toISOString()},formatISODateOnly:function(s){return s.getUTCFullYear()+"-"+e.date.to_fixed(s.getUTCMonth()+1)+"-"+e.date.to_fixed(s.getUTCDate())},init:function(){for(var s=e.locale,l=s.date.month_short,d=s.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=s.date.month_full,d=s.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(s){return s.setUTCHours(0,0,0,0),s},time_part:function(s){return s.valueOf()/1e3%86400},week_start:function(s){var c=s.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(s,-1*c,"day"))},month_start:function(s){return s.setUTCDate(1),this.date_part(s)},quarter_start:function(s){this.month_start(s);var c=s.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,s.setUTCMonth(l),s},year_start:function(s){return s.setUTCMonth(0),this.month_start(s)},day_start:function(s){return this.date_part(s)},hour_start:function(s){return s.getUTCMinutes()&&s.setUTCMinutes(0),this.minute_start(s),s},minute_start:function(s){return s.getUTCSeconds()&&s.setUTCSeconds(0),s.getUTCMilliseconds()&&s.setUTCMilliseconds(0),s},_add_days:function(s,c,l){return s.setUTCDate(s.getUTCDate()+c),s},add:function(s,c,l){var d=new Date(s.valueOf());switch(l){case"day":d=this._add_days(d,c,s);break;case"week":d=this._add_days(d,c*7,s);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](s,c,l)}return d},add_quarter:function(s,c){return this.add(s,c*3,"month")},to_fixed:function(s){return s<10?"0"+s:s},copy:function(s){return new Date(s.valueOf())},date_to_str:function(s,c){var l=Ul;return a()&&(l=Bl),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=Ul;return a()&&(l=Bl),l.str_to_date(s,c,e)},getISOWeek:function(s){return e.date._getWeekNumber(s,!0)},_getWeekNumber:function(s,c){if(!s)return!1;var l=s.getUTCDay();c&&l===0&&(l=7);var d=new Date(s.valueOf());d.setUTCDate(s.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(s){return e.date._getWeekNumber(s,e.config.start_on_monday)},getUTCISOWeek:function(s){return e.date.getISOWeek(s)},parseDate:function(s,c){if(s&&!s.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 s=="string"&&t.test(s)){var u=s.indexOf("T")!==-1,f=r(s);if(f)return o._isoDateDetected?u&&(o._isoDateOnly=!1):(o._isoDateDetected=!0,o._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),s?s=c(s):s=null}return s}};return o}function La(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Oa(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 ba(e,t,r,i,n,a,o){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=a,this.calendar=o,this}function hg(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 Hl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(_e(t)?t={date:t}:t=er({},t),!Ee(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 La)return t;var r;if(t.date?r=new La(t.date,t.unit,t.task,null,t.calendar):r=new La(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!Ee(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 Oa)return r;var i;if(_e(r)?i=new Oa(r):i=new Oa(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,!Ee(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=hg,i;if(t instanceof r)return t;if(_e(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,!Ee(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Ee(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 ba)return a;var o;if(_e(a)?o=new ba(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):o=new ba(a.start_date,a.duration,a.unit,a.step,a.task,null,a.calendar),a.id!==null&&a.id!==void 0&&(o.task=a,o.unit=null,o.step=null),o.unit=o.unit||e.config.duration_unit,o.step=o.step||e.config.duration_step,!Ee(o.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return o}}};function jl(){}jl.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 o=String(a);return o.length<2&&(o="0"+o),o}function i(a){var o=Math.floor(a/3600),s=a-o*60*60,c=Math.floor(s/60);return o+":"+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 o=r[a],s=0;s<i.length;s++){var c=i[s];c.start<o.end&&c.end>o.start&&(n.push({start:Math.max(o.start,c.start),end:Math.min(o.end,c.end)}),o.end>c.end&&(i.splice(s,1),s--,a--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,o){return a.start-o.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=Mt(e.getConfig()),i=Mt(t.getConfig()),n=r.parsed,a=i.parsed;n.customWeeks=r.customWeeks,a.customWeeks=i.customWeeks;var o={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,a.hours)),dates:{},customWeeks:{}};let s=(l,d)=>{for(let u in l.dates){let f=l.dates[u];+u>1e3&&(o.dates[u]=!1);for(let p in d.dates){let y=d.dates[p];if(p==u&&(o.dates[u]=!!(f&&y)),Array.isArray(f)){let g=Array.isArray(y)?y:d.hours;o.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,g))}}}};if(s(n,a),s(a,n),n.customWeeks)for(var c in n.customWeeks)o.customWeeks[c]=n.customWeeks[c];if(a.customWeeks)for(var c in a.customWeeks)o.customWeeks[c]?o.customWeeks[c+"_second"]=a.customWeeks[c]:o.customWeeks[c]=a.customWeeks[c];return o}};var Na=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,o=n.getUTCFullYear(),s;a.has(t)?s=a.get(t):(s=[],a.set(t,s));let c=s[o];c||(c=s[o]=new Map),c.set(r,i)}clear(){this._cache=new Map}},wa=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 o=a[i.getUTCFullYear()];if(o&&o[r]!==void 0)return o[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let o=a[t],s=n.getUTCFullYear(),c=o[s];c||(c=o[s]={}),c[r]=i}clear(){this._cache={}}},Fa=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,o=0,s=a.date.week_start(new Date(r));for(let c=0;c<7;c++)o+=n.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._weekCache.set(i,o),o},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,o=0,s=a.date.week_start(new Date(r)),c=a.date.add(s,1,"month").valueOf();for(;s.valueOf()<c;)o+=n.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._monthCache.set(i,o),o},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function mg(){return typeof Map<"u"?new Na:new wa}var xa=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 o=a[i];o||(o=a[i]={});let s=t.getUTCFullYear(),c=o[s];return c||(c=o[s]={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 o=this._getCacheObject(t,i,n),s=t.valueOf(),c=this._endDateCacheKey(s,r),l;if(o.endDates[c]===void 0){let d=a(),u=d.valueOf();o.endDates[c]=u,o.durations[this._durationCacheKey(s,u)]=r,l=d}else l=new Date(o.endDates[c]);return l}getDuration(t,r,i,n,a){let o=this._getCacheObject(t,i,n),s=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(s,c),d;if(o.durations[l]===void 0){let u=a();o.durations[l]=u.valueOf(),d=u}else d=o.durations[l];return d}clear(){this._cache={}}};function Ma(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=mg(),this._largeUnitsCache=new Fa(this),this._dateDurationCache=new xa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ma.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),o=new Date(t);i=i||1;var s=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()<o.valueOf();){if(c=this._nextDate(a,r,i),p=c.valueOf()>o.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),s+=(d.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):f&&p?(f=!1,s+=(o.valueOf()-a.valueOf())/(d.valueOf()-l.valueOf())):s++;else{var y=this._getUnitOrder(r),g=this.units[y-1];g&&!this._isWorkTime(a,g)&&(c=this._getClosestWorkTimeFuture(a,g))}a=c}return s},_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 o=Math.min(r,a.end)-Math.max(t,a.start);return o/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),o=new Date(t),s;for(r=="minute"?s=Et(this._getMinutesPerDay,this):s=Et(this.getHoursPerDay,this);a.valueOf()<o.valueOf();){if(o-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(o-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+=s(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 o=i[a];if(r.end>=o.start&&r.start<=o.end){var s=Math.max(o.start,r.start),c=Math.min(o.end,r.end);n+=(c-s)/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 o=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(o,s),u=this._getMinutesBetweenSingleDay(c,l),f=this._getWorkUnitsForRange(s,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 o=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(a.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(a)),l=a,d=this._getMinutesBetweenSingleDay(o,s,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,f=this._getWorkUnitsForRange(s,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,o=n.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!i||i<o.valueOf())&&(i=o.valueOf()),e.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:o.valueOf(),toReadable:new Date(o),name:t}),e.parsed.haveCustomWeeks=!0;var s=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)s.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],o=e.dates[a],s=t.dates[a];if(o!==s&&!(Array.isArray(o)&&Array.isArray(s)&&this._arraysEqual(o,s)))return!1}return!0},equals:function(e){if(!(e instanceof Ma))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 o=!0;return r.dates[n]!==void 0?o=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(o=r.dates[e.getUTCDay()]),o===!0?r.hours:o||[]},_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(s){typeof s=="number"?t.push(s*60*60):typeof s=="string"&&s.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],o=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:o,durationMinutes:o/60,durationHours:o/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(Et(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(Et(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 o=t;t=e,e=o,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),o=new Date(r);for(n=n||1;a.valueOf()<o.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 o=this;return this._dateDurationCache.getEndDate(t,r,i,n*a,function(){return o._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,o=e;a<t&&!(n&&n(o));){var s=this._nextDate(o,r,i),c=new Date(s.valueOf()+1);i>0&&(c=new Date(s.valueOf()-1));var l=this._isWorkTime(c,r);l&&a++,o=s}return{end:o,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),o=this._getWorkHours(e),s=0;s<o.length&&i<t;s++){var c=o[s];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 o=t-n;if(o){for(var s=i;n<t;){var c=this._nextDate(s,"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,s=c}i=s}if(n<t){var o=t-n;a=this._addHoursUntilDayEnd(i,o),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),o=this._getWorkHours(e),s=0;s<o.length&&i<t;s++){var c=o[s];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(),o=e.getUTCHours()*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),s=this._getWorkHours(e),c=s.length-1;c>=0&&i<t;c--){var l=s[c];if(o>l.start&&a<=l.end){var d=Math.min(o,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,o=u}}var y=r;return i===t&&(y=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o))),{added:i,end:y}},_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),o=this._subtractMinutesUntilHourStart(i,t);n+=o.added,i=o.end;for(var s=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!==s&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),s=f);var p=t-n,y=this._getTimeOfDayStamp(i,u);if(!c.length||!l){i=this.$gantt.date.add(i,-1,"day");continue}if(c[c.length-1].end<=y&&p>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var g=!1,C=null,R=null,A=c.length-1;A>=0;A--)if(c[A].start<y-1&&c[A].end>=y-1){g=!0,C=c[A],R=c[A-1];break}if(g)if(y===C.end&&p>=C.durationMinutes)n+=C.durationMinutes,i=this.$gantt.date.add(i,-C.durationMinutes,"minute");else if(!a&&p<=y/60-C.startMinute)n+=p,i=this.$gantt.date.add(i,-p,"minute");else if(a)p<=y/60-C.startMinute?(n+=p,i=this.$gantt.date.add(i,-p,"minute")):(n+=y/60-C.startMinute,R?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,R.end)):i=this.$gantt.date.day_start(i));else{var k=this._getMinutesPerHour(i);k<=p?(n+=k,i=this._nextDate(i,"hour",r)):(o=this._subtractMinutesUntilHourStart(i,p),n+=o.added,i=o.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var m=this._getClosestWorkTimePast(i,"hour");if(m.valueOf()===i.valueOf()){var m=this.$gantt.date.add(i,-1,"day"),L=this._getWorkHours(m);if(L.length){var F=L[L.length-1];m.setUTCSeconds(F.durationSeconds)}}i=m}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var T=t-n;o=this._subtractMinutesUntilHourStart(i,T),n+=o.added,i=o.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 o=0,s=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==o&&(s=this._getWorkHours(i),c=this._getMinutesPerDay(i),o=d);var u=t-n,f=this._getTimeOfDayStamp(i);if(!s.length||!c){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(s[0].start>=f&&u>=c){if(n+=c,u==c){i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,s[s.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,y=null,g=0;g<s.length;g++)if(s[g].start<=f&&s[g].end>f){p=!0,y=s[g];break}if(p)if(f===y.start&&u>=y.durationMinutes)n+=y.durationMinutes,i=this.$gantt.date.add(i,y.durationMinutes,"minute");else if(u<=y.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 R=t-n;a=this._addMinutesUntilHourEnd(i,R),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 o=this._getTimeOfDayStamp(i);if(a&&(o=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),t>0){for(var s=0;s<r.length;s++)if(r[s].start>=o){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].start));break}}else for(var s=r.length-1;s>=0;s--)if(r[s].end<=o){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].end));break}else if(r[s].end>o&&r[s].start<=o){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o));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,o=3e3,s=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(s++,s>o)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(o){if(!a){var s=t[o];s===!0?a=n:Array.isArray(s)&&(a=this._checkWorkHours(s))}}).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 Pr={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 gg(){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(o){var s=o&&o.resource_id?o.resource_id:o;return a.getResourceCalendar(s)}))}function i(n,a){var o=e(n);if(n.length){if(n.length===1)return a.getResourceCalendar(o).id;if(t[o])return t[o].id;var s=r(n,a);return t[o]=s,a.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:i}}var Ag=gg();function Vl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Pr.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))}Vl.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 jl,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 Ma(this.$gantt,Hl(this.$gantt));t.id=String(Pa());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=Mt(e.getConfig()):e.worktime?t=Mt(e.worktime):t=Mt(e);var r=Mt(this.defaults.fulltime.worktime);return er(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=Pr.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=Ag.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Pr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Pr.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=Pr.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||Pa(),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 Ua(e,t){this.argumentsHelper=t,this.$gantt=e}Ua.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},o=0;if(a[r])o=Math.round((t-e)/(i*a[r]));else{for(var s=new Date(e),c=new Date(t);s.valueOf()<c.valueOf();)o+=1,s=n.add(s,i,r);s.valueOf()!=t.valueOf()&&(o+=(c-s)/(n.add(s,i,r)-s))}return Math.round(o)},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 Ua},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 Kl(e){this.$gantt=e.$gantt,this.argumentsHelper=Hl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Ua(this.$gantt,this.argumentsHelper)}Kl.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 Ig=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:Et(e.mergeCalendars,e),createCalendar:Et(e.createCalendar,e),addCalendar:Et(e.addCalendar,e),getCalendar:Et(e.getCalendar,e),getCalendars:Et(e.getCalendars,e),getResourceCalendar:Et(e.getResourceCalendar,e),getTaskCalendar:Et(e.getTaskCalendar,e),deleteCalendar:Et(e.deleteCalendar,e)}},vg={create:Ig};function Yl(e){var t=new Vl(e),r=new Kl(t),i=vg.create(t,r);er(e,i)}var Gl={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 $l(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||Gl,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:Ml,mixin:er,copy:Mt,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=Wl(r),r.date.init(),Yl(r),r}function Cg(e={}){let t=$l(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 zl={createCalendar:Cg};var gF=3600*1e3;function Ql(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Sg}=zl,Lr="__replay_default__";function kg(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,o)=>a===r+o)?[`${r}:00-${i+1}:00`]:e}var ql={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Jl="__main_global__",Tg={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Xl(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 Dg(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:kg(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Zl(e){let t=Sg({config:{work_time:!0}});t.addCalendar({id:Lr,worktime:ql}),t.addCalendar({id:Jl,worktime:Tg});let r=new Set(e.filter(d=>!Xl(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Xl(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?Dg(d.worktime):ql});let n=xl(t),a=n.getCalendar(Lr),o=n.getCalendar(Jl);if(!a||!o)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([Lr]);for(let d of i)s.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 s.has(u)?p=n.getCalendar(d)??a:r.has(u)&&(p=o),c.set(u,p),p}}}}function td(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 _g(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 _g(e,t){let r=[],i=new Tt;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 Gi=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map,progressFallbackBefore: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,$t(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:$t(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:ed(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=$t(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:ed(r)}))}noteProgressFallback(t,r){let i=this._journal;!i||i.progressFallbackBefore.has(t)||i.progressFallbackBefore.set(t,r)}};function ed(e){return{...e}}var $i=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=rd(t);return this.reader.getCalendar(r??Lr)}getClosestWorkTime(t){let r=`${Wa(t.task)}|${t.dir}|${t.date.getTime()}`;return Ba(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:pt.HOUR}))}calculateEndDate(t){let r=`${Wa(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Ba(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Wa(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Ba(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 Ba(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var Eg="__default__";function rd(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Wa(e){return rd(e)??Eg}var zi=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&&!N(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||N(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(N(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(N(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?Wr(n,a):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var qi=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 rr=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Gi;_viewState=new qi;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=O(t.calendars);for(let i of t.activities)this._activities.set(i.id,i);for(let i of t.links){let n={...i,freeSlackHours:i.freeSlackHours??null,isCritical:i.isCritical===!0};this._links.set(String(i.id),n),this._indexLink(n)}this._calendar=new $i(Zl(this._calendarSnapshot)),this._flags=Pg(t),this._hierarchy=new zi(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map($t),links:this.getAllLinks().map(r=>({...r})),calendars:O(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(O(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([r,i])=>[r,new Date(i)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([r,i])=>[r,O(i)])),t._progressFallback=new Map(this._progressFallback),t._flags=O(this._flags),t._filterProjection=O(this._filterProjection),t}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=Lo(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)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,r){let i=String(t),n=this._progressFallback.get(i)??null;Object.is(n,r)||(this._writeCapture.noteProgressFallback(i,n),r===null?this._progressFallback.delete(i):this._progressFallback.set(i,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),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=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._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??id}getIncomingLinkIds(t){return this._incoming.get(String(t))??id}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,ja(n,r),r===b.PARENT&&this._hierarchy.markDirty(),Ha(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,Fl(r,i)),ja(n,r),r===b.PARENT&&this._hierarchy.markDirty(),Ha(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)),ja(i,a),a===b.PARENT&&(n=!0),Ha(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);let i={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),i),this._indexLink(i)}_indexLink(t){ad(this._outgoing,String(t.source),t.id),ad(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),nd(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),nd(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(!Rg(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.setProgressFallback(i,null),(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,progressFallbackBefore:o}=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._restoreProgressFallbacks(o),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,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()}_restoreProgressFallbacks(t){for(let[r,i]of t)i===null?this._progressFallback.delete(r):this._progressFallback.set(r,i)}_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))}},id=[];function Rg(e){return e===Cr.LAG||e===Cr.TYPE||e===Cr.FREE_SLACK_HOURS||e===Cr.IS_CRITICAL}function Ha(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function ja(e,t){t!==b.START_DATE&&t!==b.END_DATE&&t!==b.TYPE||(e.calendarDuration=Wt(e))}function nd(e,t){return e.filter(r=>String(r)!==String(t))}function ad(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function Pg(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 od(e,t){let r=e.getActivity(t);return r?O(r):null}function sd(e){return e.getAllActivities().map(O)}function cd(e){return e.getAllIds().map(String)}function ld(e,t){e.forEachActivity((r,i)=>t(i))}function dd(e,t){let r=t==="0"?Va(e,"0"):e.getChildren(t),i=[];for(let n of r){let a=e.getActivity(n);a&&i.push(O(a))}return i.sort((n,a)=>(n.correlativeId??0)-(a.correlativeId??0)),i}function Va(e,t){return Rt(t,e)}function ud(e){return e.checkedIds().map(String)}function fd(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=N(i.parentId)}),r}return e.getChildren(t).length>0}function Ka(e,t){let r=e.getLink(t);return r?St(r):null}function pd(e){return e.getAllLinks().map(t=>St(t))}function Ji(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Lg(e){return e.reduce((t,r)=>Ji(r)<Ji(t)?r:t)}function Og(e){return e.reduce((t,r)=>Ji(r)>Ji(t)?r:t)}function bg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function yd(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=bg(t);if(r.length===0)return null;let i=r.map(a=>a.split("-")[0]),n=r.map(a=>a.split("-")[1]);return{startHour:Lg(i),endHour:Og(n)}}function hd(e,t){return{calendars:e.calendarReader,hierarchy:td(e),activityReader:Ql(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function md(e){return Te(e)}var Ng=new Set(["freeSlackHours","isCritical"]);function wg(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([i])=>!t.has(i)));return e.kind==="updated"&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function vd(e){let t=e.activities.map(n=>({...n,after:null})),r=e.links.map(n=>wg(n,Ng)).filter(n=>n!==null),i=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return O({...e,source:i,activities:t,links:r})}function Ya(e,t,r,i,n,a,o){return{changeSet:e,beforeSnap:t,beforeLinks:gd(r),afterSnap:i,afterLinks:gd(n),progressFallbackBefore:a,progressFallbackAfter:o}}function gd(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Cd(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),et(a))}for(let n of t.links){if(n.kind==="deleted")continue;let a=e.getLink(String(n.id));a&&i.set(String(n.id),{...a})}return{afterSnap:r,afterLinks:i}}function Sd(e){return e.kind!==P.INLINE_EDIT||!_r.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Ad(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 kd(e,t){if(!Ad(e)||!Ad(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function Td(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??{},o={};for(let c of new Set([...Object.keys(n),...Object.keys(a)])){let l=n[c],d=a[c];o[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let s={...t.changeSet,activities:[{...i,fields:o}]};return Ya(s)}function Dd(e){return e.kind===P.PERSISTENCE_ACKNOWLEDGE?"checkpoint-on-success":e.kind===P.SIR_SYNC||e.kind===P.CALENDAR_RECONCILE||e.kind===P.ACTIVITY_LOOKAHEAD_SYNC||e.kind===P.BASELINE_APPLY||e.kind===P.PONDERATOR_CRITERION_SET||e.kind===P.STATUS_CRITERIA_SET||e.kind===P.ACTIVITY_CLIPBOARD_CLEAR||e.kind===P.ACTIVITY_COPY||e.kind===P.SELECTION_TOGGLE||e.kind===P.SELECTION_REPLACE||e.kind===P.VISIBILITY_SET||e.kind===P.FILTER_SET||e.kind===P.SORT_SET?"skip":"record"}function Ga(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&S.CUSTOM_ID in t.fields)return!0;return!1}function $a(e,t,r){let i=[],n=[];for(let o of t.changeSet.activities){let s=String(o.id);if(o.kind==="updated"){let c=e.getActivity(s);i.push({id:s,kind:"updated",fields:Id(o.fields,r),after:c?et(c):null})}else if(o.kind==="deleted")if(r==="before"){let c=e.getActivity(s);i.push({id:s,kind:"created",after:c?et(c):null})}else i.push({id:s,kind:"deleted",after:null});else if(r==="before")i.push({id:s,kind:"deleted",after:null});else{let c=e.getActivity(s);i.push({id:s,kind:"created",after:c?et(c):null})}}for(let o of t.changeSet.links){let s=String(o.id);if(o.kind==="updated"){let c=e.getLink(s);n.push({id:s,kind:"updated",fields:Id(o.fields,r),after:c?St(c):null})}else if(o.kind==="deleted")if(r==="before"){let c=e.getLink(s);n.push({id:s,kind:"created",after:c?St(c):null})}else n.push({id:s,kind:"deleted",after:null});else if(r==="before")n.push({id:s,kind:"deleted",after:null});else{let c=e.getLink(s);n.push({id:s,kind:"created",after:c?St(c):null})}}let a=(t.changeSet.viewState??[]).map(o=>r==="before"?Fg(o):o);return{source:{kind:r==="before"?Gt.UNDO:Gt.REDO},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Id(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t==="before"?{before:O(i.after),after:O(i.before)}:{before:O(i.before),after:O(i.after)}]))}function Fg(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 za(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function _d(e,t){Rd(e,t,"before")}function Ed(e,t){Rd(e,t,"after")}function Rd(e,t,r){let i=t.changeSet;for(let a of i.activities)if(a.kind==="updated"){if(!a.fields)continue;for(let[o,s]of Object.entries(a.fields))st(e,a.id,o,r==="before"?s.before:s.after)}else if(a.kind==="deleted")if(r==="before"){let o=t.beforeSnap?.get(String(a.id));if(!o)throw new Error(`undo: missing beforeSnap for resurrecting activity ${a.id}`);e.addActivity(et(o))}else e.removeActivity(String(a.id));else if(r==="before")e.removeActivity(String(a.id));else{let o=t.afterSnap?.get(String(a.id));if(!o)throw new Error(`redo: missing afterSnap for re-creating activity ${a.id}`);e.addActivity(et(o))}for(let a of i.links)if(a.kind==="updated"){if(!a.fields)continue;if(Object.hasOwn(a.fields,"source")||Object.hasOwn(a.fields,"target")){let o=r==="before"?t.beforeLinks?.get(String(a.id)):t.afterLinks?.get(String(a.id));if(!o)throw new Error(`${r==="before"?"undo":"redo"}: missing link snapshot for ${a.id}`);e.removeLink(String(a.id)),e.addLink({...o});continue}for(let[o,s]of Object.entries(a.fields))Vs(e,String(a.id),o,r==="before"?s.before:s.after)}else if(a.kind==="deleted")if(r==="before"){let o=t.beforeLinks?.get(String(a.id));if(!o)throw new Error(`undo: missing beforeLinks for re-adding link ${a.id}`);e.addLink(o)}else e.removeLink(String(a.id));else if(r==="before")e.removeLink(String(a.id));else{let o=t.afterLinks?.get(String(a.id));if(!o)throw new Error(`redo: missing afterLinks for re-creating link ${a.id}`);e.addLink(o)}for(let a of i.viewState??[])a.checked&&e.setChecked(a.activityId,r==="before"?a.checked.before:a.checked.after),a.visible&&e.setVisible(a.activityId,r==="before"?a.visible.before:a.visible.after);let n=r==="before"?t.progressFallbackBefore:t.progressFallbackAfter;for(let[a,o]of n??[])e.setProgressFallback(a,o)}var xg=100,Mg=600,Xi=class e{constructor(t=xg){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...O(this.undoStack)),t.redoStack.push(...O(this.redoStack)),t.sequence=this.sequence,t._lastKey=this._lastKey,t._lastTime=this._lastTime,t}record(t,r=null,i=0){let n=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&i-this._lastTime<=Mg&&n!==void 0&&kd(n.entry,t)?(n.entry=Td(n.entry,t),n.touchedAt=this.touch()):(this.undoStack.push({entry:t,touchedAt:this.touch()}),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()?.entry??null}takeRedo(){return this.redoStack.pop()?.entry??null}pushRedo(t){this.redoStack.push({entry:t,touchedAt:this.touch()})}pushUndo(t){this.undoStack.push({entry:t,touchedAt:this.touch()})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(t){this.removeEntriesThrough(this.undoStack,t),this.removeEntriesThrough(this.redoStack,t),this.resetCoalesce()}applyPersistedIdentities(t,r){let i=new Map(t.map(({id:a,proplannerId:o})=>[String(a),o])),n=new Map(r.map(({id:a,proplannerId:o})=>[String(a),o]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,i,n)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,r){let i=t.filter(({touchedAt:n})=>n>r);t.splice(0,t.length,...i)}withPersistedIdentities(t,r,i){let n=o=>o===void 0?void 0:new Map(Array.from(o,([s,c])=>[s,r.has(s)?{...c,proplannerId:r.get(s)}:c])),a=o=>o===void 0?void 0:new Map(Array.from(o,([s,c])=>[s,i.has(s)?{...c,proplannerId:i.get(s)}:c]));return{...t,beforeSnap:n(t.beforeSnap),afterSnap:n(t.afterSnap),beforeLinks:a(t.beforeLinks),afterLinks:a(t.afterLinks)}}};var Ug=["parentId","correlativeId"];function Ld(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(Pd(c.parentId?.before));continue}let o=n.fields;!o||!Ug.some(c=>c in o)||(i(a),"parentId"in o&&r.add(Pd(o.parentId?.before)))}return r}function Pd(e){return e==null?"0":String(e)}function Bg(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Wg(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Od(e){return{id:String(e.id),worktime:Wg(e.worktime)}}function Qi(e,t,r,i=[]){let n=t.map(Bg),a=[...r.map(Od),...i.map(Od)];return{activities:[...e],links:n,calendars:a}}var bd={id:"ignored",proplannerId:"ignored",parentId:"tracked",name:"tracked",description:"tracked",type:"tracked",startDate:"tracked",endDate:"tracked",durationHours:"tracked",constraintType:"tracked",constraintDate:"tracked",autoScheduling:"tracked",calendarId:"tracked",assignedDefaultCalendar:"ignored",dateOrigin:"tracked",progress:"tracked",cost:"tracked",usedCost:"tracked",realCost:"tracked",workHours:"tracked",realWorkHours:"tracked",ponderator:"tracked",hasCustomPonderator:"tracked",correlativeId:"tracked",uniqueCorrelativeId:"tracked",customId:"tracked",subcontractId:"tracked",isLookahead:"tracked",hasLookaheadTasks:"ignored",newActivityIds:"tracked",hasNewActivities:"tracked",isNewActivity:"ignored",pendingRequestIds:"ignored",responsableIds:"tracked",tagIds:"tracked",baselinePoints:"ignored",baselineSnapshot:"ignored",recursiveDurationHours:"ignored",isCritical:"ignored",freeSlackHours:"ignored",calendarDuration:"ignored",expectedProgress:"ignored",expectedProgressBaseline:"ignored",status:"ignored",criticalPath:"ignored"},Nd=Object.keys(bd).filter(e=>bd[e]==="tracked"),wd=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Fd=new Set(["newActivityIds","responsableIds","tagIds"]);function xd(e){let t=Nd.map(r=>[r,Hg(r,e[r])]);return Object.fromEntries(t)}function Hg(e,t){return wd.has(e)?t instanceof Date?new Date(t):null:Fd.has(e)?Array.isArray(t)?[...t]:[]:t}function Or(e,t){return qa(e,t).length>0}function qa(e,t){return Nd.filter(r=>!jg(r,e[r],t[r]))}function jg(e,t,r){return wd.has(e)?Vg(t,r):Fd.has(e)?Kg(t,r):(t??null)===(r??null)}function Vg(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function Kg(e,t){let r=new Set(Array.isArray(e)?e.map(String):[]),i=new Set(Array.isArray(t)?t.map(String):[]);if(r.size!==i.size)return!1;for(let n of r)if(!i.has(n))return!1;return!0}var Md={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},Yg=Object.keys(Md).filter(e=>Md[e]==="tracked");function Zi(e,t){return Yg.some(r=>e[r]!==t[r])}function Ud(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?Zi(n,i):!1})}function Ut(e){if(e==null||e===0)return!1;if(!(typeof e=="number"&&Number.isSafeInteger(e)&&e>0))throw new Error(`invalid proplannerId ${String(e)}`);return!0}function Bd(e,t){for(let r of e)Ut(r.proplannerId);for(let r of t)Ut(r.proplannerId)}var tn=class e{trackingEnabled;initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;constructor(t=!0){this.trackingEnabled=t}fork(){let t=new e(!1);t.initialized=this.initialized;for(let[r,i]of this.linksAtLastSave)t.linksAtLastSave.set(r,O(i));for(let[r,i]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,O(i));return t}init(t,r){if(this.trackingEnabled){Bd(t,r),this.snapshotActivities(t),this.snapshotLinks(r);for(let i of t)if(i.assignedDefaultCalendar){let n=String(i.id);this.initialCalendarRepairIds.add(n),this.dirtyActivityIds.add(n)}this.initialized=!0}}acknowledge(t,r,i=[],n=[],a,o){if(!this.trackingEnabled)return;let s=new Map(i.map(({id:p,proplannerId:y})=>[String(p),y])),c=new Map(n.map(({id:p,proplannerId:y})=>[String(p),y])),l=t.map(p=>({...p,proplannerId:s.get(String(p.id))??p.proplannerId})),d=r.map(p=>{let y=c.get(String(p.id));return y===void 0?{...p}:{...p,proplannerId:y}});if(Bd(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!a||!o)return;let u=new Map(a.map(p=>[String(p.id),p])),f=new Map(o.map(p=>[String(p.id),p]));for(let p of l){let y=String(p.id);this.activityIsDirty(y,u.get(y)??null)&&this.dirtyActivityIds.add(y)}for(let p of a){let y=String(p.id);this.activityIsDirty(y,p)&&this.dirtyActivityIds.add(y)}for(let p of d){let y=String(p.id);this.linkIsDirty(y,f.get(y)??null)&&this.dirtyLinkIds.add(y)}for(let p of o){let y=String(p.id);this.linkIsDirty(y,p)&&this.dirtyLinkIds.add(y)}}snapshotActivities(t){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let r of t){let i=String(r.id);if(!Ut(r.proplannerId)){this.dirtyActivityIds.add(i);continue}let n=xd(r);this.activitiesAtLastSave.set(String(r.id),{persistable:n,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),Or(r,n)&&this.dirtyActivityIds.add(i)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let i=String(r.id);if(!Ut(r.proplannerId)){this.dirtyLinkIds.add(i);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}}recordChanges(t,r,i,n){if(!(!this.trackingEnabled||!this.initialized)){for(let a of t){let o=String(a.id),s=i(o);this.activityIsDirty(o,s)?this.dirtyActivityIds.add(o):this.dirtyActivityIds.delete(o)}for(let a of r){let o=String(a.id),s=n(o);this.linkIsDirty(o,s)?this.dirtyLinkIds.add(o):this.dirtyLinkIds.delete(o)}}}activityIsDirty(t,r){let i=this.activitiesAtLastSave.get(t);return r===null?i!==void 0:this.initialCalendarRepairIds.has(t)||!Ut(r.proplannerId)||i===void 0||Or(r,i.persistable)}linkIsDirty(t,r){let i=this.linksAtLastSave.get(t);return r===null?i!==void 0:!Ut(r.proplannerId)||i===void 0||Zi(i,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let i=t.map(n=>{let a=typeof n=="string"?n:String(n.id),o=r(a),s=this.activitiesAtLastSave.get(a);if(o===null||s===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof n=="string"||!!n.fields?.isLookahead,acknowledgesProgress:typeof n!="string"&&!!n.fields?.progress,current:o,saved:s}});for(let{activityId:n,acknowledgesLookahead:a,acknowledgesProgress:o,current:s,saved:c}of i){let l={...c.persistable,...a?{isLookahead:s.isLookahead}:{},...o?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(n,{...c,persistable:l}),this.initialCalendarRepairIds.has(n)||!Ut(s.proplannerId)||Or(s,l)?this.dirtyActivityIds.add(n):this.dirtyActivityIds.delete(n)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=t(i);n!==null&&!Ut(n.proplannerId)&&r.push(n)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=t(i);n!==null&&!Ut(n.proplannerId)&&r.push(n)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=this.activitiesAtLastSave.get(i);n&&t(i)===null&&r.push({...n.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=this.linksAtLastSave.get(i);n&&t(i)===null&&r.push({...n})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyActivityIds){let n=t(i);if(n===null||!Ut(n.proplannerId))continue;let a=this.activitiesAtLastSave.get(i);(a===void 0||this.initialCalendarRepairIds.has(i)||Or(n,a.persistable))&&r.push(n)}return r}modifiedActivityFields(t){let r=new Map;if(!this.trackingEnabled||!this.initialized)return r;for(let i of this.dirtyActivityIds){let n=t(i),a=this.activitiesAtLastSave.get(i);if(!n||!a)continue;let o=qa(n,a.persistable);o.length>0&&r.set(i,o)}return r}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let i of this.dirtyLinkIds){let n=t(i);if(n===null||!Ut(n.proplannerId))continue;let a=this.linksAtLastSave.get(i);(a===void 0||Zi(a,n))&&r.push(n)}return r}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Wd=1440*60*1e3,Hd=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,en=7,Ja=[!1,!0,!0,!0,!0,!0,!1],jd=new Set(["1","true"]),Xa=dt.DURATION,Vd="asap",Kd={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 Yd(e,t){let r=[],i=e.map(a=>{let o=eA(a,t);return a.should_be_showed===!1&&r.push(o.id),o});iA(i);let n=new Set(i.map(a=>a.id));return nA(i,n,t.reporter),{activities:i,activityIds:n,hiddenIds:r}}function Gg(e,t){if(!e)return null;let r=Kd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Vd):r}function $g(e,t){let r=Gg(e.constraint,t),n=r!=="asap"&&r!=="alap"&&e.constraint_date?zt(e.constraint_date):null;return{constraintType:r,constraintDate:n}}function zg(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function qg(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 Jg(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Qa(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Jg(r)&&t.push(String(r.id));return t}function Xg(e){return e==="0"?null:String(e)}function Qg(e){if(e==null)return null;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid activity proplannerId ${String(e)}`);return e}function Zg(e,t){return typeof e.is_critical=="boolean"?e.is_critical:(t.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${e.unique_id}" received ${typeof e.is_critical}`)),!1)}function tA(e,t){return Array.isArray(e)?e.map(r=>Hi(r,t)).filter(r=>r!==null):[]}function eA(e,t){let r=zg(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:a,constraintDate:o}=$g(e,t.reporter),s=e.type==="milestone",c=zt(e.start_date),l=s?c:zt(e.end_date),d=s?0:Number(e.duration),u=Zg(e,t.reporter);return{id:String(e.unique_id),proplannerId:Qg(e.id),parentId:Xg(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:ge(d,t.hoursPerDay),constraintType:a,constraintDate:o,autoScheduling:he(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:zt(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:rA(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:qg(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Qa(e.pendingRequests),responsableIds:Qa(e.responsables),tagIds:Qa(e.tags),baselinePoints:tA(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:ge(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Wt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function rA(e){return e.has_childs?null:e.custom_id}function iA(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function nA(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 qd(e,t,r,i=null){let o=(e!==void 0&&e.length>0?e:t??[]).map(c=>oA(c,i)),s=(r??[]).map(c=>sA(c,i));return{calendars:o,baseCalendars:s,knownCalendarIds:new Set(o.map(c=>c.id)),defaultCalendarId:aA(o)}}function aA(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Jd(e,t){let r=pA(e.working_days),{days:i,hours:n}=fA(e,r),a=cA(t.exceptionsSource,t.exceptionRange),o={days:i,hours:n};return a&&(o.dates=a),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:o}}function oA(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return Jd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function sA(e,t){return Jd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function cA(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=lA(i.from_date,i.to_date,t);if(n.length===0)continue;let a=dA(i);if(a!==void 0)for(let o of n)r[o]=a}return Object.keys(r).length>0?r:null}function lA(e,t,r){let i=Gd(e),n=Gd(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let a=[],o=r?Math.max(i,r.start):i,s=r?Math.min(n,r.end):n;for(;o<=s;)a.push(String(o)),o+=Wd;return a}function Gd(e){if(typeof e!="string")return null;let t=Hd.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 dA(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=uA(t);if(r.length>0)return r}}var $d=/^\d{1,2}:\d{2}$/;function uA(e){let t=[];for(let r of e){let i=Zd(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),c=i.endsCsv.trim();!rn(s)&&!rn(c)&&$d.test(s)&&$d.test(c)&&t.push(`${s}-${c}`);continue}let o=Qd(i.startsCsv,i.endsCsv).find(s=>s!==null);o&&t.push(o)}return t.sort(Xd),t}function zd(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 Xd(e,t){return zd(e)-zd(t)}function fA(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=Qd(l,d);for(let f=0;f<7;f+=1){let p=u[f],y=r[f];p&&y&&y.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=Zd(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(Xd);let s=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:s}),hours:s}}function Qd(e,t){let r=Array.from({length:en},()=>null);if(typeof e!="string"||typeof t!="string")return r;let i=e.split(",").map(s=>s.trim()),n=t.split(",").map(s=>s.trim());if(!(i.length===n.length&&i.length>0&&i.length<=en))return r;let o=[...r];for(let s=0;s<i.length;s+=1){let c=i[s],l=n[s];rn(c)||rn(l)||(o[s]=`${c}-${l}`)}return o}function Zd(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 pA(e){if(typeof e!="string")return[...Ja];let t=e.split(",").map(r=>r.trim());return t.length!==en?[...Ja]:t.map(r=>jd.has(r))}var yA=new Set(["false","null"]);function rn(e){return!e||yA.has(e)}function hA(e){return e==="0"||e==="1"||e==="2"||e==="3"}function mA(e){if(typeof e!="string")return null;let t=is(e);return t||(hA(e)?e:null)}function gA(e){if(e==null)return;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid link proplannerId ${String(e)}`);return e}function eu(e,t){let r=[];for(let i of e)try{r.push(AA(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return IA(r)}function AA(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 o=mA(e.type);if(o===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let s=e.ganttId,c=e.sectorId,l=gA(e.id);return{id:i,source:n,target:a,type:o,lag:Pt(Number(e.lag??0),r),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function IA(e){let t=new Map;for(let r of e){let i=`${r.source}-${r.target}-${r.type}`,n=t.get(i);(!n||tu(r)>tu(n))&&t.set(i,r)}return[...t.values()]}function tu(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function vA(e){if(typeof e!="string")return Xa;switch(e.toUpperCase()){case dt.DURATION:return dt.DURATION;case dt.COST:return dt.COST;case dt.WORK_HOURS:return dt.WORK_HOURS;default:return Xa}}function CA(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function SA(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ru(e){let t=CA(e),r=SA(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:vA(e.activity_creter),statusCriteria:jn,ganttId:null}}function nn(e,t=Be){let r=ru(e.sector),{calendars:i,baseCalendars:n,knownCalendarIds:a,defaultCalendarId:o}=qd(e.calendars,e.sector.calendars,e.baseCalendars,kA(e.activities)),{activities:s,activityIds:c,hiddenIds:l}=Yd(e.activities,{knownCalendarIds:a,defaultCalendarId:o,hoursPerDay:r.hoursPerDay,reporter:t}),d=eu(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:s,links:d,calendars:i,baseCalendars:n,viewStateSeed:{hiddenIds:l}}}function kA(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let a of e){let o=new Date(a.start_date).getTime(),s=new Date(a.end_date).getTime();Number.isFinite(o)&&(t=Math.min(t,o)),Number.isFinite(s)&&(r=Math.max(r,s))}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 Za(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{fork(){return Za({seed:t})},next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)},snapshot(){return t},restore(i){t=i}}}function to(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{fork(){return to({seed:t})},next(){return t+=1,String(t)},bump(i){let n=typeof i=="number"?i:Number(i);Number.isFinite(n)&&r(n)},snapshot(){return t},restore(i){t=i}}}function eo(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{fork(){return eo({seed:t})},next(){return t+=1,String(t)},bump(i){if(i==null)return;let n=typeof i=="number"?i:Number(i);r(n)},snapshot(){return t},restore(i){t=i}}}function iu(e){return!!e&&typeof e=="string"&&e.trim().length>0}function an(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function on(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function nu(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function au(e,t){return!t&&iu(e)}function ou(e,t){return t&&iu(e)}function br(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function sn(e){if(!br(e))return 0n;try{return BigInt(e)}catch{return 0n}}function TA(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!br(t))return r;let i=t.length;return r.padStart(i,"0")}function bt(e,t){let r=sn(e),i=sn(t),n=r+i;return TA(n,e)}function cn(e,t){let r=sn(e),i=sn(t);return r<i?-1:r>i?1:0}function ln(e,t){return cn(e,t)<=0?e:t}function dn(e,t){return cn(e,t)>=0?e:t}function su(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>ln(t,r))}function cu(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>dn(t,r))}function lu(e){return{prefix:e,baseSuffix:null}}function du(e,t){let r=on(e);return{prefix:an(e),baseSuffix:bt(r,t)}}function uu(e){return{prefix:e,baseSuffix:null}}function fu(e,t){return au(e,t)?"parentConversion":ou(e,t)?"pasteReference":"noContext"}function pu(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var un=class e{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?pu(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=su(i),r.max=cu(i),r.quantity=i.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}fork(){let t=new e({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[r,i]of this.prefixMap)t.prefixMap.set(r,pu(i));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return an(t)}extractSuffix(t){return on(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=ln(r,i.min),i.max=dn(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=ln(i,n.min),n.max=dn(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:bt(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}${bt(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&br(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(;cn(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=bt(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||!br(r)){let s=bt(i.max,n);return`${t}${s}`.length>20?null:s}let a=r;for(let s=0;s<100;s++){if(`${t}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=bt(a,n)}let o=bt(i.max,n);return`${t}${o}`.length>20?null:o}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 o=this.getNextAvailableSuffix(t,bt(r,this.suffixIncrement));if(o===null)return this._generateDefaultCustomId();r=o,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=nu(r),a=fu(n,i),{prefix:o,baseSuffix:s}=this._applyGenerationStrategy(a,n),c=null;if(a==="parentConversion"&&this.prefixMap.has(o)){this._ensureFreshBounds(o);let f=this.prefixMap.get(o).max;c=bt(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(n);let l=a==="parentConversion"&&c?c:s,d=this.getNextAvailableSuffix(o,l);if(d===null){let f=this._generateDefaultCustomId();return this.registerCustomId(f),f}let u=`${o}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case"parentConversion":return lu(this.defaultPrefix);case"pasteReference":return du(r,this.suffixIncrement);default:return uu(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),a=this.extractSuffix(i),o=bt(a,this.suffixIncrement),s=this.getNextAvailableSuffix(n,o);if(s===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${n}${s}`;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 DA=1,_A=-1;function EA(e,t){return!e&&!t?null:e&&t?0:e?DA:_A}function yu(e){return e==null}function hu(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function RA(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 PA(e,t){let r=Xt(e.field);return r===null?null:(i,n)=>{let a=r.extract(i,t),o=r.extract(n,t),s=EA(yu(a),yu(o));if(s!==null)return s;let c=r.valueKind===E.ENUM?hu(a,r.order)-hu(o,r.order):RA(a,o,t.locale);return e.direction===ye.DESCENDING?-c:c}}function mu(e,t){let r=e.rules.map(i=>PA(i,t)).filter(i=>i!==null);return r.length===0?null:(i,n)=>{for(let a of r){let o=a(i,n);if(o!==0)return o}return 0}}function gu(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,Ue),LA(e,r)}function LA(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:rt.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 Au(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 o=[...e.getChildren(n)],s=o.length===0?Ct(a.workHours,a.progress):o.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,b.REAL_WORK_HOURS,s),r.push(n),s};for(let n of t)i(n);return r}async function Iu(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:a}=e;if(At(t),r.updateDurationForPrimaveraEndDate&&bA(t),NA(t),Au(t),n){gr(t),a&&(Ce(t,a),qt(t,r.statusCriteria));return}let o=await i.schedule({});fr(t,o),wA(t),OA(t),await He(t,void 0,!1),gr(t),a&&(Ce(t,a),qt(t,r.statusCriteria))}function OA(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}),t.calendarDuration=Wt(t))})}function bA(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function NA(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=Yt(t.constraintDate,n,r))})}function wA(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=Yt(t.constraintDate,i,r))})}var Bt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function vu(e){let t=e.clock??null,r=t?.()??null,i=r?ci(r):null,n=e.reporter??Be,a=nn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n),o=a.sector;o.statusCriteria=Ii(e.statusCriteria),o.ganttId=e.ganttId??null;let s=a.calendars,c=a.baseCalendars??[],l=Qi(a.activities,a.links,a.calendars,c),d=A=>mu(A,pe(o.hoursPerDay)),u=new rr(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new We(u,n);gu(u);let p=Za({knownIds:a.activities.map(A=>A.id)}),y=to({seed:r?.getTime()??0,knownIds:a.links.map(A=>A.id)}),g=eo({knownIds:a.activities.map(A=>A.uniqueCorrelativeId)}),C=new un({defaultPrefix:o.customIdPrefix,suffixIncrement:o.customIdIncrement});if(C.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let A=c.find(k=>k.baseDefault)?.id??null;ji(u,e.baselinePoints,i,n,A)}let R=Iu({state:u,sector:o,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:i??void 0});return{sector:o,state:u,scheduler:f,activityIdGen:p,linkIdGen:y,uidGen:g,customIdTracker:C,calendars:s,baseCalendars:c,clock:t,reporter:n,initPromise:R}}function ir(e){if(e===void 0)return["undefined"];if(e===null)return["null"];if(typeof e=="string")return["string",e];if(typeof e=="boolean")return["boolean",e];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="bigint")return["bigint",String(e)];if(e instanceof Date)return["date",String(e.getTime())];if(Array.isArray(e))return["array",e.map(ir)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[ir(t),ir(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,ir).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,ir(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function Re(e){return JSON.stringify(ir(e))}function ro(e,t){let r=new Map(e.map(o=>[String(o.id),o])),i=new Map(t.map(o=>[String(o.id),o])),n=[...new Set([...r.keys(),...i.keys()])].sort(),a=[];for(let o of n){let s=i.get(o),c=r.get(o);if(c===void 0){a.push({id:o,kind:"deleted",after:null});continue}if(s===void 0){a.push({id:o,kind:"created",after:O(c)});continue}let l=FA(s,c);Object.keys(l).length>0&&a.push({id:o,kind:"updated",fields:l,after:O(c)})}return a}function FA(e,t){let r={},i=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of i)Re(e[n])!==Re(t[n])&&(r[n]={before:O(e[n]),after:O(t[n])});return r}function xA(e,t){let r=new Set(t.selectedIds.map(String)),i=new Set(e.selectedIds.map(String)),n=new Set(t.hiddenIds.map(String)),a=new Set(e.hiddenIds.map(String)),o=e.activities.map(({id:c})=>String(c)).sort(),s=[];for(let c of o){let l=r.has(c),d=i.has(c),u=!n.has(c),f=!a.has(c);l===d&&u===f||s.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===f?{}:{visible:{before:u,after:f}}})}return s}function Cu(e,t){let r=Re(e.order)!==Re(t.order);return{source:{kind:Gt.INIT},activities:ro(e.activities,t.activities),links:ro(e.links,t.links),calendars:ro(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:xA(e,t),...r?{order:O(e.order)}:{}}}var nr={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},MA=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),io=(e,t)=>e===null?t:Math.min(e,t),no=(e,t)=>e===null?t:Math.max(e,t);function ku(e,t,r){let i=[...new Set(t.kind===nr.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=UA(e,t,i);return BA(e,i,n),{getDates(a,o){if(r(),!Number.isFinite(o))throw new Error("[ScheduleCore] invalid date gesture edge");let s=n.get(String(a));if(!s)return null;let c=HA(s,o),l=jA(s,o);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function UA(e,t,r){let i=new Map,n=t.kind===nr.MOVE?String(t.anchorActivityId):null,a=n===null?null:Su(e,n);if(n!==null&&!r.includes(n))throw new Error("[ScheduleCore] move anchor is not a participant");for(let o of r){let s=Su(e,o);if(t.kind===nr.MOVE){let c=a.startDate.getTime();i.set(o,{constantStart:null,variableStartOffset:s.startDate.getTime()-c,constantEnd:null,variableEndOffset:s.endDate.getTime()-c})}else t.kind===nr.RESIZE_START?i.set(o,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):i.set(o,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return i}function BA(e,t,r){let i=Ar(e,new Set(t));for(let n of i){let a=MA();for(let o of e.getChildren(n)){let s=r.get(o);if(s){WA(a,s);continue}let c=e.getActivity(o);if(!c)throw new Error(`[ScheduleCore] missing child ${o} while previewing parent ${n}`);a.constantStart=io(a.constantStart,c.startDate.getTime()),a.constantEnd=no(a.constantEnd,c.endDate.getTime())}r.set(n,a)}}function Su(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function WA(e,t){t.constantStart!==null&&(e.constantStart=io(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=io(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=no(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=no(e.variableEndOffset,t.variableEndOffset))}function HA(e,t){if(e.variableStartOffset===null)return e.constantStart;let r=t+e.variableStartOffset;return e.constantStart===null?r:Math.min(e.constantStart,r)}function jA(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}var ao=Symbol("ScheduleCore.fork.source");function VA(e){return e.kind===P.PERSISTENCE_ACKNOWLEDGE||e.kind===P.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function KA(e){for(let t of e.activities)if(t.kind==="deleted"||t.kind==="updated"&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function YA(e,t){let r=[];for(let i of e.activities){let n=t.getActivity(i.id);if(n===null)return null;r.push(n)}return r}function GA(e,t,r){if(e===null||e.filter!==t)return!1;let i=e.context.hoursPerDay===r.hoursPerDay,n=e.context.locale===r.locale;return i&&n}var ar=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=Bt.READY;coreRuntime;_isFork;_undo=new Xi;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,yo(this)),ao in t){this._isFork=!0;let n=t[ao],a=n.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new We(a,n.coreRuntime.reporter),sector:O(n.coreRuntime.sector),activityIdGenerator:n.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:n.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:n.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:n.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(n.coreRuntime.calendars,([o,s])=>[o,O(s)])),baseCalendars:O(n.coreRuntime.baseCalendars),clock:n.coreRuntime.clock,reporter:n.coreRuntime.reporter},this._activityClipboard.value=O(n._activityClipboard.value),this._undo=n._undo.fork(),this._saveTracker=n._saveTracker.fork(),this._scheduleRevision=n._scheduleRevision,this._pendingScheduleRevision=n._scheduleRevision,this._criticalPathRevision=n._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let r=vu(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!==Bt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let i=t.criticalPathOnLoad===!0;this._ready=i?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[ao]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return O(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),od(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return ku(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),sd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=Wi(t.map(i=>String(i)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(t){return this.assertReady(),dd(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Ka(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,i=[],n=new Set,a=o=>{if(n.has(o))return;n.add(o);let s=Ka(r,o);s&&i.push(s)};for(let o of r.getOutgoingLinkIds(t))a(o);for(let o of r.getIncomingLinkIds(t))a(o);return i}getAllLinksView(){return this.assertReady(),pd(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),i=yr(t,r),n=Jr(i),a=0;for(let o of n)o.length>a&&(a=o.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:i.length,circularComponents:n,largestComponentSize:a}}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?O(i[r]):null}getAllIds(){return this.assertReady(),cd(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),ld(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),Va(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),ud(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let t=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(r=>!t.has(r))}getActiveFilter(){return this.assertReady(),O(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),O(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),fd(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?O(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>O(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>O(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),yd(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(O)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(O)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(O)}getModifiedActivityFields(){return this.assertReady(),O(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(O)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}getCanonicalDigest(){this.assertReady();let t=(r,i)=>String(r.id).localeCompare(String(i.id));return Re({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(t),links:[...this.getAllLinksView()].sort(t),calendars:[...this.getAllCalendars()].sort(t),baseCalendars:[...this.getBaseCalendars()].sort(t)})}createProjectionChangeSetFrom(t){this.assertReady(),t.assertReady();let r=i=>({activities:i.getAllActivitiesView(),links:i.getAllLinksView(),calendars:i.getAllCalendars(),selectedIds:i.getSelectedActivityIds(),hiddenIds:i.getHiddenActivityIds(),order:xe(i.coreRuntime.state)});return Cu(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(O)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(O)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return ha(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,r){t&&(r||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(i=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",i)})))}async dispatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}async applyActivityBatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}async _dispatchInner(t,r={},i=!1){let n=!1;try{let a=await this._runDispatch(t,r);return n=a.changedState,a.result}finally{this._settleScheduleMutation(i,n)}}async _runDispatch(t,r){if(this.assertReady(),this._isFork&&VA(t))return{result:{ok:!1,reason:v.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let i=hd(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),n=Dd(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let o,s;try{o=await wl(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,isActivityIdReserved:l=>this._saveTracker.hasCheckpointActivityId(l),isLinkIdReserved:l=>this._saveTracker.hasCheckpointLinkId(l),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(l=>l.baseDefault)?.id??null,now:this.coreRuntime.clock?ci(this.coreRuntime.clock()):null});let c=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;c&&c.size>0&&(s=new Map(c)),o.ok||this._rollback(a)}catch(c){throw this._rollback(a),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(o.ok&&n==="record"&&za(o.changes)){let c=Cd(this.coreRuntime.state,o.changes),l=s?new Map(Array.from(s.keys(),d=>[d,this.coreRuntime.state.getProgressFallback(d)])):void 0;this._undo.record(Ya(vd(o.changes),o.__beforeSnap,o.__beforeLinks,c.afterSnap,c.afterLinks,s,l),Sd(t),Date.now())}if(o.ok)if(n==="checkpoint-on-success"){if(t.kind!==P.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let c=this.coreRuntime.state.getAllActivities(),l=this.coreRuntime.state.getAllLinks(),d=t.checkpoint,u=d?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(d?.activities??c,d?.links??l,t.activities,t.links,c,l),this._undo.discardThrough(u),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind===P.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(o.changes.activities,c=>this.coreRuntime.state.getActivity(c)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(o.changes.activities,o.changes.links,c=>this.coreRuntime.state.getActivity(c),c=>this.coreRuntime.state.getLink(c));return o=this._withReappliedViewState(t,o),o.ok?ha(t)&&za(o.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&Te(t)),{result:Tu(o),changedState:!0}):{result:Tu(o),changedState:!1}:{result:o,changedState:!1}}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._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind===P.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!Dc(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._emitTouchedBranchOrder(r??t);return this._reapplyActiveOrder(i.changes??r??t,i.touchedParents)??i.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,i=Ld(t,a=>r.getParentId(a));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:i};if(i.size===0)return{changes:null,touchedParents:i};let n=kn(r,i);return n.length===0?{changes:null,touchedParents:i}:{changes:{...t,order:n},touchedParents:i}}_reapplyActiveOrder(t,r){let i=this.coreRuntime.state;if(i.getActiveOrder()===null)return null;if(i.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:xe(i)};let a=new Set(r);for(let s of t.activities){if(s.kind==="deleted")return{...t,order:xe(i)};let c=i.getParentId(s.id);a.add(c===null?"0":String(c))}let o=kn(i,a);return o.length===0?null:{...t,order:o}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,i=r.getActiveFilter();if(i===null)return null;let n=pe(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),o=GA(a,i,n),s=KA(t)?null:YA(t,r),c,l;if(s===null||!o){let f=Br({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:i,context:n});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=To(a,s,f=>r.getParentId(f)),l=a.visibleIds;let u=Fe(r,l,c);return u.length===0?null:{...t,viewState:[...t.viewState??[],...u]}}_recordScheduleMutation(t){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===Bt.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 rr(Qi(this.coreRuntime.state.getAllActivities().map(s=>et(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==Bt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let s=await pa(i,this.coreRuntime.sector.hoursPerDay,n);return!n()||s===null?null:this._enqueue(async()=>{if(!n())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{for(let[l,d]of s.activities)ua(this.coreRuntime.state,l,d);for(let[l,d]of s.links)fa(this.coreRuntime.state,l,d);c=await K(this.coreRuntime.state,{source:{kind:Gt.INIT},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(l){throw this._rollback(),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:c}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let o=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(o,o),a}undo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runUndo(t,a=>{i=a})}finally{this._settleScheduleMutation(r,i)}});return n.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",o)})},()=>{}),n}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let i=this._undo.takeUndo();if(!i)return null;_d(this.coreRuntime.state,i),this._recordScheduleMutation(!1),r(!0),Ga(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=$a(this.coreRuntime.state,i,"before");return this._saveTracker.recordChanges(n.activities,n.links,a=>this.coreRuntime.state.getActivity(a),a=>this.coreRuntime.state.getLink(a)),this._reapplyViewState(n)??n}}redo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runRedo(a=>{i=a})}finally{this._settleScheduleMutation(r,i)}});return n.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",o)})},()=>{}),n}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;Ed(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Ga(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=$a(this.coreRuntime.state,r,"after");return this._saveTracker.recordChanges(i.activities,i.links,n=>this.coreRuntime.state.getActivity(n),n=>this.coreRuntime.state.getLink(n)),this._reapplyViewState(i)??i}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=Bt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new tn;assertReady(){if(this._status===Bt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Bt.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),t&&(this.coreRuntime.activityIdGenerator.restore(t[0]),this.coreRuntime.linkIdGenerator.restore(t[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(t[2]))}catch(r){throw this._status=Bt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Tu(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}async function Du(e){let t=new ar(e);return await t.ready,t}var _u=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Eu={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 Ru=8;var Pu={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return xu($A);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map