@outbuild-company/schedule-core 1.19.1 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/dist/cdn/schedule-core.global.js +1 -1
- package/dist/cdn/schedule-core.global.js.map +1 -1
- package/dist/index.cjs +17977 -10507
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1115 -424
- package/dist/index.d.ts +1115 -424
- package/dist/index.js +17963 -10508
- package/dist/index.js.map +1 -1
- package/package.json +4 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ScheduleCore=(()=>{var vo=Object.defineProperty;var mf=Object.getOwnPropertyDescriptor;var If=Object.getOwnPropertyNames;var gf=Object.prototype.hasOwnProperty;var Af=(e,t)=>{for(var r in t)vo(e,r,{get:t[r],enumerable:!0})},vf=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of If(t))!gf.call(e,n)&&n!==r&&vo(e,n,{get:()=>t[n],enumerable:!(i=mf(t,n))||i.enumerable});return e};var Cf=e=>vf(vo({},"__esModule",{value:!0}),e);var kC={};Af(kC,{ACTIVITY_BATCH_ACTION_KIND:()=>Ie,ACTIVITY_BATCH_MODE:()=>mt,ACTIVITY_DATE_EDGE:()=>zr,ACTIVITY_FIELD:()=>St,ACTIVITY_PONDERATOR_CRITERION:()=>It,ACTIVITY_PROGRESS_ORIGIN:()=>vn,ACTIVITY_TYPE:()=>D,CALENDAR_UNIT:()=>ft,CHANGE_SET_SOURCE_KIND:()=>ne,COLUMN:()=>E,COMPLETED_PROGRESS:()=>Zr,CONSTRAINT_TYPE:()=>C,CONSTRAINT_TYPE_TO_LABEL:()=>pf,CONSTRAINT_WARNING_KIND:()=>qe,CREATION_KIND:()=>yf,DATE_GESTURE_KIND:()=>Kr,DEFAULT_HOURS_PER_DAY:()=>ff,DISPATCH_ACTION_KIND:()=>h,DISPATCH_ACTION_KINDS:()=>Os,DISPATCH_LINK_OPERATION_KIND:()=>nt,DISPATCH_TRACK_EVENT:()=>Gt,EDIT_ALERT_KEY:()=>qc,EDIT_DENIAL_REASON:()=>ai,ENTITY_CHANGE_KIND:()=>b,FILTER_FIELD:()=>z,FILTER_LOGIC:()=>ur,FILTER_OPERATOR:()=>U,FILTER_REJECTION_REASON:()=>ot,FILTER_VALUE_KIND:()=>L,FLAT_WBS_DEPTH:()=>Oi,GROUP_ID_PREFIX:()=>Do,GROUP_ID_SEPARATOR:()=>pr,LINK_BATCH_OPERATION_KIND:()=>lr,LINK_CODE:()=>_t,LINK_CODE_TO_TYPE:()=>Ye,LINK_REJECTION_REASON:()=>ct,LINK_RELATIONSHIP:()=>Ue,LINK_TYPE:()=>H,LINK_TYPE_CODE:()=>en,MINIMUM_GROUP_DEPTH:()=>Li,MINIMUM_GROUP_LEVEL:()=>Ae,NEW_ACTIVITY_DEFAULTS:()=>Bn,NOT_STARTED_PROGRESS:()=>Ic,ORDER_DIRECTION:()=>Pt,ORDER_MODE:()=>ce,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>V,SCHEDULE_CORE_STATUS:()=>ee,SCHEDULE_EFFECT_KIND:()=>Cn,SIR_AUTO_REJECT_REASON:()=>Sn,STATUS:()=>Rt,STATUS_CRITERIA:()=>me,ScheduleCore:()=>Yr,UNASSIGNED_GROUP_LABEL:()=>Pi,UNASSIGNED_VALUE_ID:()=>Ve,VIEW_ATTRIBUTE_KIND:()=>We,VISUAL_ROW_KIND:()=>fr,WORK_TIME_DIRECTION:()=>Y,appendGroupRowId:()=>bi,buildGroupRowId:()=>Ni,checkNoUpdatedLinks:()=>Sp,computeExpectedProgress:()=>Zo,createSchedule:()=>df,expectedProgressFromBaseline:()=>Rr,getActiveBaseline:()=>Ct,getUnsavedActivities:()=>uf,isRootParent:()=>B,isViewAttributeCriterion:()=>He,isViewAttributeOrderRule:()=>yr,normalizeParentKey:()=>zt,parseFromBackend:()=>uo,willRunCriticalPath:()=>tp,yieldToBrowser:()=>ut});var D={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Sf=Object.values(D);function Gr(e){return Sf.includes(e)}var Si={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},Y={FUTURE:"future",PAST:"past"},ft={HOUR:"hour",DAY:"day"},It={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},me={BASELINE:"Baseline",ACTUAL:"Actual"},Rt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},b={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var C={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Tf={[C.MSO]:()=>!0,[C.MFO]:()=>!0,[C.SNLT]:(e,t)=>e<t,[C.SNET]:(e,t)=>e>t,[C.FNLT]:(e,t)=>e<t,[C.FNET]:(e,t)=>e>t};function Di(e,t,r){if(!t)return{violated:!1};let i=Tf[e];return i?i(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Df=new Set([C.MSO,C.SNET,C.SNLT]);function Me(e,t,r){return Df.has(e)?t:r}function Ei(e,t,r){return{type:Si.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Ef={[C.SNET]:{startOfDay:!0,direction:Y.FUTURE},[C.SNLT]:{startOfDay:!0,direction:Y.PAST},[C.FNET]:{startOfDay:!1,direction:Y.FUTURE},[C.FNLT]:{startOfDay:!1,direction:Y.PAST},[C.MSO]:{startOfDay:!0,direction:Y.FUTURE},[C.MFO]:{startOfDay:!1,direction:Y.PAST}},Ti=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Rs=(e,t)=>new Date(e.getTime()+t*864e5),_f=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function $r(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Ef[e.constraintType];if(!r)return e.constraintDate;let i=e.constraintDate,n=t.getClosestWorkTime({date:Ti(i),dir:Y.FUTURE,task:e});if(_f(n,i))return i.getTime()!==Ti(i).getTime()?i:r.startOfDay?n:t.getClosestWorkTime({date:Rs(Ti(i),1),dir:Y.PAST,task:e});let o=Ti(t.getClosestWorkTime({date:i,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:o,dir:Y.FUTURE,task:e}):t.getClosestWorkTime({date:Rs(o,1),dir:Y.PAST,task:e})}function Ps(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=e.constraintType;if(!i||i===C.ASAP||i===C.ALAP)return r;let n=$r(e,t);if(!n)return r;let o=s=>t.calculateEndDate({startDate:s,durationHours:e.durationHours,task:e}),a=s=>t.calculateEndDate({startDate:s,durationHours:-e.durationHours,task:e});switch(i){case C.SNET:return{earliestStart:n,latestStart:null,earliestEnd:o(n),latestEnd:null};case C.SNLT:return{earliestStart:null,latestStart:n,earliestEnd:null,latestEnd:o(n)};case C.FNET:return{earliestStart:a(n),latestStart:null,earliestEnd:n,latestEnd:null};case C.FNLT:return{earliestStart:null,latestStart:a(n),earliestEnd:null,latestEnd:n};case C.MSO:{let s=o(n);return{earliestStart:n,latestStart:n,earliestEnd:s,latestEnd:s}}case C.MFO:{let s=a(n);return{earliestStart:s,latestStart:s,earliestEnd:n,latestEnd:n}}default:return r}}function Ls(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Co(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var H={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},kf=Object.values(H);function _i(e){return kf.includes(e)}var Rf={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"},Pf={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",BASELINE_VARIANCE:"baseline_variance",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"},E={...Rf,...Pf};var Et={CREATE:"create",UPDATE:"update",DELETE:"delete"},ct={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var h={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_TYPE_SET:"activity-type-set",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_LOOKAHEAD_CONVERT:"activity-lookahead-convert",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",VIEW_ATTRIBUTES_SET:"view-attributes-set",GROUP_SET:"group-set",WBS_DEPTH_SET:"wbs-depth-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},Ie="activity-batch",nt=Et,Os=Object.values(h);function Ct(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var St={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"},zr={START:"start",END:"end"},Ue={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},lr={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var Lf={[St.NAME]:E.TEXT,[St.DESCRIPTION]:E.DESCRIPTION,[St.DURATION_DAYS]:E.DURATION,[St.PROGRESS]:E.PROGRESS,[St.COST]:E.COST,[St.USED_COST]:E.USED_COST,[St.WORK_HOURS]:E.HH_WORK_TIME,[St.START_DATE]:E.START_DATE,[St.END_DATE]:E.END_DATE,[St.CONSTRAINT_TYPE]:E.CONSTRAINT_TYPE,[St.CONSTRAINT_DATE]:E.CONSTRAINT_DATE,[St.CALENDAR_ID]:E.CALENDAR_ID,[St.CUSTOM_ID]:E.CUSTOM_ID,[St.SUBCONTRACT_ID]:E.SUBCONTRACT_ID,[St.RESPONSABLE_IDS]:E.RESPONSABLES,[St.TAG_IDS]:E.TAGS};function So(e,t){return{activityId:e,column:Lf[t.field],newValue:t.value}}var Of={[Ue.FINISH_TO_START]:H.FINISH_TO_START,[Ue.START_TO_START]:H.START_TO_START,[Ue.FINISH_TO_FINISH]:H.FINISH_TO_FINISH,[Ue.START_TO_FINISH]:H.START_TO_FINISH};function qr(e){return Of[e]}function Nf(e){return e.kind===lr.CREATE?{kind:nt.CREATE,source:e.sourceId,target:e.targetId,type:qr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}}:e.kind===lr.UPDATE?{kind:nt.UPDATE,linkId:e.linkId,...e.sourceId===void 0?{}:{source:e.sourceId},...e.targetId===void 0?{}:{target:e.targetId},...e.relationship===void 0?{}:{type:qr(e.relationship)},...e.lagDays===void 0?{}:{lag:e.lagDays}}:e.kind===lr.REMOVE?{kind:nt.DELETE,linkId:e.linkId}:e}function bf(e){return e===zr.START?E.START_DATE:e===zr.END?E.END_DATE:e}function wf(e){return{kind:Ie,mode:e.mode,items:e.items,links:e.links.map(t=>({source:t.source,target:t.target,type:qr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}})),...e.eventSource===void 0?{}:{eventSource:e.eventSource}}}function Ff(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:h.ACTIVITY_CREATE},r),applyBatch:(t,r)=>e.applyActivityBatch(wf(t),r),editInline:(t,r,i)=>e.dispatch({...So(t,r),kind:h.INLINE_EDIT},i),setType:(t,r,i)=>e.dispatch({kind:h.ACTIVITY_TYPE_SET,activityId:t,type:r},i),applyDragBatch:(t,r)=>e.dispatch({kind:h.DATES_BATCH,edits:t.map(i=>({activityId:i.activityId,column:bf(i.edge),newValue:i.value}))},r),editFields:(t,r)=>e.dispatch({kind:h.BULK_EDIT,edits:t.map(i=>So(i.activityId,i))},r),remove:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_DELETE,activityIds:t}),move:(t,r)=>e.dispatch({...t,kind:h.ACTIVITY_MOVE},r),planLookaheadConversion:t=>e.planLookaheadConversion(t),applyLookaheadConversion:t=>e.applyLookaheadConversion(t),indent:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_INDENT,activityIds:t}),outdent:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_OUTDENT,activityIds:t}),setProgress:(t,r,i={})=>e.dispatch({...i,kind:h.ACTIVITY_SET_PROGRESS,activityId:t,newValue:r}),copy:(t={})=>e.dispatch({...t,kind:h.ACTIVITY_COPY}),paste:(t,r={})=>e.dispatch({...r,kind:h.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:t}}),clearClipboard:(t={})=>e.dispatch({...t,kind:h.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:t=>e.dispatch({...t,kind:h.ACTIVITY_LOOKAHEAD_SYNC}),autoSchedule:(t,r)=>e.dispatch({kind:h.SCHEDULE_AUTO_SCHEDULE,...t===void 0?{}:{activityId:t}},r),createDateGesturePreview:t=>e.createDateGesturePreview(t)}}function xf(e){return{get:t=>e.getLinkView(t),list:()=>e.getAllLinksView(),forActivity:t=>e.getLinksForActivityView(t),create:(t,r)=>e.dispatch({kind:h.LINK_CREATE,source:t.sourceId,target:t.targetId,type:qr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}},r),update:(t,r,i)=>e.dispatch({kind:h.LINK_UPDATE,linkId:t,...r.sourceId===void 0?{}:{source:r.sourceId},...r.targetId===void 0?{}:{target:r.targetId},...r.relationship===void 0?{}:{type:qr(r.relationship)},...r.lagDays===void 0?{}:{lag:r.lagDays}},i),remove:(t,r)=>e.dispatch({kind:h.LINK_DELETE,linkId:t},r),batch:(t,r)=>e.dispatch({kind:h.LINKS_BATCH,operations:t.map(Nf)},r)}}function Ns(e){let t=(r,i)=>e.dispatch({kind:h.BASELINE_APPLY,points:r},i);return{activities:Ff(e),links:xf(e),calendars:{get:r=>e.getCalendar(r),list:()=>e.getAllCalendars(),listBase:()=>e.getBaseCalendars(),projectWorkHours:()=>e.getProjectWorkHours(),reconcile:r=>e.dispatch({kind:h.CALENDAR_RECONCILE},r)},selection:{ids:()=>e.getSelectedActivityIds(),toggle:({checked:r,...i})=>e.dispatch({...i,kind:h.SELECTION_TOGGLE,isChecked:r}),replace:(r,i={})=>e.dispatch({...i,kind:h.SELECTION_REPLACE,activityIds:r})},view:{hiddenActivityIds:()=>e.getHiddenActivityIds(),visibleActivityIds:()=>e.getVisibleActivityIds(),visualOrderIds:()=>e.getVisualOrderIds(),visualRows:()=>e.getVisualRows(),filter:()=>e.getActiveFilter(),setFilter:r=>e.dispatch({...r,kind:h.FILTER_SET}),order:()=>e.getActiveOrder(),setOrder:(r,i={})=>e.dispatch({...i,kind:h.SORT_SET,rules:r}),group:()=>e.getActiveGroup(),setViewAttributes:(r,i={})=>e.dispatch({...i,kind:h.VIEW_ATTRIBUTES_SET,catalogs:r}),setGroup:(r,i={})=>e.dispatch({...i,kind:h.GROUP_SET,group:r}),wbsDepth:()=>e.getWbsDepth(),setWbsDepth:(r,i={})=>e.dispatch({...i,kind:h.WBS_DEPTH_SET,wbsDepth:r}),setVisibility:(r,i={})=>e.dispatch({...i,kind:h.VISIBILITY_SET,visibleIds:r}),setStatusCriteria:(r,i)=>e.dispatch({kind:h.STATUS_CRITERIA_SET,criteria:r},i)},baselines:{refresh:t,setVisibility:t,setPonderatorCriterion:(r,i)=>e.dispatch({kind:h.PONDERATOR_CRITERION_SET,criterion:r},i),activeFor:r=>Ct(r)},impactRequests:{sync:r=>e.dispatch({...r,kind:h.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:h.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(),stateRevision:()=>e.getStateRevision(),canonicalDigest:()=>e.getCanonicalDigest()}}}var Bt=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 ki=e=>String(e);function bs(e){let{clickedId:t,isChecked:r,currentSelection:i,hierarchy:n,isFrozen:o,exists:a,autoCheckParents:s}=e,c=ki(t),l=new Set([...i].map(String)),d=new Set(l),u=Mf(c,n).filter(a),p=u.filter(y=>!o(y)),f=r&&p.length<u.length;r&&!f?d.add(c):d.delete(c);for(let y of p)r?d.add(y):d.delete(y);return f||Uf({id:c,isChecked:r,autoCheckParents:s,hierarchy:n,isFrozen:o,exists:a,next:d}),{nextSelection:d,changed:Bf(l,d),parentBlocked:f}}function Mf(e,t){let r=[],i=new Bt;i.enqueue(e);let n=new Set([e]);for(;!i.isEmpty();){let o=i.dequeue();for(let a of t.getChildrenIds(o)){let s=ki(a);n.has(s)||(n.add(s),r.push(s),i.enqueue(s))}}return r}function Uf(e){let{id:t,isChecked:r,autoCheckParents:i,hierarchy:n,isFrozen:o,exists:a,next:s}=e,c=n.getParentId(t);for(;c!==null&&typeof c<"u";){let l=ki(c);if(o(l))return;let d=n.getChildrenIds(l).map(ki).filter(a),u=d.some(o),p=d.filter(m=>!o(m)),y=p.length>0&&p.every(m=>s.has(m))&&!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 Bf(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 dr(e){return(e.pendingRequestIds?.length??0)>0}var S={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",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var ws=(e,t)=>{let r=e.getActivity(t);return r!=null&&dr(r)},Fs=(e,t,r)=>{let i=[],n=(o,a)=>{let s=t.isChecked(o);t.setChecked(o,a)&&i.push({activityId:o,checked:{before:s,after:a}})};for(let o of r.checked)n(o,!0);for(let o of r.unchecked)n(o,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function xs(e,t){let{adapter:r}=t,i=e.activityId;if(!r.getActivity(i))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let n=e.frozenIds?new Set(e.frozenIds):null,o=n?s=>n.has(s):s=>ws(r,s),a=bs({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:o,exists:s=>r.activityExists(s),autoCheckParents:e.autoCheckParents??!1});return{ok:!0,changes:Fs(e,r,a.changed)}}function Ri(e,t){let{adapter:r}=t,i=new Set(e.activityIds.map(String).filter(a=>r.activityExists(a)).filter(a=>!ws(r,a))),n=new Set(r.checkedIds().map(String)),o={checked:[...i].filter(a=>!n.has(a)),unchecked:[...n].filter(a=>!i.has(a))};return{ok:!0,changes:Fs(e,r,o)}}function Be(e,t,r=e.getAllIds()){let i=[];for(let n of r){let o=String(n),a=t.has(o),s=e.isVisible(o);s!==a&&(e.setVisible(o,a),i.push({activityId:o,visible:{before:s,after:a}}))}return i}function Ms(e,t){let{adapter:r}=t,i=new Set(e.visibleIds.map(String)),n=Be(r,i);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}}}var Us={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var We="viewAttribute";var L={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},z={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_VARIANCE_DAYS:"baselineVarianceDays",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"},U={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"};function He(e){return"kind"in e&&e.kind===We}var ur={AND:"and",OR:"or"};var Wf=2,Hf=[Rt.WAITING,Rt.DONE,Rt.DOING,Rt.OVERDUE,Rt.ADVANCEMENT],Vf=[C.MFO,C.MSO,C.SNLT,C.SNET,C.ALAP,C.ASAP,C.FNET,C.FNLT],jf=1e3*60*60*24;function To(e,t){return e===null||t<=0?null:e/t}function Kf(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)/jf)+1}var Yf={[z.NAME]:{valueKind:L.STRING,extract:e=>e.name},[z.DESCRIPTION]:{valueKind:L.STRING,extract:e=>e.description},[z.CUSTOM_ID]:{valueKind:L.STRING,extract:e=>e.customId},[z.CORRELATIVE_ID]:{valueKind:L.NUMBER,extract:e=>e.correlativeId},[z.UNIQUE_CORRELATIVE_ID]:{valueKind:L.NUMBER,extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},[z.PROGRESS]:{valueKind:L.NUMBER,extract:e=>e.progress},[z.DURATION_DAYS]:{valueKind:L.NUMBER,extract:(e,t)=>To(e.durationHours,t.hoursPerDay)},[z.CALENDAR_DURATION]:{valueKind:L.NUMBER,extract:e=>e.type===D.MILESTONE?0:Kf(e.startDate,e.endDate)},[z.COST]:{valueKind:L.NUMBER,extract:e=>e.cost},[z.USED_COST]:{valueKind:L.NUMBER,extract:e=>e.usedCost},[z.REAL_COST]:{valueKind:L.NUMBER,extract:e=>e.realCost},[z.WORK_HOURS]:{valueKind:L.NUMBER,extract:e=>e.workHours},[z.REAL_WORK_HOURS]:{valueKind:L.NUMBER,extract:e=>e.realWorkHours},[z.PONDERATOR]:{valueKind:L.NUMBER,extract:e=>e.ponderator},[z.FREE_SLACK_DAYS]:{valueKind:L.NUMBER,extract:(e,t)=>To(e.freeSlackHours,t.hoursPerDay)},[z.TOTAL_SLACK_DAYS]:{valueKind:L.NUMBER,extract:(e,t)=>To(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},[z.EXPECTED_PROGRESS_BASELINE]:{valueKind:L.NUMBER,equalityPrecision:Wf,extract:e=>e.expectedProgressBaseline},[z.EXPECTED_PROGRESS]:{valueKind:L.NUMBER,extract:e=>e.expectedProgress},[z.BASELINE_DURATION_DAYS]:{valueKind:L.NUMBER,extract:e=>e.baselineSnapshot?.durationDays??null},[z.BASELINE_VARIANCE_DAYS]:{valueKind:L.NUMBER,extract:e=>e.baselineVarianceDays},[z.BASELINE_COST]:{valueKind:L.NUMBER,extract:e=>e.baselineSnapshot?.cost??null},[z.BASELINE_WORK_HOURS]:{valueKind:L.NUMBER,extract:e=>e.baselineSnapshot?.workHours??null},[z.START_DATE]:{valueKind:L.DATE,extract:e=>e.startDate},[z.END_DATE]:{valueKind:L.DATE,extract:e=>e.endDate},[z.CONSTRAINT_DATE]:{valueKind:L.DATE,extract:e=>e.constraintDate},[z.BASELINE_START_DATE]:{valueKind:L.DATE,extract:e=>e.baselineSnapshot?.startDate??null},[z.BASELINE_END_DATE]:{valueKind:L.DATE,extract:e=>e.baselineSnapshot?.endDate??null},[z.EARLY_START]:{valueKind:L.DATE,extract:e=>e.criticalPath?.earlyStart??null},[z.EARLY_FINISH]:{valueKind:L.DATE,extract:e=>e.criticalPath?.earlyFinish??null},[z.LATE_START]:{valueKind:L.DATE,extract:e=>e.criticalPath?.lateStart??null},[z.LATE_FINISH]:{valueKind:L.DATE,extract:e=>e.criticalPath?.lateFinish??null},[z.RESPONSABLE_IDS]:{valueKind:L.ID_ARRAY,extract:e=>e.responsableIds},[z.TAG_IDS]:{valueKind:L.ID_ARRAY,extract:e=>e.tagIds},[z.STATUS]:{valueKind:L.ENUM,order:Hf,extract:e=>e.status},[z.CONSTRAINT_TYPE]:{valueKind:L.ENUM,order:Vf,extract:e=>e.constraintType},[z.CALENDAR_ID]:{valueKind:L.REFERENCE,extract:e=>e.calendarId===null?null:String(e.calendarId)},[z.SUBCONTRACT_ID]:{valueKind:L.REFERENCE,extract:e=>e.subcontractId===null?null:String(e.subcontractId)},[z.IS_CRITICAL]:{valueKind:L.BOOLEAN,extract:e=>e.isCritical}};function ge(e){return Yf[e]??null}var fr={GROUP:"group",ACTIVITY:"activity"},Ve="unassigned",Do="g",pr=":",Pi="Unassigned",Li=1,Ae=1,Oi=0;function Ni(e,t){return`${Do}${pr}${e}${pr}${t}`}function bi(e,t,r){return`${e}${pr}${t}${pr}${r}`}var Ws=null;function Bs(e){return e===Ws?"":e}function Hs(e){let t=new Map,r=new Map;for(let c of e.values){t.set(c.id,c);let l=Bs(c.parentId),d=r.get(l)??[];d.push(c),r.set(l,d)}for(let c of r.values())c.sort((l,d)=>l.sequence!==d.sequence?l.sequence-d.sequence:l.id.localeCompare(d.id));let i=new Map,n=new Map,o=(c,l,d)=>{let u=r.get(Bs(c))??[];for(let p of u){let f=[...l,p.id],y=[...d,p.sequence];i.set(p.id,f),n.set(p.id,y),o(p.id,f,y)}};o(Ws,[],[]);let a=new Map;for(let c of t.keys()){let l=new Set([c]);for(let[d,u]of i)u.includes(c)&&l.add(d);a.set(c,l)}let s=new Map;for(let c of e.assignments)t.has(c.valueId)&&s.set(String(c.activityId),c.valueId);return{key:e.key,valueById:t,pathByValueId:i,sequencePathByValueId:n,descendantIdsByValueId:a,assignmentByActivityId:s}}var wi=new Map;function Vs(e,t){let r=new Set;for(let i of t){let n=e.descendantIdsByValueId.get(i);if(n===void 0){r.add(i);continue}for(let o of n)r.add(o)}return r}function js(e,t,r,i){let n=Math.max(r,Ae),o=e.pathByValueId.get(t);return o===void 0||o.length===0?n>Ae?[]:[t]:o.slice(n-1,Math.max(i,n))}function Ks(e,t,r){let i=r.get(t.key),n=i?.assignmentByActivityId.get(String(e.id))??null,o=i?Vs(i,t.value):new Set(t.value),a=n!==null&&o.has(n);return t.operator===U.SOME_OF?a:t.operator===U.NOT_SOME_OF?!a:!1}function Eo(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function se(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function Gf(e,t,r){let i=e===null;return r===U.INCLUDES?!i&&String(e).toLowerCase().includes(t.toLowerCase()):r===U.NOT_INCLUDES?i||!String(e).toLowerCase().includes(t.toLowerCase()):r===U.IS?!i&&String(e)===t:r===U.IS_NOT?i||String(e)!==t:!1}function $f(e,t,r,i){if(e===null||typeof e!="number")return r===U.NOT_EQUALS;let n=i===void 0?e:Number(e.toFixed(i));return r===U.EQUALS?n===t:r===U.NOT_EQUALS?n!==t:r===U.GREATER_THAN?e>t:r===U.LESS_THAN?e<t:r===U.GREATER_OR_EQUAL?e>=t:r===U.LESS_OR_EQUAL?e<=t:!1}function zf(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function qf(e,t,r){if(!(e instanceof Date))return!1;let i=se(e),n=se(t);return r===U.AFTER?i>n:r===U.BEFORE?i<n:!1}function Jf(e,t,r){if(!(e instanceof Date))return!1;let i=se(e);return i>=se(t)&&i<=se(r)}function Xf(e,t,r){let n=(Array.isArray(e)?e:[]).some(o=>t.has(String(o)));return r===U.SOME_OF?n:r===U.NOT_SOME_OF?!n:!1}function Zf(e,t,r){let i=e!==null&&t.has(String(e));return r===U.SOME_OF?i:r===U.NOT_SOME_OF?!i:!1}function Ys(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function xi(e){return e.viewAttributeCatalogs??wi}function Fi(e,t,r,i){if(He(t))return Ks(e,t,i);let n=ge(t.field);if(n===null)return!1;let o=n.extract(e,r),{operator:a}=t;return a===U.BETWEEN?n.valueKind===L.NUMBER?zf(o,Number(t.value),Number(t.valueTo)):n.valueKind===L.DATE?Jf(o,Eo(t.value),Eo(t.valueTo)):!1:n.valueKind===L.STRING?Gf(o,String(t.value),a):n.valueKind===L.NUMBER?$f(o,Number(t.value),a,n.equalityPrecision):n.valueKind===L.DATE?qf(o,Eo(t.value),a):n.valueKind===L.ID_ARRAY?Xf(o,Ys(t.value),a):Zf(o,Ys(t.value),a)}function Gs(e,t,r,i){return t.criteria.length===0?!0:t.logic===ur.OR?t.criteria.some(n=>Fi(e,n,r,i)):t.criteria.every(n=>Fi(e,n,r,i))}function Qf(e,t,r,i){return t.groups&&t.groups.length>0?t.logic===ur.OR?t.groups.some(n=>Gs(e,n,r,i)):t.groups.every(n=>Gs(e,n,r,i)):t.criteria.length===0?!0:t.logic===ur.OR?t.criteria.some(n=>Fi(e,n,r,i)):t.criteria.every(n=>Fi(e,n,r,i))}function ty(e,t){let r=se(e.startDate),i=se(e.endDate),n=se(t.start),o=se(t.end),a=r>=n&&i<=o,s=r>=n&&r<=o,c=n>=r&&n<=i;return a||s||c}function _o(e,t,r,i){let n=Qf(e,t,r,i),o=t.dateRange,a=o===void 0||ty(e,o);return n&&a}function ey(e,t,r){let i=t(e);for(;i!==null&&!r.has(String(i));)r.add(String(i)),i=t(i)}function $s(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=xi(e),a=new Set,s=[];for(let c of t)_o(c,i,n,o)&&(a.add(String(c.id)),s.push(c.id));for(let c of s)ey(c,r,a);return a}function ry(e){let{activities:t,parentOf:r,filter:i,context:n}=e,o=xi(e),a=new Set,s=new Map,c=new Map,l=new Map;for(let d of t){let u=String(d.id),p=r(u);c.set(u,p),l.set(u,l.get(u)??0),p!==null&&l.set(p,(l.get(p)??0)+1);let f=_o(d,i,n,o);s.set(u,f?1:0),f&&a.add(u)}return{matchedIds:a,visibleReferenceCounts:s,parentIds:c,remainingChildren:l}}function iy(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:i}=e,n=[];for(let o of r.keys())i.get(o)===0&&n.push(o);for(;n.length>0;){let o=n.pop();if(o===void 0)break;let a=r.get(o);if(a==null)continue;let s=t.get(o)??0;t.set(a,(t.get(a)??0)+s);let c=(i.get(a)??1)-1;i.set(a,c),c===0&&n.push(a)}}function ny(e){let t=new Set;for(let[r,i]of e)i>0&&t.add(r);return t}function Mi(e){let t=ry(e);iy(t);let r=ny(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts,viewAttributeCatalogs:xi(e)}}function zs(e,t,r){let i=new Set;for(let n of t){let o=String(n.id);i.add(o);let a=e.matchedIds.has(o),s=_o(n,e.filter,e.context,xi(e));if(a===s)continue;s?e.matchedIds.add(o):e.matchedIds.delete(o);let c=s?1:-1,l=o;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let p=d>0,f=u>0;p!==f&&(i.add(l),f?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return i}function je(e){return{hoursPerDay:e,locale:"en"}}var ot={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},oy={[L.STRING]:new Set([U.INCLUDES,U.NOT_INCLUDES,U.IS,U.IS_NOT]),[L.NUMBER]:new Set([U.EQUALS,U.NOT_EQUALS,U.GREATER_THAN,U.LESS_THAN,U.GREATER_OR_EQUAL,U.LESS_OR_EQUAL,U.BETWEEN]),[L.DATE]:new Set([U.AFTER,U.BEFORE,U.BETWEEN]),[L.ID_ARRAY]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[L.ENUM]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[L.BOOLEAN]:new Set([U.SOME_OF,U.NOT_SOME_OF]),[L.REFERENCE]:new Set([U.SOME_OF,U.NOT_SOME_OF])};function qs(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:ot.INVALID_VALUE};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:ot.INVALID_VALUE};let i=t.getTime(),n=r.getTime();return!Number.isFinite(i)||!Number.isFinite(n)||i>n?{ok:!1,reason:ot.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(n)}}}function Po(e){if(He(e))return sy(e);let t=ge(e.field);if(t===null)return{ok:!1,reason:ot.UNKNOWN_FIELD};if(!oy[t.valueKind].has(e.operator))return{ok:!1,reason:ot.UNKNOWN_OPERATOR};if(e.operator===U.BETWEEN)return ay(e,t.valueKind);if(t.valueKind===L.NUMBER){let i=ko(e.value);return i===null?{ok:!1,reason:ot.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}if(t.valueKind===L.DATE){let i=Ro(e.value);return i===null?{ok:!1,reason:ot.INVALID_VALUE}:{ok:!0,criterion:{...e,value:i}}}let r=cy(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind===L.BOOLEAN?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind===L.ID_ARRAY||t.valueKind===L.ENUM||t.valueKind===L.REFERENCE?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function ay(e,t){if(t===L.NUMBER){let r=ko(e.value),i=ko(e.valueTo);return r===null||i===null||r>i?{ok:!1,reason:ot.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}if(t===L.DATE){let r=Ro(e.value),i=Ro(e.valueTo);return r===null||i===null||r.getTime()>i.getTime()?{ok:!1,reason:ot.INVALID_VALUE}:{ok:!0,criterion:{...e,value:r,valueTo:i}}}return{ok:!1,reason:ot.UNKNOWN_OPERATOR}}function sy(e){return He(e)?typeof e.key!="string"||e.key.length===0?{ok:!1,reason:ot.UNKNOWN_FIELD}:e.operator!==U.SOME_OF&&e.operator!==U.NOT_SOME_OF?{ok:!1,reason:ot.UNKNOWN_OPERATOR}:!Array.isArray(e.value)||e.value.some(t=>typeof t!="string")?{ok:!1,reason:ot.INVALID_VALUE}:{ok:!0,criterion:e}:{ok:!1,reason:ot.UNKNOWN_FIELD}}function cy(e,t){let{value:r}=e;return t===L.BOOLEAN?Array.isArray(r)&&r.every(i=>typeof i=="boolean")?null:ot.INVALID_VALUE:t===L.ID_ARRAY||t===L.ENUM||t===L.REFERENCE?Array.isArray(r)&&r.every(i=>typeof i=="string"||typeof i=="number")?null:ot.INVALID_VALUE:Array.isArray(r)?ot.INVALID_VALUE:null}function ko(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 Ro(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 F(e){return structuredClone(e)}function Js(e){return!(e.groups!==void 0&&e.groups.some(r=>r.criteria.length>0))&&e.criteria.length===0&&e.dateRange===void 0}function Xs(e,t,r){let i=e.getAllActivities();if(Js(t))return{visibleIds:$s({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:je(r),viewAttributeCatalogs:e.getViewAttributeCatalogMap()}),projection:null};let n=Mi({activities:i,parentOf:o=>e.getParentId(o),filter:t,context:je(r),viewAttributeCatalogs:e.getViewAttributeCatalogMap()});return{visibleIds:n.visibleIds,projection:n}}function ly(e){if(!e||e.length===0)return{ok:!0,groups:[]};let t=[];for(let r of e){let i=[];for(let n of r.criteria){let o=Po(n);if(!o.ok)return{ok:!1,reason:o.reason};i.push(o.criterion)}t.push({criteria:i,logic:r.logic})}return{ok:!0,groups:t}}function Zs(e,t){let{adapter:r,hoursPerDay:i}=t,n=[];for(let p of e.criteria){let f=Po(p);if(!f.ok)return{ok:!1,reason:f.reason};n.push(f.criterion)}let o=ly(e.groups);if(!o.ok)return{ok:!1,reason:o.reason};let a=qs(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=F({criteria:n,logic:e.logic,...o.groups.length>0?{groups:o.groups}:{},...a.dateRange!==void 0?{dateRange:a.dateRange}:{}});r.setActiveFilter(Js(s)?null:s);let{visibleIds:c,projection:l}=Xs(r,s,i);r.setFilterProjection(l);let d=Be(r,c);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:d}}}function Qs(e,t){let r=e.getActiveFilter();if(r===null)return[];let{visibleIds:i,projection:n}=Xs(e,r,t);return e.setFilterProjection(n),Be(e,i)}var Pt={ASCENDING:"asc",DESCENDING:"desc"};function yr(e){return"kind"in e&&e.kind===We&&"key"in e&&"direction"in e&&!("operator"in e)}var ce={STANDARD:"standard",KEEP_WBS_IN_PLACE:"keepWbsInPlace"};var V="0";function B(e){return e==null||e===0||e==="0"}function zt(e){return B(e)?"0":String(e)}var Lo=Number.MAX_SAFE_INTEGER;function jt(e,t){let r=Jr(e,t);return Ui(r,t.getOrderComparator?.()??null,t.getOrderMode?.()??ce.STANDARD,n=>t.hasChildren(n)).map(n=>String(n.id))}function Ui(e,t,r,i){return t===null?(e.sort(hr),e):r===ce.KEEP_WBS_IN_PLACE?dy(e,t,i):(e.sort((n,o)=>t(n,o)||hr(n,o)),e)}function dy(e,t,r){let i=[],n=[];for(let o of e)r(o.id)?n.push(o):i.push(o);return i.sort((o,a)=>t(o,a)||hr(o,a)),n.sort(hr),e.length=0,e.push(...i,...n),e}function ec(e){let t=[],r=n=>{t.push(n);let o=jt(String(n.id),e);for(let a of o){let s=e.getActivity(a);s&&r(s)}},i=jt("0",e);for(let n of i){let o=e.getActivity(n);o&&r(o)}return t}function rc(e,t,r){let i=r.getActivity(e);if(!i)return null;let n=ic(i),o=jt(n,r),a=o.findIndex(s=>String(s)===String(e));if(a<=0)return null;for(let s=a-1;s>=0;s--){let c=o[s];if(c!==void 0&&!uy(t,c))return c}return null}function Oo(e,t){let r=t.getActivity(e);if(!r)return-1;let i=ic(r);return jt(i,t).findIndex(o=>String(o)===String(e))}function Jr(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),i=[];for(let n of r){let o=t.getActivity(n);o&&i.push(o)}return i}function hr(e,t){let r=tc(e),i=tc(t);return r!==i?r-i:String(e.id).localeCompare(String(t.id))}function tc(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Lo}function ic(e){let t=e.parentId;return t===null?"0":t}function uy(e,t){return e.has(t)?!0:e.has(String(t))}function ve(e){let t=[],r=i=>{let n=jt(i,e);n.length>1&&t.push({parentId:i,childIds:n});for(let o of n)r(o)};return r("0"),t}function No(e,t){let r=[];for(let i of t){let n=jt(i,e);n.length>1&&r.push({parentId:i,childIds:n})}return r}function py(e){return yr(e)?typeof e.key!="string"||e.key.length===0?ot.UNKNOWN_FIELD:e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING?ot.UNKNOWN_OPERATOR:null:ge(e.field)===null?ot.UNKNOWN_FIELD:e.direction!==Pt.ASCENDING&&e.direction!==Pt.DESCENDING?ot.UNKNOWN_OPERATOR:null}function nc(e,t){let{adapter:r}=t;for(let a of e.rules){let s=py(a);if(s!==null)return{ok:!1,reason:s}}let i=e.mode??ce.STANDARD,n=e.rules.length===0?null:F({rules:e.rules,mode:i});return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:ve(r)}}}function bo(e){return Number.isInteger(e)&&Number.isFinite(e)}function oc(e){return e===Pt.ASCENDING||e===Pt.DESCENDING}function ac(e){let t=e.startLevel??Ae;return!bo(t)||t<Ae||!bo(e.depth)||e.depth<Li||e.depth<t?null:{startLevel:t,depth:e.depth}}var mr=Symbol("invalid-group-criterion");function fy(e){let t=e.secondary;if(t==null)return null;if(typeof t!="object"||typeof t.attributeKey!="string"||t.attributeKey.length===0||t.attributeKey===e.attributeKey)return mr;let r=ac(t);return r===null||!oc(t.direction)?mr:{attributeKey:t.attributeKey,startLevel:r.startLevel,depth:r.depth,direction:t.direction}}function yy(e){if(typeof e.attributeKey!="string"||e.attributeKey.length===0)return null;let t=ac(e);if(t===null||!oc(e.direction)||typeof e.includeWbs!="boolean"||!Array.isArray(e.collapsedIds)||e.collapsedIds.some(i=>typeof i!="string"))return null;let r=fy(e);return r===mr?null:{attributeKey:e.attributeKey,startLevel:t.startLevel,depth:t.depth,direction:e.direction,includeWbs:e.includeWbs,collapsedIds:new Set(e.collapsedIds),secondary:r}}function Bi(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function sc(e,t){let{adapter:r,hoursPerDay:i}=t;if(!Array.isArray(e.catalogs))return{ok:!1,reason:ot.INVALID_VALUE};r.setViewAttributeCatalogs(e.catalogs);let n=Qs(r,i),o=r.getActiveOrder();return{ok:!0,changes:{...Bi(e),viewState:n,...o===null?{}:{order:ve(r)}}}}function cc(e,t){let{adapter:r}=t;if(e.group===null)return r.setGroup(null),{ok:!0,changes:Bi(e)};let i=yy(e.group);return i===null?{ok:!1,reason:ot.INVALID_VALUE}:(r.setGroup(i),{ok:!0,changes:Bi(e)})}function lc(e,t){let{adapter:r}=t,{wbsDepth:i}=e;return i!==null&&(!bo(i)||i<Oi)?{ok:!1,reason:ot.INVALID_VALUE}:(r.setWbsDepth(i),{ok:!0,changes:Bi(e)})}function dc(e,t){throw new Error(t)}var wo={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},Fo={[D.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:wo.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[D.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:wo.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[D.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:wo.ZERO,promotesToProjectOnFirstChild:!0}};function qt(e,t){return t||Gr(e)&&Fo[e].alwaysSummary}function le(e){return e===D.MILESTONE}function Ce(e){return Gr(e)&&Fo[e].promotesToProjectOnFirstChild}var xo=D.PROJECT,Ir=D.TASK;function Xr(e,t){return t===0?D.MILESTONE:e===0&&t>0?D.TASK:null}var w={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",BASELINE_VARIANCE_DAYS:"baselineVarianceDays",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},xt={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 uc(e,t){return()=>t()===e}var Mo=typeof window>"u",hy=!Mo&&typeof MessageChannel<"u";function ut(){return hy?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 Wi(e,t){return performance.now()-e<Us.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await ut(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function gr(e){return Mo||await ut(),e()?{aborted:!1}:{aborted:!0}}function Hi(e,t){let{inDegree:r,successors:i}=my(e,t),n=Iy(r),o=gy(n,r,i),a=o.length<e.length,s=a?Ay(e,o):[],c=[...o].reverse();return{ordered:o,reversed:c,hasCycles:a,cycleNodes:s}}function my(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 o=n.source,a=n.target;!r.has(o)||!r.has(a)||(i.get(o).push(a),r.set(a,(r.get(a)??0)+1))}return{inDegree:r,successors:i}}function Iy(e){let t=new Bt;for(let[r,i]of e)i===0&&t.enqueue(r);return t}function gy(e,t,r){let i=[];for(;!e.isEmpty();){let n=e.dequeue();i.push(n);for(let o of r.get(n)??[]){let a=(t.get(o)??1)-1;t.set(o,a),a===0&&e.enqueue(o)}}return i}function Ay(e,t){let r=new Set(t);return e.filter(i=>!r.has(i))}var Vi=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Hi(t,r),this.cached)}};function pc(e,t){let r=[];for(let i of e)t.has(i)&&r.push(i);return r}function ji(e,t){let r=t.getActivity(e);return r?qt(r.type,t.getChildren(e).length>0):!1}function Ki(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 Gi(e,t,r){let i=ji(e,r);return ji(t,r)&&Ki(e,t,r)||i&&Ki(t,e,r)}function hc(e,t){let r=[],i=[e];for(;i.length>0;){let n=i.pop(),o=t.getChildren(n);if(o.length===0){String(n)!==String(e)&&r.push(n);continue}for(let a of o)i.push(a)}return r}function vy(e){let t=new Map;for(let r of e)fc(t,String(r.source),r),fc(t,String(r.target),r);return t}function fc(e,t,r){let i=e.get(t);if(i){i.push(r);return}e.set(t,[r])}function Cy(e,t,r,i){if(e.length<=1)return e;let n=new Set(e.map(String)),o=[];for(let a of e)Sy(a,n,t,r,i)||o.push(a);return o.length>0?o:e}function Sy(e,t,r,i,n){let o=String(e),a=r.getActivity(e);if(!a||a.autoScheduling===!1)return!1;let s=i.get(o)??[];for(let c of s)if(Ty(c,o,a,t,r,n))return!0;return!1}function Ty(e,t,r,i,n,o){if(Dy(e)||!(o?String(e.source)===t:String(e.target)===t))return!1;let s=Ey(e,t);if(!i.has(String(s)))return!1;let c=n.getActivity(s);return!!(c?.autoScheduling!==!1&&c&&_y(e,r,c))}function Dy(e){return e.source===e.target}function Ey(e,t){return String(e.source)===t?e.target:e.source}function _y(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 $i(e,t){let r=[],i=vy(e),n=0;for(let o of e){let a=ji(o.source,t),s=ji(o.target,t);if(ky(o,a,s,t))continue;if(!a&&!s){r.push(o);continue}let c=yc(o.source,a,t,i,!0),l=yc(o.target,s,t,i,!1);n=wy(r,c,l,o,t,n,i)}return r}function ky(e,t,r,i){return r&&Ki(e.source,e.target,i)||t&&Ki(e.target,e.source,i)}function yc(e,t,r,i,n){return t?Cy(hc(e,r),r,i,n):[e]}function Ry(e,t,r){let i=hc(e,t);if(i.length===0)return null;let n=null,o=null;for(let a of i){let s=r(a);if(!s)continue;(n===null||s.startDate<n)&&(n=s.startDate),(o===null||s.endDate>o)&&(o=s.endDate)}return n===null||o===null?null:{startDate:n,endDate:o}}function Yi(e,t){return Ry(e,t,r=>{let i=t.getActivity(r);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function Py(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Ly(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 Oy(e,t){let r=String(e);return(t.get(r)??[]).some(n=>String(n.target)===r)}function Ny(e,t,r,i,n){if(Oy(e,n))return 0;let o=i.getActivity(e);return!t||!o||!r?0:i.calculateDuration({startDate:t,endDate:o.startDate,task:r})}function by(e,t){let r=t.getActivity(e.source),i=t.getActivity(e.target),n=Yi(e.source,t),o=Yi(e.target,t),a=e.type===H.START_TO_START||e.type===H.START_TO_FINISH,s=e.type===H.FINISH_TO_FINISH||e.type===H.START_TO_FINISH;return{source:r,sourceBounds:n,targetStart:o?.startDate??i?.startDate,userLag:e.lag??0,sourceEndpointIsStart:a,targetLag:s?-Py(i,o,t):0,summarySourceId:e.type===H.START_TO_START&&n?e.source:void 0,finishAnchoredSummaryTargetId:s&&o?e.target:void 0}}function wy(e,t,r,i,n,o,a){let s=by(i,n),{source:c,sourceBounds:l,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:p,targetLag:f,summarySourceId:y,finishAnchoredSummaryTargetId:m}=s,g=o;for(let _ of t){let k=p?Ly(_,c,l,n):0;for(let O of r){if(String(_)===String(O))continue;let T=Ny(O,d,c,n,a);e.push(Fy(i,_,O,g,k,f,u+T,y,m??(T!==0&&f===0?i.target:void 0))),g+=1}}return g}function Fy(e,t,r,i,n,o,a,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:o,_trueLag:a,...s===void 0?{}:{_summarySourceId:s},...c===void 0?{}:{_summaryTargetId:c}}}var zi=class{invalidate(){}get(t,r){return $i(t,r)}};function xy(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 My(e,t,r){let i=new Set,n=new Map,o=new Bt;for(o.enqueue(e);!o.isEmpty();){let a=o.dequeue(),s=String(a);if(i.has(s))continue;i.add(s);let c=r.neighbors.get(a);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 p=String(d.source)===s?d.target:d.source;i.has(String(p))||o.enqueue(p)}}return Array.from(n.values())}function mc(e,t){let r=new Map;for(let a of t)r.set(a.id,a);let i=xy(t),n=My(e,r,i),o=new Set([String(e)]);for(let a of n)o.add(String(a.source)),o.add(String(a.target));return{activityIds:o,links:n}}var Ic=0,Zr=100;function Ke(e){return e===0}function gc(e,t,r){let i=r.type===H.FINISH_TO_START,n=r.type===H.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 o=r.lag??0;switch(r.type){case H.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case H.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case H.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};case H.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:o,isFS:i,isFF:n,isZeroDurationCase:!1}}}function Uy(e,t,r){if(e._summarySourceId===void 0)return null;let i=r.getActivity(e._summarySourceId);if(!i)return null;let n=Yi(e._summarySourceId,r);return n?-r.calculateDuration({startDate:n.startDate,endDate:t.endDate,task:i}):null}function By(e,t,r,i,n){let o=t.durationHours===0&&n;return{successorStart:i.getClosestWorkTime({date:e.endDate,dir:o?"past":"future",task:t}),link:r}}function Ac(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a,isFS:s,isFF:c}=gc(e,t,r),l=Uy(r,e,i)??n,d=l+o+a;if(!(t.durationHours===0?d!==0:l!==0||o!==0||a!==0))return By(e,t,r,i,s||c);let f=s?t:e,y=i.getClosestWorkTime({date:e.endDate,dir:"future",task:f});if(l!==0&&(y=i.calculateEndDate({startDate:y,durationHours:l,task:e})),o!==0&&(y=i.calculateEndDate({startDate:y,durationHours:o,task:t})),a!==0&&(y=i.calculateEndDate({startDate:y,durationHours:a,task:t})),t.durationHours===0){if(s||c)return{successorStart:i.getClosestWorkTime({date:y,dir:"past",task:t}),link:r};let m=new Date(Date.UTC(y.getUTCFullYear(),y.getUTCMonth(),y.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}return{successorStart:i.getClosestWorkTime({date:y,dir:"future",task:t}),link:r}}function vc(e,t,r,i){let{sourceLag:n,targetLag:o,trueLag:a}=gc(t,e,r),s=i.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return a!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-a,task:e})),o!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-o,task:e})),n!==0&&(s=i.calculateEndDate({startDate:s,durationHours:-n,task:t})),s}function Cc(e,t,r){for(let i of e){let n=t.getActivity(i);if(!n)continue;let o=n.constraintType;if(!o||o===C.ASAP||o===C.ALAP)continue;let a=Ps(n,t);!a.earliestStart&&!a.latestStart&&!a.earliestEnd&&!a.latestEnd||r.set(i,{activityId:i,startDate:n.startDate,endDate:n.endDate,drivingLinkId:null,kind:C.ASAP,conflict:!1,earliestStart:a.earliestStart,latestStart:a.latestStart,earliestEnd:a.earliestEnd,latestEnd:a.latestEnd})}}function qi(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,o;n===null?o=Co(e.startDate,i):Ls(n,i)?o=n:o=Co(n,i),t.startDate=o,t.endDate=r.calculateEndDate({startDate:o,durationHours:e.durationHours,task:e})}function Sc(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:i}=e;if(!r||!i)return t;switch(r){case C.MSO:case C.MFO:return new Date(i);case C.SNET:case C.FNET:return i>t?new Date(i):t;case C.SNLT:case C.FNLT:return i<t?new Date(i):t;default:return t}}function Wy(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Tc(e,t,r){return Uo(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Uo(e,t,r){return t.dragWithMultiple&&Wy(e,r)}async function Dc(e,t,r,i,n,o){let a=new Map;for(let u of t){let p=String(u.target);a.has(p)||a.set(p,[]),a.get(p).push(u)}let s=u=>{let p=o.get(u);if(p?.startDate&&p.endDate)return{startDate:p.startDate,endDate:p.endDate};let f=r.getActivity(u);return f?{startDate:f.startDate,endDate:f.endDate}:{startDate:new Date,endDate:new Date}},c=r.getFlags(),l=i.draggedIds??[],d=performance.now();for(let u of e){let p=await Wi(d,n);if(p.aborted)return o;d=p.newSliceStart;let f=r.getActivity(u);if(!f||!f.autoScheduling||f.progress===100||Hy(f,r))continue;let y=a.get(String(u))??[],m=null,g=null,_=!1;for(let M of y){let A=r.getActivity(M.source);if(!A)continue;let v=s(M.source),N=v.startDate.getTime()!==A.startDate.getTime()||v.endDate.getTime()!==A.endDate.getTime(),j={...A,startDate:v.startDate,endDate:v.endDate},K=Tc(j,c,l),Z={...j,startDate:K.startDate,endDate:K.endDate},st=Uo(M.source,c,l)?{...M,lag:0}:M,lt=Ac(Z,f,st,r);(!m||lt.successorStart>m)&&(m=lt.successorStart,g=String(M.id),_=M._summaryTargetId!==void 0&&!N&&(M._targetLag===0||i.preventSummaryTargetPullback===!0))}m!==null&&_&&m<f.startDate&&(m=new Date(f.startDate));let O=o.get(u),T=O?{...O}:{activityId:u,startDate:f.startDate,endDate:f.endDate,drivingLinkId:null,kind:C.ASAP,conflict:!1},P=T.earliestStart||T.latestStart||T.earliestEnd||T.latestEnd;if(!(!m&&!P)){if(m){let M=m;f.type===D.MILESTONE&&(M=Sc(f,m)),T.drivingLinkId=g,T.startDate=M,T.endDate=r.calculateEndDate({startDate:M,durationHours:f.durationHours,task:f}),T.earliestSchedulingStart=M,T.earliestSchedulingEnd=T.endDate}else f.constraintType===C.MSO?T.earliestStart&&(T.startDate=T.earliestStart,T.endDate=T.earliestEnd??r.calculateEndDate({startDate:T.earliestStart,durationHours:f.durationHours,task:f})):f.constraintType===C.MFO&&T.latestStart&&(T.startDate=T.latestStart,T.endDate=T.latestEnd??r.calculateEndDate({startDate:T.latestStart,durationHours:f.durationHours,task:f}));qi(f,T,r),o.set(u,T)}}return o}function Hy(e,t){return qt(e.type,t.getChildren(e.id).length>0)}async function Ec(e,t,r,i,n,o){let a=new Map(r),s=i.getAllActivities(),c=s.length,l=[];for(let g of s)g.constraintType===C.ALAP&&l.push(g.id);if(l.length===0)return a;let d=new Map,u=new Map;for(let g of t){let _=String(g.source);d.has(_)||d.set(_,[]),d.get(_).push(g);let k=String(g.target);u.has(k)||u.set(k,[]),u.get(k).push(g)}let p=g=>{let _=a.get(g);if(_)return{startDate:_.startDate,endDate:_.endDate};let k=i.getActivity(g);return k?{startDate:k.startDate,endDate:k.endDate}:{startDate:new Date,endDate:new Date}},f=g=>!g.parentId||B(g.parentId)?i.getProjectEnd():p(g.parentId).endDate,y=(g,_)=>{let k=g,O=0;for(;k&&!B(k)&&O++<c+1;){if(String(k)===String(_))return!0;let T=i.getActivity(k);if(!T||!T.parentId)break;k=T.parentId}return!1},m=performance.now();for(let g of e){let _=await Wi(m,o);if(_.aborted)return a;m=_.newSliceStart;let k=i.getActivity(g);if(!k||k.constraintType!==C.ALAP||!k.autoScheduling||k.progress===100||qt(k.type,i.getChildren(g).length>0))continue;let O=f(k),T=O,P=null,M=null,A=!1,v=d.get(String(g))??[];for(let Vt of v){if((Vt.lag??0)<0)continue;let cr=i.getActivity(Vt.target);if(!cr||cr.autoScheduling===!1)continue;let ks=p(Vt.target),hf={...cr,startDate:ks.startDate,endDate:ks.endDate},Ci=vc(hf,k,Vt,i);(T===null||Ci<T)&&(T=Ci),(P===null||Ci<P)&&(P=Ci,M=Vt.type,A=k.parentId&&!B(k.parentId)?y(Vt.target,k.parentId):!1)}if(P!==null)if(A||O===null)T=P;else{let Vt=p(g).endDate,cr=Vt.getTime()>O.getTime()?Vt:O;T=P<cr?P:cr}else{if(O===null||T===null)continue;T>O&&(T=O)}if(T===null)continue;let j=(u.get(String(g))??[]).some(Vt=>Vt.type===H.FINISH_TO_START||Vt.type===H.FINISH_TO_FINISH),K=new Date(Date.UTC(T.getUTCFullYear(),T.getUTCMonth(),T.getUTCDate())),Z=()=>i.getClosestWorkTime({date:K,dir:"past",task:k}),st=i.getClosestWorkTime({date:T,dir:"future",task:k}).getTime()===T.getTime(),lt;k.durationHours===0&&P===null?lt=j&&st?Z():i.getClosestWorkTime({date:T,dir:"past",task:k}):k.durationHours===0?P!==null&&M===H.FINISH_TO_START&&T.getTime()===P.getTime()?lt=T:j?lt=Z():lt=i.getClosestWorkTime({date:T,dir:"future",task:k}):lt=i.getClosestWorkTime({date:T,dir:"future",task:k});let dt=i.calculateEndDate({startDate:lt,durationHours:-k.durationHours,task:k}),re=a.get(g),Ft=re?{...re}:{activityId:g,startDate:dt,endDate:lt,drivingLinkId:null,kind:C.ALAP,conflict:!1};Ft.startDate=dt,Ft.endDate=lt,Ft.drivingLinkId=null,Ft.kind=C.ALAP;let sr=Ft.earliestSchedulingStart??null;Ft.earliestSchedulingStart=null,Ft.earliestSchedulingEnd=null;let Ao=sr!==null&&sr.getTime()>dt.getTime()?sr:dt;Ft.latestSchedulingStart=Ao,Ft.latestSchedulingEnd=Ao===dt?lt:i.calculateEndDate({startDate:Ao,durationHours:k.durationHours,task:k}),qi(k,Ft,i),a.set(g,Ft)}return a}var Ar={warn(){},error(){}};var Vy=864e5;function ie(e){if(e.type===D.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)/Vy)+1}function Qr(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=ie(n),e.updateActivity(r))}})}function Bo(e,t){let r=String(t.source),i=String(t.target);if(r===i)return!0;let n=new Map;for(let o of e){let a=String(o.source),s=String(o.target),c=n.get(a)??[];c.push(s),n.set(a,c)}return jy(n,i,r)}function ti(e){let t=new Map,r=new Map;for(let o of e){let a=String(o.source),s=String(o.target),c=t.get(a)??[];c.push(s),t.set(a,c),r.set(a,r.get(a)??0),r.set(s,(r.get(s)??0)+1)}let i=new Bt;for(let[o,a]of r)a===0&&i.enqueue(o);let n=0;for(;!i.isEmpty();){let o=i.dequeue();n+=1;for(let a of t.get(o)??[]){let s=r.get(a)-1;r.set(a,s),s===0&&i.enqueue(a)}}return n!==r.size}function jy(e,t,r){if(t===r)return!0;let i=new Set([t]),n=new Bt;for(n.enqueue(t);!n.isEmpty();){let o=n.dequeue(),a=e.get(o)??[];for(let s of a){if(s===r)return!0;i.has(s)||(i.add(s),n.enqueue(s))}}return!1}function Ji(e){let t=Ky(e);for(let r of t.adjacency.keys())t.records.has(r)||Yy(r,t);return t.components}function Ky(e){let t=new Map,r=new Set;for(let i of e){let n=String(i.source),o=String(i.target),a=_c(t,n);if(_c(t,o),n===o){r.add(n);continue}a.push(o)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function _c(e,t){let r=e.get(t);if(r)return r;let i=[];return e.set(t,i),i}function Yy(e,t){let r=[];for(r.push({node:e,record:kc(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;Gy(i,s,r,t);continue}r.pop();let o=r[r.length-1];o&&i.record.lowLink<o.record.lowLink&&(o.record.lowLink=i.record.lowLink),i.record.lowLink===i.record.visitIndex&&$y(i.node,t)}}function Gy(e,t,r,i){let n=i.records.get(t);if(!n){r.push({node:t,record:kc(t,i),neighborCursor:0});return}n.onStack&&n.visitIndex<e.record.lowLink&&(e.record.lowLink=n.visitIndex)}function kc(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 $y(e,t){let r=[];for(;;){let a=t.componentStack.pop();if(a===void 0||(a.record.onStack=!1,r.push(a.node),a.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 ei(e,t,r){let i=r?new Wo(e,r):e;return $i([...t],i)}var Wo=class{constructor(t,r){this.base=t;for(let[i,n]of r.reparented){let o=String(i),a=n===null||B(n)?null:n,s=t.getActivity(i)?.parentId??null,c=s===null||B(s)?null:String(s),l=a===null?null:String(a);if(c!==l){if(this.reparented.set(o,a),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(o),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),o=i?n.filter(s=>!i.has(String(s))):[...n],a=this.movedInByParent.get(r);return a&&o.push(...a),o}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,o=this.getActivity(t);for(;o;){let a=o.parentId;if(a===null||B(a))return!1;let s=String(a);if(s===i)return!0;if(n.has(s))return!1;n.add(s),o=this.getActivity(a)}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 Se(e){let{port:t,proposedPort:r,currentLinks:i,proposedLinks:n,proposal:o}=e,a=ei(r??t,n,o);if(!ti(a))return{ok:!0};let s=ei(t,i),c=Rc(s),d=[...Rc(a)].filter(u=>!c.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function Rc(e){let t=new Set;for(let r of Ji(e))for(let i of r)t.add(i);return t}function Zi(e,t,r){return r.getChildren(e).length>0||r.getChildren(t).length>0}function Te(e,t){switch(e.kind){case Et.CREATE:return zy(e,t);case Et.UPDATE:return qy(e,t.port,t.rejectParentLinkMutations??!1);case Et.DELETE:return Jy(e,t)}}function tn(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=Qi(l);i.has(d)||i.set(d,l.id),n.push({source:l.source,target:l.target})}let o=ti(n),a=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){a={applied:!1,rejected:ct.SELF_LINK};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){a={applied:!1,rejected:ct.ACTIVITY_MISSING};break}if(t.rejectParentLinkMutations&&Zi(l.source,l.target,t.port)){a={applied:!1,rejected:ct.HIERARCHY_LINK};break}if(Gi(l.source,l.target,t.port)){a={applied:!1,rejected:ct.HIERARCHY_LINK};break}let u=Qi(l),p=i.get(u);if(p!==void 0){a={applied:!1,rejected:ct.DUPLICATE,linkId:p};break}if(i.set(u,d),o&&Bo(n,{source:l.source,target:l.target}))return{applied:!1,rejected:ct.CYCLE};n.push({source:l.source,target:l.target})}if(!o&&ti(n))return{applied:!1,rejected:ct.CYCLE};if(a)return a;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(!Se({port:t.port,currentLinks:r,proposedLinks:s}).ok)return{applied:!1,rejected:ct.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 Qi(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function zy(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:ct.SELF_LINK};let i=r.getActivity(e.source),n=r.getActivity(e.target);if(!i||!n)return{applied:!1,rejected:ct.ACTIVITY_MISSING};if(t.rejectParentLinkMutations&&Zi(e.source,e.target,r))return{applied:!1,rejected:ct.HIERARCHY_LINK};if(Gi(e.source,e.target,r))return{applied:!1,rejected:ct.HIERARCHY_LINK};let o=r.getAllLinks();for(let d of o)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:ct.DUPLICATE,linkId:d.id};let a=o.map(d=>({source:d.source,target:d.target}));if(Bo(a,{source:e.source,target:e.target}))return{applied:!1,rejected:ct.CYCLE};let s=(t.newLinkId??Xy)(),c={id:s,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return Se({port:r,currentLinks:o,proposedLinks:[...o,c]}).ok?(r.addLink(c),{applied:!0,linkId:s}):{applied:!1,rejected:ct.CYCLE}}function qy(e,t,r){let i=t.getLink(e.linkId);if(!i)return{applied:!1,rejected:ct.LINK_MISSING};let n={...i,source:e.source??i.source,target:e.target??i.target,type:e.type??i.type,lag:e.lag??i.lag};if(String(n.source)===String(n.target))return{applied:!1,rejected:ct.SELF_LINK};if(!t.getActivity(n.source)||!t.getActivity(n.target))return{applied:!1,rejected:ct.ACTIVITY_MISSING};if(r&&(Zi(i.source,i.target,t)||Zi(n.source,n.target,t)))return{applied:!1,rejected:ct.HIERARCHY_LINK};if(Gi(n.source,n.target,t))return{applied:!1,rejected:ct.HIERARCHY_LINK};let o=t.getAllLinks(),a=o.find(l=>String(l.id)!==String(e.linkId)&&Qi(l)===Qi(n));if(a)return{applied:!1,rejected:ct.DUPLICATE,linkId:a.id};let s=o.map(l=>String(l.id)===String(e.linkId)?n:l);return Se({port:t,currentLinks:o,proposedLinks:s}).ok?((String(i.source)!==String(n.source)||String(i.target)!==String(n.target))&&t.setLinkEndpoints(e.linkId,n.source,n.target),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:ct.CYCLE}}function Jy(e,t){let{port:r}=t;return r.getLink(e.linkId)?(r.removeLink(e.linkId),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:ct.LINK_MISSING}}var Xi=null;function Xy(){return Xi===null&&(Xi=Date.now()),Xi+=1,String(Xi)}var _t={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},en={[H.FINISH_TO_START]:_t.FINISH_TO_START,[H.START_TO_START]:_t.START_TO_START,[H.FINISH_TO_FINISH]:_t.FINISH_TO_FINISH,[H.START_TO_FINISH]:_t.START_TO_FINISH},Ye={[_t.FINISH_TO_START]:H.FINISH_TO_START,[_t.START_TO_START]:H.START_TO_START,[_t.FINISH_TO_FINISH]:H.FINISH_TO_FINISH,[_t.START_TO_FINISH]:H.START_TO_FINISH},Pc=_t.FINISH_TO_START;function Lc(e){if(e in Ye)return Ye[e]}var Oc=";",De={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},Nc=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var Zy=5,rn=30,Ho=365,Qy={[De.DAY]:1,day:1,days:1,[De.MONTH]:rn,[De.MONTH_DHTMLX]:rn,month:rn,months:rn,[De.YEAR]:Ho,year:Ho,years:Ho},th=new Set([De.WEEK,De.WEEK_DHTMLX,"week","weeks"]);function nn(e,t={}){let r=[],i=[],n=t.daysPerWeek!==void 0&&Number.isFinite(t.daysPerWeek)&&t.daysPerWeek>0?t.daysPerWeek:Zy,o=e.replace(/\s+/g,"");if(o.length===0)return{specs:r,errors:i};for(let a of o.split(Oc)){if(a.length===0)continue;let s=eh(a,n);s?r.push(s):i.push(a)}return{specs:r,errors:i}}function eh(e,t){let r=e.toLowerCase(),i=Nc.exec(r);if(!i)return null;let[,n,o,a,s,c]=i,l=o?Ye[o]:Ye[Pc],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let p=c!==void 0&&th.has(c)?t:Qy[c??De.DAY],f=u*p;d=a==="-"?-f:f}return{correlativeId:n,type:l,lag:d}}function an(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],o=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=on(l,c.type);o.has(d)||o.set(d,{source:l,type:c.type,lag:c.lag})}let a=new Map;for(let c of r)String(c.target)===String(t)&&a.set(on(c.source,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:Et.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:Et.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:Et.CREATE,source:l.source,target:t,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function on(e,t){return`${String(e)}::${t}`}function sn(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:i}=e,n=[],o=new Map;for(let c of i){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){n.push(c);continue}let d=on(l,c.type);o.has(d)||o.set(d,{target:l,type:c.type,lag:c.lag})}let a=new Map;for(let c of r)String(c.source)===String(t)&&a.set(on(c.target,c.type),c);let s=[];for(let[c,l]of a)o.has(c)||s.push({kind:Et.DELETE,linkId:l.id});for(let[c,l]of o){let d=a.get(c);d&&d.lag!==l.lag&&s.push({kind:Et.UPDATE,linkId:d.id,lag:l.lag})}for(let[c,l]of o)a.has(c)||s.push({kind:Et.CREATE,source:t,target:l.target,type:l.type,lag:l.lag});return{operations:s,unresolved:n}}function cn(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function Kt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var bc={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:Y.FUTURE,date:e,unit:ft.HOUR}):t.isWorkTime(e,ft.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function Vo(e,t,r){switch(r){case H.FINISH_TO_START:return{sourceDate:e.endDate,targetDate:t.startDate};case H.START_TO_START:return{sourceDate:e.startDate,targetDate:t.startDate};case H.FINISH_TO_FINISH:return{sourceDate:e.endDate,targetDate:t.endDate};case H.START_TO_FINISH:return{sourceDate:e.startDate,targetDate:t.endDate}}}var jo=bc;var vr=class{adapter;reporter;currentCalculationId=0;topoCache=new Vi;expandedLinksCache=new zi;constructor(t,r=Ar){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=uc(r,()=>this.currentCalculationId),n={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{nh(this.adapter);let o=Ee("schedule.total"),a=Ee("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(s,this.adapter);de(a);let l=c;if((await gr(i)).aborted)return{...n,cancelled:!0};let d=Ee("schedule.scoping"),u=this.adapter.getAllIds(),p=oh(t,l,this.adapter),f=p.links,y=p.idSet;de(d);let m=Ee("schedule.topologicalSort"),g=sh(this.topoCache,u,l,y);if(de(m),g.hasCycles)return de(o),{...n,cycles:[g.cycleNodes]};if((await gr(i)).aborted)return{...n,cancelled:!0};let _=Ee("schedule.processConstraints"),k=new Map;if(Cc(g.ordered,this.adapter,k),de(_),(await gr(i)).aborted)return{...n,cancelled:!0};let O=Ee("schedule.asapPass"),T=await Dc(g.ordered,f,this.adapter,t,i,k);if(de(O),(await gr(i)).aborted)return{...n,cancelled:!0};let P=Ee("schedule.alapPass"),M=await Ec(g.reversed,f,T,this.adapter,t,i);if(de(P),(await gr(i)).aborted)return{...n,cancelled:!0};let A=Ee("schedule.diff"),v=[];for(let[N,j]of M){let K=this.adapter.getActivity(N);if(!K)continue;let Z=K.startDate.getTime()!==j.startDate.getTime(),st=K.endDate.getTime()!==j.endDate.getTime();(Z||st)&&v.push(N)}return de(A),de(o),{plans:M,updatedIds:v,cycles:[],cancelled:!1}}catch(o){throw this.reporter.error("[AutoScheduler] Error during scheduling",o),o}}},rh=!1;function ih(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:rh}function Ee(e){return{name:e,startedAt:performance.now()}}function nh(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function de(e){if(!ih())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function oh(e,t,r){let i=e.triggerId;if(i==null)return{idSet:null,links:t};let n=mc(i,t);return ah(n,t,r)}function ah(e,t,r){let i=new Set(e.activityIds),n=new Set;for(let a of r.getAllActivities()){let s=String(a.id);a.constraintType===C.ALAP&&!i.has(s)&&(n.add(s),i.add(s))}if(n.size===0)return{idSet:i,links:e.links};let o=[...e.links];for(let a of t)(n.has(String(a.source))||n.has(String(a.target)))&&o.push(a);return{idSet:i,links:o}}function sh(e,t,r,i){let n=e.get(t,r);if(n.hasCycles){let a=i?Array.from(i):t;return Hi(a,r)}if(!i)return n;let o=pc(n.ordered,i);return{ordered:o,reversed:[...o].reverse(),hasCycles:!1,cycleNodes:[]}}function wc(e,t,r){let i=t.getActivity(e);if(!i)return;let n=r?{...i,endDate:r.endDate}:i,o=t.calendarReader.getCalendar(String(i.calendarId));for(let a of t.getIncomingLinkIds(e)){let s=t.getLink(a);if(!s)continue;let c=t.getActivity(s.source);if(!c||c.constraintType===C.ALAP||le(i.type)&&(s.type===H.START_TO_FINISH||s.type===H.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=Vo(c,n,s.type),p=jo.computeLagBetweenTasks(d,u,o);p!==s.lag&&t.setLinkField(s.id,xt.LAG,p)}}function Fc(e,t){let r=t.getActivity(e);r&&le(r.type)&&(r.durationHours=0)}function ln(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 xc(e){return Number(e.toFixed(2))}function ri(e){for(let t of ch(e))Uc(t,e)}function Mc(e,t){for(let r of e)Uc(r,t)}function ch(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,lh(i,e));return[...t].sort((i,n)=>(r.get(n)??0)-(r.get(i)??0))}function lh(e,t){let r=0,i=e;for(;i&&i!=="0"&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Uc(e,t){let r=t.getChildren(e);if(r.length===0)return;let i=[];for(let n of r){let o=t.getActivity(n);o&&i.push({progress:Number(o.progress??0),ponderator:Number(o.ponderator??0)})}Ko(e,i,t)}function Ko(e,t,r){let i=r.getActivity(e);if(!i)return;let n=ln(t);if(n===null){let o=r.getProgressFallback(e);o!==null&&r.setActivityField(e,E.PROGRESS,o);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(i.progress??0)),r.setActivityField(e,E.PROGRESS,xc(n))}function Bc(e,t,r){let i=[e];for(;i.length>0;){let n=i.pop();if(n===void 0)continue;let o=r.getChildren(n);o.length!==0&&(r.setProgressFallback(n,t),i.push(...o))}}function Mt(e,t){return(Number(e)||0)*(Number(t)||0)/100}var ii={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function Cr(e,t,r=!0,i={}){let n=t?ni(e,t):hh(e),o=r?i.progressMode??ii.FREEZE_WITHOUT_CONTRIBUTION:ii.SKIP;await dh(n,e,o,{recomputeRealWork:i.recomputeRealWork??!1})}function dn(e,t){Wc(e,t,ii.SKIP)}async function dh(e,t,r,i={recomputeRealWork:!1}){let o=0;for(let a of e)Wc(a,t,r,i.recomputeRealWork),o+=1,o%200===0&&await ut()}function ni(e,t){let r=new Set,i=new Map;for(let a of t)uh(a,e,r,i);if(r.size===0)return[];let n=Array.from(r),o=ph(n,i);return Hc(n,o)}function uh(e,t,r,i){let n=t.getParentId(e);for(;n&&!B(n);){if(r.has(n))return;r.add(n);let o=t.getParentId(n);i.set(n,o),n=o}}function ph(e,t){let r=new Map;for(let i of e){if(r.has(i))continue;let n=[],o=new Set,a=i;for(;a&&!B(a)&&!r.has(a)&&!o.has(a);)n.push(a),o.add(a),a=t.get(a)??null;let s=a?r.get(a)??0:0;for(let c=n.length-1;c>=0;c-=1)s+=1,r.set(n[c],s)}return r}function fh(e,t,r){let i=null,n=null,o=0,a=[];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&&(o+=yh(c,t.getChildren(s).length>0)),a.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:i,maxEnd:n,realWorkSum:o,weightedChildren:a}}function Wc(e,t,r=ii.FREEZE_WITHOUT_CONTRIBUTION,i=!1){let n=t.getActivity(e);if(!n)return;let o=t.getChildren(e);if(o.length===0)return;let a=fh(o,t,i);if(a.minStart===null||a.maxEnd===null)return;let s=String(n.calendarId??""),c=t.calendarReader.getCalendar(s),l=new Date(a.minStart),d=new Date(a.maxEnd),u=c.calculateDuration(l,d);t.setActivityField(e,"startDate",l),t.setActivityField(e,"endDate",d),t.setActivityField(e,"durationHours",u),r!==ii.SKIP&&Ko(e,a.weightedChildren,t),i&&t.setActivityField(e,"realWorkHours",a.realWorkSum)}function yh(e,t){return t?Number(e.realWorkHours)||0:Mt(e.workHours,e.progress)}function hh(e){let t=mh(e),r=Ih(t,e);return Hc(t,r)}function mh(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ih(e,t){let r=new Map;for(let i of e)r.set(i,gh(i,t));return r}function gh(e,t){let r=0,i=e;for(;i&&!B(i)&&t.getActivity(i);)r+=1,i=t.getParentId(i);return r}function Hc(e,t){return[...e].sort((r,i)=>(t.get(i)??0)-(t.get(r)??0))}var Vc={updateActivityDuration:Fc,updateTaskTiming:vh("updateTaskTiming"),adjustLinkLagOnTaskMove:wc,recordLastStartDate:Ah};function Ah(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function _e(e,t,r,i){for(let n of t){let o=n in Vc?Vc[n]:void 0;if(!o){console.warn(`[replay post-processors] unknown: ${n} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}o(e,r,i??null)}}function vh(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function G(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function J(e){return{ok:!1,reason:e}}function rt(){return{valid:!0}}function gt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function tt(){return{allowed:!0}}function at(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function et(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 ht={PROGRESS_ENTRY:"activity_progress_entry",PROGRESS_UPDATE_RADIO_BUTTON:"activity_progress_update_radio_button",DURATION_ENTRY:"activity_duration_entry",START_DATE_ENTRY:"activity_start_date_entry",END_DATE_ENTRY:"activity_end_date_entry",NAME_ENTRY:"activity_name_entry",DESCRIPTION_ENTRY:"activity_description_entry",CALENDAR_ASSIGNMENT:"activity_calendar_assignment",COST_BUDGETED_ENTRY:"activity_cost_budgeted_entry",COST_SPENT_ENTRY:"activity_cost_spent_entry",LABOR_HOURS_BUDGETED_ENTRY:"activity_labor_hours_budgeted_entry"};var jc={targetField:"name",canEdit(){return tt()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e)},validate(){return rt()},transform(e,t){return et({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ht.NAME_ENTRY};var Kc={targetField:"description",canEdit(){return tt()},parseInput(e){return typeof e!="string"?J("not_a_string"):G(e.trim())},validate(){return rt()},transform(e,t){return et({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:ht.DESCRIPTION_ENTRY};function Jt(e){return e.constraintType??C.ASAP}var un=100;function ke(e){return e.progress>=un}function At(e,t){return qt(e.type,t.hasChildren(e.id))}function Yc(e){return e.progress>0}function Gc(e){return e.hasLookaheadTasks}function Ge(e,t){return Math.round(Math.ceil(e*t*60)/60)}var Sr=e=>({endDate:e});var pn="UTC";function Re(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(o=>o.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 fn(e,t){if(!t||t===pn){let p=new Date(e);return p.setUTCHours(23,59,0,0),p}let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),i=p=>Number(r.find(f=>f.type===p)?.value),n=i("year"),o=i("month"),a=i("day"),s=Date.UTC(n,o-1,a,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=p=>Number(c.find(f=>f.type===p)?.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 Ch(e,t){let r=Re(t,pn);for(;!e.isWorkTime(r,ft.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Re(r,pn);return r}function Yo(e,t){return e.getClosestWorkTime({direction:Y.FUTURE,date:t,unit:ft.HOUR})}function Go(e,t){let r=Ch(e,t),i=new Date(r);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:Y.PAST,date:i,unit:ft.HOUR})}var oi=new Set([C.SNET,C.SNLT,C.MSO]),$o=new Set([C.FNET,C.FNLT,C.MFO]),Pe=new Set([C.ASAP,C.ALAP]),yn=C.SNET;function ue(e,t,r){let i=Re(e,pn);if(!oi.has(r)&&!$o.has(r))return i;let n=oi.has(r)?Yo(t,i):Go(t,i),o=new Date(i);return o.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),o}var Le=()=>({constraintType:yn});var $e=e=>({constraintDate:e}),$c=e=>({constraintDate:e});var zc={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var hn={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"},ai={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress"},qc={CANT_EDIT_COMPLETED:"cant_edit_completed_activity",SUMMARY_COLUMN_VALUE:"summary_column_value",CANT_EDIT_WITH_PROGRESS:"cant_edit_activity_with_progress",SIR_CANT_MOVE_START_AFTER_PROGRESS:"sir_cant_move_start_after_progress",CANT_EDIT_WITH_TASK:"cant_edit_actvity_with_task"};function Tr(e,t,r){return Di(e,t,r)}function Dr(e,t,r){return Ei(e,t,r)}var Xc={targetField:"durationHours",canEdit(e,t){return ke(e)?at("completed","cant_edit_completed_activity"):At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e,t,r){let i=parseFloat(String(e));return Number.isFinite(i)?G(Ge(i,r.hoursPerDay)):J("not_a_number")},validate(e,t,r){return Jc(r)?gt(hn.NEGATIVE_DURATION):Sh(t,r)?gt("unchanged"):rt()},transform(e,t,r){if(Jc(t))return et({},{autoSchedule:!1,postProcessors:[]});let i=Th(e,t,r),n=Dh(e,t,r,i.violated);return{...et(n,{autoSchedule:!0,postProcessors:[zc.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:Dr(i.constraintType,i.constraintDate,Zc(e,t,r)??void 0)}:{}}},trackEvent:ht.DURATION_ENTRY};function Jc(e){return Math.sign(e)===-1}function Sh(e,t){return e===t}function Th(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)return{violated:!1};let n=e.constraintType;if(n!==C.FNET&&n!==C.FNLT&&n!==C.MFO)return{violated:!1};let o=i.calculateEndDate(e.startDate,t);return Tr(n,e.constraintDate,o)}function Dh(e,t,r,i=!1){let n={};i&&Object.assign(n,Le(),$e(e.startDate));let o=Xr(e.durationHours,t);o&&(n.type=o),n.durationHours=t;let a=Zc(e,t,r);return a&&Object.assign(n,Sr(a)),n}function Zc(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateEndDate(e.startDate,t):null}var Er=e=>({realWorkHours:e});var Eh=0,_h=un,mn={targetField:"progress",canEdit(e,t){return At(e,t)?at("summary","summary_column_value"):Gc(e)?at("has_lookahead_tasks","cant_edit_actvity_with_task"):tt()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(e,t,r){return kh(r)?gt("out_of_range"):rt()},transform(e,t,r){let i=Ke(t),n=e.progress!==t&&i,o=Rh(t),a=Oh(e,t,r.hierarchy),s={progress:t,autoScheduling:i,...Er(a.get(e.id)??0)},c=o?Ph(e,t,i,r.hierarchy,a):[],l=o?bh(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],p=o?Fh(e,t):void 0;return et(s,{autoSchedule:n,postProcessors:u,cascadeMutations:d,trackingEvents:p})},trackEvent:ht.PROGRESS_ENTRY};function kh(e){return e<Eh||e>_h}function Rh(e){return e===un||Ke(e)}function Ph(e,t,r,i,n){return i.getDescendantIds(e.id).map(a=>({activityId:a,fields:Lh(t,r,n.get(a)??0)}))}function Lh(e,t,r){return{progress:e,autoScheduling:t,...Er(r)}}function Oh(e,t,r){let i=new Map,n=a=>{let s=0;for(let c of r.getChildHhInfo(a)){let l=r.hasChildren(c.id)?n(c.id):Mt(c.workHours,t);i.set(c.id,l),s+=l}return s},o=r.hasChildren(e.id)?n(e.id):Mt(e.workHours,t);return i.set(e.id,o),i}function Nh(e,t){let r=[e.id,...t.getDescendantIds(e.id)],i=o=>t.getChildProgressInfo(o).some(a=>t.hasChildren(a.id)),n=o=>t.getAncestorIds(o).length;return r.filter(o=>i(String(o))).map(String).sort((o,a)=>n(a)-n(o))}function bh(e,t,r){let i=new Map;i.set(e.id,t);for(let a of r.getDescendantIds(e.id))i.set(a,t);let n=[...Nh(e,r),...r.getAncestorIds(e.id)],o=[];for(let a of n){let s=wh(a,i,r);s!==null&&(i.set(a,s),o.push({activityId:a,fields:{progress:s}}))}return o}function wh(e,t,r){let i=r.getChildProgressInfo(e).map(o=>({progress:t.has(o.id)?t.get(o.id):o.progress,ponderator:o.ponderator??0})),n=ln(i);return n===null?null:Number(n.toFixed(2))}function Fh(e,t){return[{name:ht.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Qc={targetField:"cost",canEdit(e,t){return At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e){if(String(e).trim()==="")return G(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(){return rt()},transform(e,t,r){let i=xh(e,t,r.hierarchy);return et({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:ht.COST_BUDGETED_ENTRY};function xh(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let o of r.getAncestorIds(e.id)){let a=0;for(let s of r.getChildCostInfo(o))a+=i.has(s.id)?i.get(s.id):s.cost;i.set(o,a),n.push({activityId:o,fields:{cost:a}})}return n}var tl={targetField:"usedCost",canEdit(e,t){return At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e){if(String(e).trim()==="")return G(0);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(){return rt()},transform(e,t,r){let i=Mh(e,t,r.hierarchy);return et({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:ht.COST_SPENT_ENTRY};function Mh(e,t,r){let i=new Map;i.set(e.id,t);let n=[];for(let o of r.getAncestorIds(e.id)){let a=0;for(let s of r.getChildUsedCostInfo(o))a+=i.has(s.id)?i.get(s.id):s.usedCost;i.set(o,a),n.push({activityId:o,fields:{usedCost:a}})}return n}var el={targetField:"workHours",canEdit(e,t){return At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e){if(String(e).trim()==="")return G(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?J("not_a_number"):G(t)},validate(){return rt()},transform(e,t,r,i){let n=rl(t,e.progress),o=String(i).trim()===""?[]:Uh(e,t,n,r.hierarchy);return et({workHours:t,...Er(n)},{autoSchedule:!1,postProcessors:[],cascadeMutations:o})},trackEvent:ht.LABOR_HOURS_BUDGETED_ENTRY};function rl(e,t){return Mt(e,t)}function Uh(e,t,r,i){let n=new Map,o=new Map;n.set(e.id,t),o.set(e.id,r);let a=[];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,p=o.has(d.id)?o.get(d.id):d.realWorkHours??rl(d.workHours,d.progress);c+=u,l+=p}n.set(s,c),o.set(s,l),a.push({activityId:s,fields:{workHours:c,...Er(l)}})}return a}function In(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function zo(e,t){return e.getTime()<t.getTime()}function _r(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var gn=e=>({durationHours:e});var Bh="sir-apply",il={targetField:"startDate",canEdit(e,t,r){return At(e,t)?at("summary","summary_column_value"):Yc(e)?r?.eventSource!==Bh?at("has_progress","cant_edit_activity_with_progress"):ke(e)?at("completed","cant_edit_completed_activity"):tt():tt()},parseInput(e,t,r){return _r(e)?G(Re(e,"UTC")):J("invalid_date")},validate(e,t,r,i){if(In(t,r))return gt("unchanged");let n=Wh(e,r,i);return n||rt()},transform(e,t,r){let i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let n=Yo(i,t),o=e.type===D.MILESTONE,a=o?n:i.calculateEndDate(n,e.durationHours),s=n;return{...et({startDate:n,...Sr(a),...o?gn(0):{},...Le(),...$e(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Hh(e,n,i)}},trackEvent:ht.START_DATE_ENTRY};function Wh(e,t,r){let i=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!i)return null;let n=Re(i,"UTC");return t.getTime()<n.getTime()?gt("before_parent_start"):null}function Hh(e,t,r){let i=r.calculateEndDate(t,e.durationHours),n=Me(Jt(e),t,i),o=Tr(Jt(e),e.constraintDate,n);if(o.violated)return Dr(o.constraintType,o.constraintDate,n)}var Vh=99.999,ol={targetField:"endDate",canEdit(e,t){return At(e,t)?at("summary","summary_column_value"):jh(e)?at("completed","cant_edit_completed_activity"):tt()},parseInput(e,t,r){if(!_r(e))return J("invalid_date");let i=Re(e,"UTC"),n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(i,ft.DAY)?G(Go(n,i)):G(n.getClosestWorkTime({direction:"past",date:i,unit:ft.HOUR})):G(i)},validate(e,t,r,i){if(In(e.endDate,r))return gt("unchanged");if(Kh(r,e))return gt("before_date_origin");if(Yh(r,e))return gt("before_start_date");let n=Gh(r,e,i);return n||rt()},transform(e,t,r){let i=$h(e,t),n=zh(e,t,r,!!i);return{...et(n,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:ht.END_DATE_ENTRY};function jh(e){return e.progress>=Vh}function Kh(e,t){return t.dateOrigin?zo(e,t.dateOrigin):!1}function Yh(e,t){return zo(e,t.startDate)}function Gh(e,t,r){let i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(e,ft.DAY)?null:gt("not_working_day"):null}function $h(e,t){if(Jt(e)===C.MSO)return;let i=Me(Jt(e),e.startDate,t),n=Tr(Jt(e),e.constraintDate,i);if(n.violated)return Dr(n.constraintType,n.constraintDate,i)}function zh(e,t,r,i=!1){let n={};le(e.type)&&!i&&nl(e)?Object.assign(n,$e(e.startDate)):(i||nl(e))&&Object.assign(n,Le(),$e(e.startDate));let s=qh(e,t,r),c=Xr(e.durationHours,s);return c&&(n.type=c),Object.assign(n,gn(s)),n.endDate=t,n}function nl(e){return Pe.has(Jt(e))}function qh(e,t,r){let i=r.calendars.getCalendar(e.calendarId);return i?i.calculateDuration(e.startDate,t):e.durationHours}var Jh=new Set(Object.values(C)),al={targetField:"constraintType",canEdit(e,t){return ke(e)?at("completed","cant_edit_completed_activity"):At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e){let t=String(e).toLowerCase();return Xh(t)?G(t):J("invalid_constraint_type")},validate(){return rt()},transform(e,t,r){let i=Zh(e,t,r);return et(i,{autoSchedule:!0})}};function Xh(e){return Jh.has(e)}function Zh(e,t,r){let i=tm(e,t);return{constraintType:t,...$c(Qh(e,t,i,r))}}function Qh(e,t,r,i){if(e.type!==D.MILESTONE||!r||oi.has(t))return r;let n=i.calendars.getCalendar(String(e.calendarId));return n?ue(r,n,t):r}function tm(e,t){return Pe.has(t)?null:oi.has(t)?e.startDate:$o.has(t)?e.endDate:e.constraintDate}var sl={targetField:"constraintDate",canEdit(e,t){return ke(e)?at("completed","cant_edit_completed_activity"):At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e){return _r(e)?G(e):J("invalid_date")},validate(){return rt()},transform(e,t,r){let i=cl(e)?yn:Jt(e),n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let o=ue(t,n,i),a=em(e,o);return et(a,{autoSchedule:!0})}};function em(e,t){return{constraintDate:t,...cl(e)?Le():{}}}function cl(e){return Pe.has(Jt(e))||!e.constraintType}var ll={targetField:"calendarId",canEdit(){return tt()},parseInput(e){let t=String(e).trim();return rm(t)?J("empty_calendar"):G(t)},validate(e,t,r,i){return im(e.calendarId,r)?gt("unchanged"):i.calendars.getCalendar(r)?rt():gt("unknown_calendar")},transform(e,t,r){return et(nm(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:ht.CALENDAR_ASSIGNMENT};function rm(e){return e===""}function im(e,t){return e===t}function nm(e,t,r){let i={calendarId:t,assignedDefaultCalendar:!1},n=r.calendars.getCalendar(t);if(n){let o=n.isWorkTime(e.startDate,"hour"),a=n.getClosestWorkTime({date:o?dl(e.startDate):e.startDate,direction:"future",unit:"hour"});i.startDate=a;let s=om(e,n);if(s&&(i.constraintDate=s),!e.autoScheduling)return i;Object.assign(i,Sr(n.calculateEndDate(a,e.durationHours)))}return i}function om(e,t){return!e.constraintDate||!e.constraintType?null:$r({...e,constraintDate:dl(e.constraintDate)},{getClosestWorkTime:({date:r,dir:i})=>t.getClosestWorkTime({date:r,direction:i,unit:ft.HOUR})})}function dl(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var ul={targetField:"customId",canEdit(e,t){return At(e,t)?at("summary","summary_column_value"):tt()},parseInput(e){if(e==null)return J("empty_custom_id");if(typeof e!="string")return J("not_a_string");let t=e.trim();return t.length===0?J("empty_custom_id"):t.length>20?J("exceeds_max_length"):G(t)},validate(){return rt()},transform(e,t){return et({customId:t},{autoSchedule:!1,postProcessors:[]})}};var pl={targetField:"subcontractId",canEdit(){return tt()},parseInput(e){if(e==null)return G(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return G(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?J("not_an_integer"):G(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?J("not_an_integer"):G(e):J("not_an_integer")},validate(){return rt()},transform(e,t){return et({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function si(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 An(e){return e.some(t=>si(t)===null)}var fl={targetField:"responsableIds",canEdit(){return tt()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,r){return An(r)?gt("missing_id"):rt()},transform(e,t){let r=t.map(si).filter(i=>i!==null);return et({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var yl={targetField:"tagIds",canEdit(){return tt()},parseInput(e){return e==null?G([]):Array.isArray(e)?G(e):J("not_an_array")},validate(e,t,r){return An(r)?gt("missing_id"):rt()},transform(e,t){let r=t.map(si).filter(i=>i!==null);return et({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var am=new Map([[E.TEXT,jc],[E.DESCRIPTION,Kc],[E.DURATION,Xc],[E.PROGRESS,mn],[E.COST,Qc],[E.USED_COST,tl],[E.HH_WORK_TIME,el],[E.START_DATE,il],[E.END_DATE,ol],[E.CONSTRAINT_TYPE,al],[E.CONSTRAINT_DATE,sl],[E.CALENDAR_ID,ll],[E.CUSTOM_ID,ul],[E.SUBCONTRACT_ID,pl],[E.RESPONSABLES,fl],[E.TAGS,yl]]);function Oe(e){return am.get(e)}var mt={APPEND:"append",REPLACE:"replace"},vn={ACTION_BUTTON:"action-button"},Cn={SIR_AUTO_REJECT:"sir-auto-reject"},Sn={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},qe={VIOLATION:"constraint_violation"},ne={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo"};function Je(e,t){if(!t||t.type!==Si.CONSTRAINT)return null;let r=t.data;return!r?.constraintType||!r.constraintDate?null:{kind:qe.VIOLATION,activityId:e,constraintType:r.constraintType,constraintDate:r.constraintDate,projectedDate:r.projectedDate??r.constraintDate,messageKey:t.messageKey}}var sm=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],hl=new Set(sm);function Tt(e,t,r,i){e.setActivityFieldDynamic(t,r,i)}function ml(e,t,r,i){e.setLinkFieldDynamic(t,r,i)}function pe(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:oe(e.constraintDate),dateOrigin:oe(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:oe(t.startDate),endDate:oe(t.endDate)})),baselineSnapshot:cm(e.baselineSnapshot),criticalPath:lm(e.criticalPath)}}function oe(e){return e===null?null:new Date(e)}function cm(e){return e===null?null:{...e,startDate:oe(e.startDate),endDate:oe(e.endDate)}}function lm(e){return e===null?null:{...e,earlyStart:oe(e.earlyStart),earlyFinish:oe(e.earlyFinish),lateStart:oe(e.lateStart),lateFinish:oe(e.lateFinish)}}var Al=200;function Ne(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%Al===0&&await ut();let o=e.getActivity(n);o&&r.set(n,it(o))}return r}function it(e){return pe(e)}function Tn(e,t){let r=e.getActivity(t);return r?pe(r):null}function be(e,t,r){Il(e,t,r.patch);for(let i of r.cascadeMutations??[])Il(e,i.activityId,i.fields)}function Il(e,t,r){for(let[i,n]of Object.entries(r)){if(!hl.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);Tt(e,t,i,n)}}async function Dn(e,t,r,i){let n=[],o=0;for(let a of r){o+=1,o%Al===0&&await ut();let s=dm(e,t,a,i);s&&n.push(s)}return n}function dm(e,t,r,i){let n=e.getActivity(r);if(!n)return{id:r,kind:b.DELETED,after:null};let o=t.get(r);if(!o&&i?.has(r))return um(r,i.get(r),n);let a=Jo(o,n);return pm(a,i,r,n),o&&Object.keys(a).length===0?null:{id:r,kind:o?b.UPDATED:b.CREATED,fields:a,after:it(n)}}function um(e,t,r){return t===r.correlativeId?null:{id:e,kind:b.UPDATED,fields:{correlativeId:{before:t,after:r.correlativeId}},after:it(r)}}function pm(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})}var fm=[w.CALENDAR_DURATION,w.BASELINE_VARIANCE_DAYS];function Jo(e,t){let r={},i=e??{},n=t,o=new Set([...Object.keys(i),...Object.keys(n)]);for(let a of fm)o.delete(a);for(let a of o)(Object.hasOwn(i,a)!==Object.hasOwn(n,a)||!qo(i[a],n[a]))&&(r[a]={before:gl(i[a]),after:gl(n[a])});return r}function gl(e){return e===null||typeof e!="object"?e:F(e)}function qo(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((a,s)=>qo(a,t[s]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,i=t,n=Object.keys(r),o=Object.keys(i);return n.length!==o.length?!1:n.every(a=>Object.hasOwn(i,a)&&qo(r[a],i[a]))}function En(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 Xo(e,t){let r=new Set;for(let i of e)r.add(String(i));for(let i of t)r.add(i);return r}function kr(e,t,r,i,n){for(let o of t){if(r.has(o.activityId)||(n.add(o.activityId),i.has(o.activityId)))continue;let a=e.getActivity(o.activityId);if(!a)continue;let s=it(a);o.before!==void 0&&(s.correlativeId=o.before),i.set(o.activityId,s)}}var ym=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function fe(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(ym);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,i,n,o,a]=t;return new Date(Date.UTC(Number(r),Number(i)-1,Number(n),Number(o),Number(a)))}function Rr(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),o=i.calculateDuration(e,t);return o===0?0:n*100/o}var hm=e=>e.type===D.PROJECT,mm=(e,t,r)=>{let i=e.calendarId,n=i!=null?r.calendarReader.getCalendar(String(i)):null;if(!n)return 0;let o=a=>a instanceof Date?a:fe(String(a));return Rr(o(e.startDate),o(e.endDate),t,n)};function Im(e,t,r){let i=[],n=(a,s)=>{let c=r.getActivity(a);c&&c.expectedProgress!==s&&(r.setActivityField(a,"expectedProgress",s),i.push(String(a)))},o=a=>{let s=r.getActivity(a);if(!s)return 0;if(!hm(s)){let d=mm(s,t,r);return n(a,d),d}let c=0;for(let d of r.getChildren(a)){let u=o(d),p=r.getActivity(d),f=typeof p?.ponderator=="number"?p.ponderator:0;c+=u*f}let l=c/100;return n(a,l),l};for(let a of e)o(a);return i}function Xe(e,t){let r=[];e.forEachActivity((i,n)=>{i.parentId===null&&r.push(n)}),Im(r,t,e)}var gm=e=>e.type===D.PROJECT,Am=e=>Ct(e),vm=(e,t,r,i)=>{let n=Am(e);if(!n)return 0;let o=(n.baseCalendarId!=null?r.getBaseCalendar(`${n.baseCalendarId}-base`):null)??(i?r.getBaseCalendar(i):null);return!o||!n.startDate||!n.endDate?0:Rr(n.startDate,n.endDate,t,o)};function Zo(e,t,r,i=null){let n=[],o=(s,c)=>{let l=r.getActivity(s);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(s,"expectedProgressBaseline",c),n.push(s))},a=s=>{let c=r.getActivity(s);if(!c)return 0;if(!gm(c)){let u=vm(c,t,r,i);return o(s,u),u}let l=0;for(let u of r.getChildrenIds(s)){let p=a(u),f=r.getActivity(u),y=typeof f?.ponderator=="number"?f.ponderator:0;l+=p*y}let d=l/100;return o(s,d),d};for(let s of e)a(s);return n}function Pr(e,t,r=null){let i={getChildrenIds:o=>e.getChildren(String(o)).map(a=>String(a)),getActivity:o=>e.getActivity(o),setActivityField:(o,a,s)=>Tt(e,o,a,s),getBaseCalendar:o=>e.calendarReader.getCalendar(o)},n=[];return e.forEachActivity((o,a)=>{o.parentId===null&&n.push(a)}),Zo(n,t,i,r)}var Qo=me.BASELINE;function _n(e){return e===me.ACTUAL?me.ACTUAL:Qo}var vl=e=>Math.round(e*100)/100;function Cm(e,t){return(t===me.BASELINE?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Sm(e,t){let r=vl(e),i=vl(t);return r>99.99?Rt.DONE:i>r?Rt.OVERDUE:e>0&&r>i?Rt.ADVANCEMENT:e===0&&t===0?Rt.WAITING:e>0&&r<i?Rt.DOING:Rt.WAITING}function ye(e,t){let r=[];return e.forEachActivity((i,n)=>{let o=typeof i.progress=="number"?i.progress:0,a=Sm(o,Cm(i,t));i.status!==a&&(Tt(e,n,E.STATUS,a),r.push(n))}),r}function Cl(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isVisibleVersion)??null}var Sl=100,Tm=e=>Math.round(e*Sl)/Sl;function Dm(e,t,r){if(r<=0)return null;let i=Cl(e)?.endDate,n=e.endDate;if(!i||!n)return null;let o=n.getTime()>i.getTime(),a=i.getTime()>n.getTime();if(!o&&!a)return 0;let s=t.calculateDuration({startDate:o?i:n,endDate:o?n:i,task:e}),c=Tm(s/r);return o?c:-c}function Ze(e,t){let r=[];return e.forEachActivity((i,n)=>{let o=Dm(i,e,t);i.baselineVarianceDays!==o&&(i.baselineVarianceDays=o,r.push(String(n)))}),r}function ta(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,o)=>a=>a===void 0?t[n]():(t[o](a),i),i={__isMomentShim:!0,clone:()=>ta(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}ta.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Yt=ta;function Em(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function kn(e){return Em(e)&&!isNaN(e.getTime())}function R(e,t,r,i){if(!kn(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 Wt(e){if(!kn(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 I=C;var W=Object.freeze({FS:_t.FINISH_TO_START,SS:_t.START_TO_START,FF:_t.FINISH_TO_FINISH,SF:_t.START_TO_FINISH});function Qe(e){return en[String(Number(e))]??_t.START_TO_FINISH}var q=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),tr=Object.freeze({GREATER:"greater",LESS:"less"}),Xt=Object.freeze({SOURCE:"$source"});var _m=e=>e?e.$level===1:!1,km=e=>e.type===D.PROJECT,Rm=e=>e.$level!==0,Pm=e=>e.type===D.TASK,Lm=e=>e.type===D.TASK||e.type===D.MILESTONE,bt={byFirstLevel:_m,filterByParentType:km,avoidSubproject:Rm,byTaskType:Pm,byTaskTypeAndMilestone:Lm};function Tl(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:i,linkProperty:n}=e;try{let o=Om({gantt:t,pendingParentsWithNoLinks:r});if(o.length===0)return new Set;let a=Nm({gantt:t,subprojectsWithNoLinks:o}),s=bm({gantt:t,childrenIds:a,linkProperty:n,getArrayOfLinkedActivities:wm,calculations:i});return new Set(s.map(c=>c.id))}catch(o){throw o}}function Om(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(bt.filterByParentType).filter(i=>r.has(i.id)).map(i=>i.id)}function Nm(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=bt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(s=>i.add(s));return[...i]}function bm(e){let{gantt:t,childrenIds:r,linkProperty:i,getArrayOfLinkedActivities:n,calculations:o}=e,a=[];for(let s of r){let c=t.getTask(s),l=c[i]||[];n({gantt:t,links:l,linkDirection:i===Xt.SOURCE?"target":"source"}).every(p=>o.has(p))&&a.push(c)}return a}function wm(e){let{gantt:t,links:r,linkDirection:i}=e,n=[];for(let o of r){let a=t.getLink(o);if(!a){`${o}`;continue}let s=Number(a[i]);n.push(s)}return n}function Dl({gantt:e,linkProperty:t,direction:r}){try{let i=Fm(e,t);if(r===q.FORWARD)return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(r===q.BACKWARD)return xm(i,e,t)}catch(i){throw console.log("Critical Path",i),i}}function Fm(e,t){return e.getTaskByTime().filter(bt.avoidSubproject).filter(bt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function xm(e,t,r){let i=[],n=new Set;return e.forEach(o=>{let a=Number(o.parent),s=t.getTask(a);s&&(s[r].length>0?n.add(o.id):s.constraint_type!==I.FNLT&&i.push(o))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:n}}function El({gantt:e,direction:t,linkProperty:r}){try{let i=Mm(e),n=new Set,o=new Set,a=new Set;t===q.BACKWARD&&Wm(i).forEach(d=>{n.add(d.id)});let s=Um(i,t,r),c=Bm(i,s);return s.forEach(l=>{o.add(l.id)}),c.forEach(l=>{a.add(l.id)}),{parentsWithFullProgress:n,pendingParentsWithNoLinks:o,pendingParentsWithLinks:a}}catch(i){throw i}}function Mm(e){return e.getTaskByTime().filter(bt.filterByParentType).filter(bt.avoidSubproject)}function Um(e,t,r){return e.filter(i=>{let n=i[r];if(!Array.isArray(n))return!1;let o=n.length>0,a=i.constraint_type||"",s=a!==I.FNLT;if(t===q.FORWARD){let c=a!==I.SNET;return!o&&s&&c}else return!o&&s})}function Bm(e,t){let r=new Set(t.map(i=>i.id));return e.filter(i=>!r.has(i.id))}function Wm(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function _l({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let i=new Set;return e.forEach(n=>{let o=t.getTask(n),a=Hm(r),s=Vm(r),c=o[a];if(!Array.isArray(c))return;jm(t,c,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function Hm(e){return e===q.FORWARD?Xt.SOURCE:"$target"}function Vm(e){return e===q.FORWARD?"target":"source"}function jm(e,t,r){return t.map(i=>{let o=e.getLink(i)[r];return Number(o)})}var ci={identifySecondLevelActivities:Tl,identifyInitialActivities:Dl,identifyParentsWithAndWithoutLinks:El,identifyForbiddenActivities:_l};function Rn(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function ea({linkType:e,lag:t,predecessorTime:r,activityCalendar:i,activity:n}){return e===W.FS&&t===0?Wt({predecessorTime:r,activityCalendar:i,direction:"future",activity:n}):li(r,e,i,n)}function kl({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t);return{es:R(r,n,e,i),ef:n}}function Rl({duration:e,constraintDate:t,activityCalendar:r,activity:i}){let n=new Date(t),o=R(r,n,e,i);return{es:n,ef:o}}function li(e,t,r,i){if(![W.FS,W.SS,W.FF].includes(t))return e;let o=[W.FS,W.SS].includes(t)?"future":"past";return Wt({dateBaseToCalculate:e,activityCalendar:r,direction:o,activity:i})}var ra=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=Rn(t),i=this.activity.constraint_type;return i===I.SNET?this.handleSNETConstraint(r):i===I.FNLT?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let i=r.linkType,n=Qe(i),o=r.linkLag,a=r.es,s=r.ef,c=null;if(n===W.SS)c=this.calculateSSLink({lag:o,predecessorEs:a});else if(n===W.FF)c=this.calculateFFLink({lag:o,predecessorEf:s});else if(n===W.FS)c=this.calculateFSLink({lag:o,predecessorEf:s});else if(n===W.SF)c=this.calculateSFLink({lag:o,predecessorEs:a,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=Rl({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=kl({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=ea({linkType:W.SS,lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=R(this.activityCalendar,i,t,this.activity);t>0&&(n=li(n,W.SS,this.activityCalendar,this.activity));let o=R(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateFFLink({lag:t,predecessorEf:r}){let i=ea({linkType:W.FF,lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),n=R(this.activityCalendar,i,t,this.activity),o=R(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(o=li(o,W.FF,this.activityCalendar,this.activity)),{es:o,ef:n}}calculateFSLink({lag:t,predecessorEf:r}){let i=r;t===0&&(i=Wt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let n=R(this.activityCalendar,i,t,this.activity),o=R(this.activityCalendar,n,this.activity.duration,this.activity);return{es:n,ef:o}}calculateSFLink({lag:t,predecessorEs:r}){let i=R(this.activityCalendar,r,t,this.activity),n=R(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(n=li(n,W.SF,this.activityCalendar,this.activity)),{es:n,ef:i}}},Pl=ra;var ia=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=Qe(r.linkType);if(r.type===D.TASK&&Number(r.progress)>0||r.type===D.PROJECT&&Number(r.progress)===100)continue;let n=r.linkLag,o=r.ls,a=r.lf;if(i===W.SS){let s={lag:n,workTime:o,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(s);t.push({ls:c,lf:l})}if(i===W.FF){let s={lag:n,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFFLink(s);t.push({ls:c,lf:l})}if(i===W.FS){let s={lag:n,workTime:o,lsDataCalculation:-this.activity.duration,lfDataCalculation:-n},{ls:c,lf:l}=this.calculateFsLink(s);t.push({ls:c,lf:l})}if(i===W.SF){let s={lag:n,workTime:a,lsDataCalculation:-n,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSFLink(s);t.push({ls:c,lf:l})}}if(this.activity.constraint_type===I.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:R(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 o=null,a=null;if(t===0)return o=R(this.activityCalendar,r,n,this.activity),a=R(this.activityCalendar,o,i,this.activity),{ls:a,lf:o};let s=r;return t>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,Y.PAST)),o=R(this.activityCalendar,s,n,this.activity),a=R(this.activityCalendar,o,i,this.activity),{ls:a,lf:o}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,Y.PAST);return a=R(this.activityCalendar,l,n,this.activity),a=this.getLastWorkingHour(a,this.activityCalendar,Y.PAST),s=R(this.activityCalendar,a,i,this.activity),{ls:s,lf:a}}let c=r;return o||(c=this.getLastWorkingHour(r,this.activityCalendar)),a=R(this.activityCalendar,c,n,this.activity),s=R(this.activityCalendar,a,i,this.activity),o||(a=this.getLastWorkingHour(a,this.activityCalendar,Y.PAST)),{ls:s,lf:a}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n}){let o=null,a=null,s=r;return a=R(this.activityCalendar,s,i,this.activity),o=R(this.activityCalendar,a,n,this.activity),{ls:a,lf:o}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:i,lfDataCalculation:n,isMilestone:o=!1}){let a=null,s=null;if(t===0)return s=R(this.activityCalendar,r,i,this.activity),a=R(this.activityCalendar,s,n,this.activity),{ls:s,lf:a};let c=r;return t<0&&!o&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),s=R(this.activityCalendar,c,i,this.activity),a=R(this.activityCalendar,s,n,this.activity),{ls:s,lf:a}}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:R(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,i=Y.PAST){let n=t instanceof Date?t:new Date(t),o=Yt(n).clone();return this.isActivityInInitHour(r,n)&&i===Y.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Wt({dateBaseToCalculate:new Date(o),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),o=t.getWorkHours(i)[0];if(!o||!o.includes("-"))return!1;let a=o.split("-")[0];if(!a.includes(":"))return!1;let s=a.split(":");return s.length<2?!1:(a=parseInt(s[0],10),Yt.isMoment(r)?r.hours()===a:i.getUTCHours()===a)}},Ll=ia;function Ol(e){let{parent:t,linkProperty:r,linkDirection:i,calculations:n,gantt:o,direction:a,linkCandidates:s}=e,c=t[r],l=Km(t),d=null;if(a===q.FORWARD){let u=Ym(c,i,n,o);d=new Pl(u,t,o,s),d=d.calculate()}else{let u=Gm(c,i,n,o);d=new Ll({linksWithActivityData:u,activity:t,parentData:l,gantt:o}).calculate()}return d}function Km(e){return{duration:e.duration,calendarId:e.calendar_id}}function Ym(e,t,r,i){return e.length===0?[]:e.map(n=>{let o=i.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=r.get(a);return s?{linkId:String(o.id),es:s.es,ef:s.ef,linkLag:o.lag,linkType:o.type}:(console.warn(`Calculations not found for activity: ${a}`),null)}).filter(Boolean)}function Gm(e,t,r,i){return e.length===0?[]:e.map(n=>{let o=i.getLink(n);if(!o)return console.warn(`Link not found: ${n}`),null;let a=Number(o[t]),s=r.get(a);if(!s)return null;let c=i.getTask(a);return c?{ls:s.ls,lf:s.lf,linkLag:o.lag||0,linkType:o.type,progress:c.progress,type:c.type}:null}).filter(Boolean)}function wl(e){let{activityData:t,calculations:r,singleParents:i,direction:n}=e;if($m(t.id,r))return null;let o=zm(t.id,i),a=qm(o,r);return a.length===0?null:Jm(a,n)}function $m(e,t){return t.has(e)}function zm(e,t){let r=t.get(e);return r?r.childrens:[]}function qm(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Jm(e,t){if(t===q.FORWARD){let r=Nl(e,"es"),i=bl(e,"ef");return{es:r,ef:i}}else{let r=Nl(e,"ls"),i=bl(e,"lf");return{ls:r,lf:i}}}function Nl(e,t){return e.reduce((r,i)=>i[t]<r[t]?i:r)[t]}function bl(e,t){return e.reduce((r,i)=>i[t]>r[t]?i:r)[t]}var na={parentWithLinks:Ol,parentWithNoLinks:wl};var oa=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction===q.FORWARD?"$target":Xt.SOURCE,this.linkDirection=t.direction===q.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===q.BACKWARD){let i=[I.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===q.FORWARD&&this.setDatesToParentsWithLinks(),this.direction===q.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=na.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=na.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(a=>t.includes(a[0])).map(a=>a[1]),{minEs:n,maxEf:o}=i.reduce((a,{es:s,ef:c})=>({minEs:new Date(Math.min(a.minEs.getTime(),new Date(s).getTime())),maxEf:new Date(Math.max(a.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:o}),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(a=>t.includes(a[0])).map(a=>a[1]),{minLs:n,maxLf:o}=i.reduce((a,{ls:s,lf:c})=>({minLs:new Date(Math.min(a.minLs.getTime(),new Date(s).getTime())),maxLf:new Date(Math.max(a.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:o})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let o=this.gantt.getLink(i)[r||this.linkDirection];return Number(o)})}},Fl=oa;var aa=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,o=this.getAllLevels(n),a=this.getDeepestLevel(o),s=this.createResult(r,i,a,o);this.structureOfParents.set(r.id,s)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(t){throw t}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(bt.byFirstLevel).filter(bt.filterByParentType)}processEachActivity(t){let r=new Set,i=new Set,n=new Map;return this.initializeParent(t),this.gantt.eachTask(o=>{this.processActivity(o,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 o=Number(t.id),a=Number(t.parent);i.add(o),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(a);a!=null&&c&&this.addChildToParent(a,o),this.addActivityToLevel(t,n)}isProjectActivity(t){return t.type===D.PROJECT}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let i=Number(t.id),n=t.$level,o=this.hasLink(t),a={level:n,hasLink:o,childrens:[]};r.add(i),this.singleParents.set(i,a)}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 o=r.get(i);o.has(n)||o.set(n,[]),o.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:o,parentsIds:a,allTasks:s}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:n,allParentChildrens:a,allChildrens:s,childrensByLevel:o,currentResolutionLevel:i,canBeCalculated:!1}}},xl=aa;var sa=class{constructor(t,r){this.direction=r,this.gantt=t,this.linkProperty=this.direction===q.FORWARD?"$target":Xt.SOURCE,this.linkDirection=this.direction===q.FORWARD?"source":"target",this.projectDates=t.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(t=>{let{currentResolutionLevel:r,childrensByLevel:i,isALinkedParent:n}=t;if(n)return;let o=i.get(r);for(let[a,s]of o)if(s.filter(l=>!this.calculations.has(l.id)).length===0){let l=this.gantt.getTask(a);this.calculateParentWithNoLinks(l,s);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(bt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:i}=ci.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=ci.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(i=>{let o=this.gantt.getLink(i)[r||this.linkDirection];return Number(o)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new xl({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,o=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((a,s)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(i.add(c.id),c.type===D.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===D.PROJECT,calculated:!1})}.bind(this),t.id),a({parentsIds:r,allTasks:i,activitiesByLevel:n,singleParents:o})})}identifySecondLevelActivities(){try{let t=ci.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}=ci.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===q.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===D.PROJECT)return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction===q.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(o=>{o&&n.set(o.id,o)}),n.forEach((o,a)=>{if(i.has(a))return;let s=[];(o[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(a,s)}),{graph:r,activityMap:n,calculatedActivities:i}}topologicalSort(t,r){let i=new Set,n=new Set,o=[],a=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)a(l);n.delete(s),i.add(s),o.push(s)}};for(let s of t.keys())!i.has(s)&&!r.has(s)&&a(s);return o.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let i=t,n=Number(i.progress);n==="0.00"&&(n=0);let o=this.gantt.getCalendar(i.calendar_id);if(!o)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);if((r||this.direction)===q.FORWARD){let s=i.start_date,c=i.end_date;return{es:s,ef:c}}else{if(n>=100)return{ls:Yt(i.start_date).clone(),lf:Yt(i.end_date).clone()};if(n===0)return this.calculateBackwardWhenZeroProgress(i,o);if(n<100&&n>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,o)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(t,r){let i=Yt(t.start_date).clone(),n=Yt(t.end_date).clone(),o=t.duration,a=[I.ASAP,I.ALAP,I.SNET,I.FNET],s=t.constraint_type||I.ASAP;if(a.includes(s))n=this.projectDates.end_date,i=R(r,n,-o,t);else{let c=[I.SNLT,I.MSO],l=[I.FNLT,I.MFO];c.includes(s)&&(i=t.constraint_date,n=R(r,i,o,t)),l.includes(s)&&(n=t.constraint_date,i=R(r,n,-o,t))}return{ls:i,lf:n}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,i=null,n=t.constraint_type||I.ASAP,o=this.projectDates.end_date,a=[I.ASAP,I.ALAP,I.SNET,I.FNET],s=[I.SNLT,I.FNLT];if(a.includes(n))i=Math.max(t.end_date,o);else if(n===I.MSO)i=t.end_date;else if(n===I.MFO||s.includes(n)){let c=Math.min(o,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===D.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===q.FORWARD?"es":"ls"]:i.start_date,[this.direction===q.FORWARD?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new Fl({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()}},we=sa;function Xm(e,t,r){let i={es:null,ef:null};if(!e)return i;if([I.SNET,I.SNLT].includes(t)){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if([I.FNLT,I.FNET].includes(t)){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}else if(t===I.MSO){let n=new Date(e.constraint_date);i.es=n,i.ef=R(r,n,e.duration,e)}else if(t===I.MFO){let n=new Date(e.constraint_date);i.es=R(r,n,-e.duration,e),i.ef=n}return i}var Pn=Xm;var ca=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,o=W.FS){let a=this.gantt.getCalendar(this.referenceActivity.calendar_id);if(!a)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===D.MILESTONE;return d||(o===W.FS&&n===0?s=Wt({dateBaseToCalculate:s,activityCalendar:a,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(t,o,a)),[W.FF,W.SF].includes(o)?(l=R(a,s,i,this.referenceActivity),c=R(a,l,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a))):(c=R(a,s,r,this.referenceActivity),!d&&n>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,o,a)),l=R(a,c,i,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(r.es,i,o,a,W.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(r.ef,n,o,a,W.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=t.lag||0,o=this.referenceActivity.duration,a=t.lag||0;return this.calculateSucessorTimes(r.ef,i,o,a,W.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=-this.referenceActivity.duration,o=t.lag||0,a=t.lag||0;return this.calculateSucessorTimes(r.es,n,o,a,W.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,i){if(![W.FS,W.SS,W.FF].includes(r))return t;let o=[W.FS,W.SS].includes(r)?"future":Y.PAST;return Wt({dateBaseToCalculate:t,activityCalendar:i,direction:o,activity:this.referenceActivity})}},Ml=ca;var di=class extends Ml{constructor(t){super(t)}calculate(){if(this.links.length===0)return new we(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 o=this.calculateLink(n);return this.linkCandidates?.set(String(n.id),{targetId:String(this.referenceActivity.id),...o}),o}),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,o=R(i,n,this.referenceActivity.duration,this.referenceActivity);t.push({es:n,ef:o})}return Rn(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var la=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 o=this.gantt.getTask(n);o.type===D.PROJECT?this.handleProjectActivity(n,o,r,i):this.handleNonProjectActivity(n,o,r,i)}return{activitiesThatCanBeCalculated:r,pendingActivities:i}}handleProjectActivity(t,r,i,n){let o=this.pendingParentsWithNoLinks.has(t),a=this.pendingParentsWithLinks.has(t),s=this.calculationOfParentsFromLinks.has(t);if(o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(i.add(t),n.delete(t));return}if(a&&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}a&&!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===q.FORWARD?i===I.FNLT||i===I.SNLT:i===I.FNLT)&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(a=>this.calculations.has(a))}handleNonProjectActivity(t,r,i,n){let o=Number(r.parent),a=this.pendingParentsWithLinks.has(o),s=this.calculationOfParentsFromLinks.has(o);if(a&&!s||this.direction===q.BACKWARD&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!s)return;if(r.$target.length===0&&r[Xt.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===q.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 o=n[this.linkDirection],a=this.gantt.getTask(o);a&&r.push(a)}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}},Ln=la;var da=(e,t)=>()=>t()===e;var ua=e=>!e?.fullyParsed;var Zm=16,er=async e=>performance.now()-e>Zm?(await ut(),performance.now()):e;var ui=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:i,isCalculated:n,onActivityProcessed:o,isCurrent:a})=>{let s=new Set(e),c=performance.now();for(;s.size>0;){if(!a())return;c=await er(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(s);if(l.size===0)break;for(let u of l){if(!a())return;c=await er(c),r([u])}for(let u of l){if(!a())return;i(u)&&d.add(u),o(u),n(u)&&d.delete(u)}s=d}};var pa=class extends we{constructor(t){super(t,q.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 Ln({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 ui({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===D.PROJECT)return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:r}});let n=i.$target,o=i.constraint_type||I.ASAP,a=[I.SNET,I.SNLT,I.FNLT,I.FNET],s=[I.ASAP,I.ALAP,I.SNET,I.FNET,I.SNLT,I.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,p=null;if(l===100){this.setDatesForActivityWithFullProgress(i);return}l>0&&s.includes(o)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),p=new di({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:o,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),o===I.ASAP&&this.totalFloatForAsap.set(r,{es:p.es,ef:p.ef,text:i.text})):{es:d,ef:u}=new di({links:n,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:o,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),o===I.ALAP&&this.alapMap.set(r,{es:i.start_date,ef:i.end_date,text:i.text});let f=Pn(i,o,c);if(a.includes(o)&&(this.constraintsMap.set(r,f),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(o,f,{es:d,ef:u})),[I.MSO,I.MFO].includes(o))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,f),i.progress===0)d=f.es,u=f.ef;else{let y=i.end_date;o===I.MFO&&(y=Math.max(f.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=tr.GREATER){if(i===tr.GREATER)return r.ef>t.ef?r:t;if(i===tr.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=[I.SNET,I.FNET].includes(t)?tr.GREATER:tr.LESS,{es:o,ef:a}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,i,n);return{es:o,ef:a}}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,o=i.target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===D.PROJECT)&&!(!this.gantt.getTask(o)||this.gantt.getTask(o)?.type===D.PROJECT))return r}).filter(Boolean)}},Ul=pa;var fa=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===I.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,i=0,n,o=W.FS){let a=this.gantt.getCalendar(this.activity.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`);let s=t,c=this.activity.type===D.MILESTONE;if(c&&n===0){let d=R(a,s,r,this.activity),u=R(a,d,i,this.activity);return{ls:d,lf:u}}let l={lag:n,workTime:s,activityCalendar:a,lsDataCalculation:r,lfDataCalculation:i,isMilestone:c};if(o===W.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(o===W.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(o===W.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(o===W.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,o=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(i,n,o,a,W.SS)}calculateFF(t,r){let i=this.getForwardOrBackwardCalculations(Number(t.target)),n=r===I.ALAP?"ef":"lf",o=i[n],a=-this.activity.duration,s=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(o,a,s,c,W.FF)}calculateFS(t,r){let i="ls";i=r===I.ALAP?"es":"ls";let n=this.getForwardOrBackwardCalculations(Number(t.target),r),o=-this.activity.duration,a=t.lag||0,s=-t.lag||0;return this.calculateSuccessorTimes(n[i],o,s,a,W.FS)}calculateSF(t,r=!1){let i=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,n=-t.lag||0,o=this.activity.duration,a=t.lag;return this.calculateSuccessorTimes(i,n,o,a,W.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,i){let n=Yt(r).clone();return R(t,new Date(n),i,this.activity)}getLastWorkingHour(t,r,i=Y.PAST){let n=t instanceof Date?t:new Date(t),o=Yt(n).clone();return this.isActivityInInitHour(r,n)&&i===Y.PAST&&(o=o.hours(0).minutes(0).seconds(0).milliseconds(0)),Wt({dateBaseToCalculate:new Date(o),direction:i,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let i=r instanceof Date?r:new Date(r),o=t.getWorkHours(i)[0];if(!o||!o.includes("-"))return!1;let a=o.split("-")[0];if(!a.includes(":"))return!1;let s=a.split(":");return s.length<2?!1:(a=parseInt(s[0],10),Yt.isMoment(r)?r.hours()===a:i.getUTCHours()===a)}calculateFsLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,i,Y.PAST);return s=R(i,d,o,this.activity),s=this.getLastWorkingHour(s,i,Y.PAST),c=R(i,s,n,this.activity),{ls:c,lf:s}}let l=r;return a||(l=this.getLastWorkingHour(r,i)),s=R(i,l,o,this.activity),c=R(i,s,n,this.activity),a||(s=this.getLastWorkingHour(s,i,Y.PAST,!0)),{ls:c,lf:s}}calculateFFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;if(t===0)return a=R(i,r,o,this.activity),s=R(i,a,n,this.activity),{ls:s,lf:a};let c=r;return t>0&&(c=this.getLastWorkingHour(c,i,Y.PAST)),a=R(i,c,o,this.activity),s=R(i,a,n,this.activity),{ls:s,lf:a}}calculateSSlink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o,isMilestone:a=!1}){let s=null,c=null;if(t===0)return c=R(i,r,n,this.activity),s=R(i,c,o,this.activity),{ls:c,lf:s};let l=r;return t<0&&!a&&(l=this.getLastWorkingHour(l,i,"future")),c=R(i,l,n,this.activity),s=R(i,c,o,this.activity),{ls:c,lf:s}}calculateSFLink({lag:t,workTime:r,activityCalendar:i,lsDataCalculation:n,lfDataCalculation:o}){let a=null,s=null;return t===0?(s=R(i,r,n),a=R(i,s,o,this.activity),{ls:s,lf:a}):(s=R(i,r,n,this.activity),a=R(i,s,o,this.activity),{ls:s,lf:a})}},Bl=fa;var ya=class extends Bl{constructor(t){super(t),this.constraint=t.constraint||I.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new we(this.gantt,q.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(a=>{let s=this.gantt.getLink(a);if(!s)throw new Error("Link not found",{cause:{linkId:a}});if(!this.parentsWithFullProgress.has(Number(s.target)))return this.calculateLink(s)}).filter(a=>a);if(n.length!==0){let a=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:a}}if(i){n.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,c=R(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 o=this.calculateTheLsAndLfForTheActivity();return{ls:o.ls,lf:o.lf,minFromLinks:o}}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:R(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!==D.PROJECT)return;let i=this.getSpecialCalculationParamForConstraintLink(),n=this.getSpecialParamForSf(),o=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,i),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,o),3:()=>this.calculateSF(t,n)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===I.ALAP)return I.ALAP;if(this.constraint===I.FNET||this.constraint===I.SNET)return"snet-fnet";if(this.constraint===I.FNLT)return I.FNLT}getSpecialParamForSf(){return!![I.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![I.MFO,I.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===I.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===I.SNET||this.constraint===I.SNLT||this.constraint===I.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===I.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===I.ALAP||this.constraint===I.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,o=this.activity.constraint_date;if(r===I.ASAP)return new Date(Math.max(i,n));if(r===I.FNET||r===I.FNLT){let a=Math.min(i,o);return new Date(Math.max(i,a))}if(r===I.ALAP)return new Date(Math.min(i,n))}},Wl=ya;function Qm(e,t,r){let i={ls:null,lf:null};return r===I.MSO&&(i.ls=t.constraint_date,i.lf=R(e,i.ls,t.duration,t)),r===I.MFO&&(i.lf=t.constraint_date,i.ls=R(e,i.lf,-t.duration,t)),i}var Hl=Qm;var ha=class extends we{constructor(t,r,i){super(t,q.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 Ln({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 ui({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:o,maxLf:a}=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:o,lf:a})}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,o=i.constraint_type||I.ASAP,a=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===D.PROJECT)return this.doCalculationForParentType(i);if(a===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(n,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(a>0&&a<100&&(o===I.MSO||o===I.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,o);return}if(o===I.MSO||o===I.MFO){this.recalculateInBaseRestriction(i,o);return}let{ls:s,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(n,i,o,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(o===I.SNLT||o===I.FNLT)&&({ls:s,lf:c}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:s,lf:c},o)),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 o=this.gantt.getTask(t),a=this.gantt.getCalendar(o.calendar_id);n=Pn(o,i,a)}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 o=this.gantt.getTask(n.target);o&&(o.type===D.PROJECT&&(r=!1),o.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,q.BACKWARD);if(this.calculationsOfParentThatImpactChildrens.has(r)){i=t.start_date;let o=this.calculationsOfParentThatImpactChildrens.get(r);o&&typeof o=="object"&&o.lf!=null&&(n=new Date(Math.min(n,o.lf)))}this.setCalculations(t,i,n)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===I.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===I.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,o){return new Wl({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:n,parentsThatImpactChildrens:o,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=Hl(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===D.PROJECT)&&!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type===D.PROJECT))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),i=this.calculationsOfParentThatImpactChildrens.get(r),n=0,o=0;if([I.ASAP,I.ALAP,I.SNET,I.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;o=new Date(Math.min(l,i.lf)),n=t.start_date}else o=i.lf,n=R(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t);if([I.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=R(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())),o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}if([I.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())),o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)}[I.MSO].includes(t.constraint_type)&&(n=t.constraint_date,o=R(this.gantt.getCalendar(t.calendar_id),n,t.duration,t)),[I.MFO].includes(t.constraint_type)&&(o=t.constraint_date,n=R(this.gantt.getCalendar(t.calendar_id),o,-t.duration,t));let a=this.projectDates.end_date,s=[{ls:n,lf:o}];s.push({ls:R(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t),lf:a});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}},Vl=ha;function jl(){return null}var Kl=({forward:e,backward:t,id:r,activity:i,gantt:n,projectDates:o})=>({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:o,gantt:n}});var ma=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=I.ASAP),t===I.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===I.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===I.SNET||t===I.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===I.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===I.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===I.MSO||t===I.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===I.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===I.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)})}},Yl=ma;var Ia=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===I.MSO||t===I.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=I.ASAP){let r=this.activity.$source.map(i=>{let{LINK:n,LINK_TYPE:o}=this.getLinkData(i),a=this.gantt.getTask(n.target);if(!a)return{linkId:n.id,freeFloat:null,hasProgress:!1};let s=Number(a.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(o,t,a),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(n.lag),p=Math.max(0,u);return this.linksFreeFloatObject[n.id]=p,{linkId:n.id,freeFloat:p,hasProgress:s}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=I.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(t),n=[I.SNLT,I.FNLT].includes(t)&&r===null?this.doCalculationForSnltFnlt(t,i,r):this.doGeneralCalculation(i,r);return Math.max(0,n)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=I.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,i){let n=i.constraint_type===I.ALAP,o=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:n,sucessorId:i.id,predecessorId:this.activity.id}),a=new Date,s=new Date;return a=o[t].sucessor,s=o[t].predecessor,{sucessorDateToCalculate:a,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===I.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===I.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===I.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},i=Qe(r.type);return{LINK:r,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:i,predecessorId:n}){let o=(r?this.backwardMap:this.forwardMap).get(i),a=(t===I.ALAP?this.backwardMap:this.forwardMap).get(n),s=t===I.ALAP?a?.ls:a?.es,c=t===I.ALAP?a?.lf:a?.ef;return{fs:{sucessor:o?.ls??o?.es,predecessor:c},ss:{sucessor:o?.ls??o?.es,predecessor:s},ff:{sucessor:o?.lf??o?.ef,predecessor:c},sf:{sucessor:o?.lf??o?.ef,predecessor:s}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,i=this.forwardMap.get(this.activity.id),n=t===I.MSO?i?.es:i?.ef,o=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(o))}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 o=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(i,o),o}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)}},Gl=Ia;var $l=e=>({totalFloat:new Yl(e.totalFloat).getTotalFloat(),freeFloat:new Gl(e.freeFloat).getFreeFloat()});var ga=async({activityIds:e,forward:t,backward:r,gantt:i,projectDates:n,isCurrent:o})=>{let a=performance.now(),s=new Map,c=new Map;for(let l of e){if(o&&!o())return{totalFloatMap:s,freeFloatMap:c};let d=i.getTask(l);if(!d)continue;let u=Kl({forward:t,backward:r,id:l,activity:d,gantt:i,projectDates:n}),{totalFloat:p,freeFloat:f}=$l(u);s.set(l,p),c.set(l,f),a=await er(a)}return{totalFloatMap:s,freeFloatMap:c}};var Aa=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=da(i,this.getCurrentCalculationId),o=()=>n()&&r();try{let a=t||this.gantt;if(this.gantt=a||jl(),ua(this.gantt))return!1;let s=new Ul(this.gantt);if(await s.calculateAsync(o),!o())return!1;let c=s.calculations,l=s.constraintsMap,d=new Vl(this.gantt,c,l);if(await d.calculateAsync(o),!o())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(s.linkCandidates,c,o);if(!u||!o())return!1;this.linkResidualHours=u;let{totalFloatMap:p,freeFloatMap:f}=await this.calculateFloatsAsync(s,d,o);return o()?(this.totalFloat=p,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(a){throw this.forwardPathCalculations?.size,a}}async calculateLinkResidualHours(t,r,i=()=>!0){let n=new Map,o=performance.now();for(let[a,s]of t){if(o=await er(o),!i())return null;let c=Number(s.targetId),l=this.gantt.getTask(c),d=r.get(c),u=s.ef,p=d?.ef,f=l&&this.gantt.getCalendar(l.calendar_id);if(!f||!(u instanceof Date)||!(p instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(p.getTime())){n.set(a,null);continue}let y=u.getTime(),g=p.getTime()>=y?f.calculateDuration({start_date:u,end_date:p}):-f.calculateDuration({start_date:p,end_date:u});n.set(a,Number.isFinite(g)?Object.is(g,-0)?0:g:null)}return n}async calculateFloatsAsync(t,r,i){try{let n=this.gantt.getSubtaskDates(),o=Array.from(this.forwardPathCalculations.keys());return await ga({activityIds:o,forward:t,backward:r,gantt:this.gantt,projectDates:n,isCurrent:i})}catch(n){throw this.forwardPathCalculations?.size,n}}},zl=Aa;var tI=e=>e===C.FNET||e===C.FNLT||e===C.MFO,eI=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function rI(e,t){let r=e.constraintDate;if(!r||!tI(e.constraintType))return r;let i=eI(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()?$r(e,t):r}function iI(e){let t=new Map,r=new Map,i=new Map;return{calculateEndDate:({start_date:n,duration:o})=>{let a=`${n.getTime()}|${o}`,s=t.get(a);if(s!==void 0)return new Date(s);let c=e.calculateEndDate(n,o);return t.set(a,c.getTime()),c},calculateDuration:({start_date:n,end_date:o})=>{let a=`${n.getTime()}|${o.getTime()}`,s=r.get(a);if(s!==void 0)return s;let c=e.calculateDuration(n,o);return r.set(a,c),c},getWorkHours:n=>e.getWorkHours(n),$gantt:{getClosestWorkTime:({date:n,dir:o,unit:a})=>{let s=a??"hour",c=`${n.getTime()}|${o}|${s}`,l=i.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:n,direction:o,unit:s});return i.set(c,d.getTime()),d}}}}function nI(e){let t=new Map;e.forEachActivity((n,o)=>t.set(String(o),n));let r=new Map,i=(n,o)=>{let a=r.get(n);if(a!=null)return a;let c=t.get(n)?.parentId??null,l=0;return c!==null&&!o.has(n)&&(o.add(n),l=i(String(c),o)+1),r.set(n,l),l};for(let n of t.keys())i(n,new Set);return r}function oI(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 o=1,a=s=>{let c=String(s),l=i.get(c);if(l!==void 0)return l;for(;n.has(o);)o+=1;return i.set(c,o),n.set(o,c),o++};for(let s of t)a(s);return{toLegacy:a,toCanonical:s=>typeof s=="number"?n.get(s)??null:i.has(String(s))?String(s):null}}function aI(e,t){let r=nI(e),i=new Map;return e.forEachActivity((n,o)=>{let a=String(o);i.set(a,{id:t.toLegacy(a),parent:n.parentId===null?0:t.toLegacy(n.parentId),$level:r.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),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:rI(n,e)})}),i}function sI(e){let t=new Map;for(let a of e.values()){let s=t.get(a.parent);s?s.push(a):t.set(a.parent,[a])}let r=[],i=new Set,n=[],o=a=>{if(a)for(let s=a.length-1;s>=0;s-=1)n.push(a[s])};for(o(t.get(0));n.length>0;){let a=n.pop();i.has(a)||(i.add(a),r.push(a),o(t.get(a.id)))}if(r.length<e.size)for(let a of e.values())i.has(a)||r.push(a);return r}function cI(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 ql(e,t){let r=new Map,i=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let p=e.calendarReader.getCalendar(String(l)),f=iI(p);return r.set(d,f),f},n=cI(e);await ut();let o=oI(e),a=aI(e,o);await ut();let s=[...a.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await ut();let c=sI(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=o.toCanonical(l);return d===null?null:a.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:o.toLegacy(d.source),target:o.toLegacy(d.target),lag:d.lag}:null},getCalendar:i,getChildren:l=>{let d=o.toCanonical(l);return d===null?[]:e.getChildren(d).map(o.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>s,getSubtaskDates:()=>n,getCanonicalActivityId:o.toCanonical,refreshData:()=>{}}}var Ca=1e3,lI=e=>typeof e!="number"||!Number.isFinite(e)?null:Object.is(e,-0)?0:e,dI=(e,t)=>typeof e!="number"||e<0?null:va(e,t);function uI(e){let t=dI(e.freeFloatDays,e.hoursPerDay),r=lI(e.residualHours);return{freeSlackHours:t,isCritical:r!==null&&r<=0&&e.sourceIsCritical&&e.targetIsCritical&&e.targetProgress===0}}async function pI(e,t){let r=new Map,i=0;for(let n of e.values())for(let o in n.linksFreeFloat)if(Object.hasOwn(n.linksFreeFloat,o)){if(++i>=Ca&&(i=0,await ut(),!t()))return null;r.set(String(o),n.linksFreeFloat[o])}return t()?r:null}async function fI(e,t,r,i,n){let o=new Map,a=0;for(let s of t.forward?.keys()??[]){if(++a>=Ca&&(a=0,await ut(),!n()))return null;let c=i(s);if(c===null)continue;let l=e.getActivity(c);l&&o.set(String(c),hI(s,Number(l.progress??0),t,r))}return n()?o:null}async function yI(e,t,r,i,n,o){let a=new Map,s=0;for(let c of e.getAllLinks()){if(++s>=Ca&&(s=0,await ut(),!o()))return null;a.set(String(c.id),uI({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 o()?a:null}var va=(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 hI(e,t,r,i){let n=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},o=r.forward?.get(e),a=r.backward?.get(e),s=va(r.totalFloat.get(e),i);return{criticalPath:{earlyStart:n(o?.es),earlyFinish:n(o?.ef),lateStart:n(a?.ls),lateFinish:n(a?.lf),totalSlackHours:s},isCritical:t<100&&s!==null&&s<=0,freeSlackHours:va(r.freeFloat.get(e)?.activityFreeFloat,i)}}var On=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function Sa(e,t,r){let i=e.getActivity(t),n=i?.criticalPath,o=r.criticalPath;i&&n&&On(n.earlyStart,o.earlyStart)&&On(n.earlyFinish,o.earlyFinish)&&On(n.lateStart,o.lateStart)&&On(n.lateFinish,o.lateFinish)&&Object.is(n.totalSlackHours,o.totalSlackHours)&&Object.is(i.isCritical,r.isCritical)&&Object.is(i.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function Ta(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 Da(e,t,r=()=>!0){if(!r())return null;let i=await ql(e,t);if(!r())return null;let n=new zl(i);if(!await n.calculate(i,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let a={forward:n.forwardPathCalculations,backward:n.backwardPathCalculations,totalFloat:n.totalFloat,freeFloat:n.freeFloat},s=await fI(e,a,t,i.getCanonicalActivityId,r);if(!s)return null;let c=await pI(a.freeFloat,r);if(!c)return null;let l=await yI(e,c,n.linkResidualHours,s,t,r);return l?{activities:s,links:l}:null}async function Jl(e,t,r=()=>!0){let i=await Da(e,t,r);if(!i||!r())return!1;for(let[n,o]of i.activities){if(!r())return!1;Sa(e,n,o)}for(let[n,o]of i.links){if(!r())return!1;Ta(e,n,o)}return!0}function Lr(e){let t=[],r=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let i=n=>{let o=e.getActivity(String(n));if(!o)return 0;let a=[...e.getChildren(String(n))],s;if(a.length===0){let c=Ct(o),l=c&&Number(c.cost)||0;s=(Number(o.progress)||0)/100*l}else{let c=0;for(let l of a)c+=i(String(l));s=c}return e.setActivityField(String(n),w.REAL_COST,s),r.push(String(n)),s};for(let n of t)i(n);return r}var Xl=new Set;var Zl=new Set(["activity-outdent","activity-indent"]);var pi=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),mI=new Set([h.ACTIVITY_CLIPBOARD_CLEAR,h.ACTIVITY_COPY,h.SELECTION_TOGGLE,h.SELECTION_REPLACE,h.VISIBILITY_SET,h.FILTER_SET,h.SORT_SET,h.VIEW_ATTRIBUTES_SET,h.GROUP_SET,h.WBS_DEPTH_SET,h.SIR_SYNC,h.ACTIVITY_LOOKAHEAD_SYNC,h.PERSISTENCE_ACKNOWLEDGE,h.BASELINE_APPLY,h.PONDERATOR_CRITERION_SET,h.STATUS_CRITERIA_SET]),II=new Set([h.ACTIVITY_CLIPBOARD_CLEAR,h.ACTIVITY_COPY,h.SELECTION_TOGGLE,h.SELECTION_REPLACE,h.VISIBILITY_SET,h.FILTER_SET,h.SORT_SET,h.VIEW_ATTRIBUTES_SET,h.GROUP_SET,h.WBS_DEPTH_SET]);function td(e){return!II.has(e.kind)}var gI=new Set;function AI(e){return e.kind===h.INLINE_EDIT?pi.has(e.column):e.kind===h.BULK_EDIT?e.edits.every(t=>pi.has(t.column)):!1}function Ea(e,t){return!(mI.has(e.kind)||t.has(e.kind)||AI(e))}function fi(e){return e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Ea(e,gI)}function rr(e){return e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?e.persistedProgress!==void 0:Ea(e,Xl)}function ed(e){return Ea(e,Zl)}function _a(e){return e.kind===h.ACTIVITY_SET_PROGRESS?!0:e.kind===h.INLINE_EDIT?e.column===E.PROGRESS:e.kind===h.BULK_EDIT?e.edits.some(t=>t.column===E.PROGRESS):!1}function vI(e){return ed(e)&&_a(e)}var Ql=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function CI(e){return e.kind===h.ACTIVITY_SET_PROGRESS?!0:e.kind===h.INLINE_EDIT?Ql.has(e.column):e.kind===h.BULK_EDIT?e.edits.some(t=>Ql.has(t.column)):!1}var Dt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",BASELINE_VARIANCE:"baseline-variance",CRITICAL_PATH:"critical-path"};function rd(e,t,r){let i=new Set;t.ran&&i.add(Dt.AUTOSCHEDULE),i.add(Dt.PARENT_BOUNDS),CI(e)&&i.add(Dt.PARENT_PROGRESS),_a(e)&&i.add(Dt.REAL_WORK);let n=!r.skipAutoSchedule;return n&&ed(e)&&i.add(Dt.EXPECTED_PROGRESS),n&&vI(e)&&i.add(Dt.REAL_COST),fi(e)&&i.add(Dt.BASELINE_VARIANCE),n&&rr(e)&&!r.skipCriticalPath&&i.add(Dt.CRITICAL_PATH),i}var vt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},Nn=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,pe(r)),i.dirty.add(t))}noteInsert(t){this._journal?.ops.push({kind:vt.INSERT,activityId:t})}noteRemove(t,r){this._journal?.ops.push({kind:vt.REMOVE,activityId:t,before:pe(r)})}noteLinkAdd(t){this._journal?.ops.push({kind:vt.LINK_ADD,linkId:t})}noteLinkRemove(t,r){this._journal?.ops.push({kind:vt.LINK_REMOVE,linkId:t,before:id(r)})}noteCorrelativeBefore(t,r){let i=this._journal;if(!i||i.correlativeBefore.has(t))return;let n=i.before.get(t)?.correlativeId;i.correlativeBefore.set(t,typeof n=="number"?n:r)}noteScheduledBefore(t,r){let i=this._journal;if(!i)return;let n=pe(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:vt.LINK_FIELD,linkId:t,before:id(r)}))}noteProgressFallback(t,r){let i=this._journal;!i||i.progressFallbackBefore.has(t)||i.progressFallbackBefore.set(t,r)}};function id(e){return{...e}}function ka(e,t,r){let i=[];for(let n of r){let o=e.get(n);if(!o)continue;let a=o.pendingRequestIds??[];if(dr({pendingRequestIds:a})&&t.getActivity(n)==null)for(let s of a)i.push({kind:Cn.SIR_AUTO_REJECT,activityId:n,sirId:s,reason:Sn.ACTIVITY_DELETED})}return i}function Ut(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}var Lt={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function $(e,t){let r=EI(e,t),i=new Map(t.beforeSnap),n=e.peekWriteCapture();if(n){let p=kI(n);_I(e,n,p,i,r)}let o=t.sirDetection,a=o===Lt.BEFORE_DIFF?ka(i,e,r):[],s=DI(t.correlativeShifts,r),c=await Dn(e,i,r,s),l=o===Lt.AFTER_DIFF?ka(i,e,r):a,d=t.warnings??[],u=TI(t.links??[],n?SI(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 SI(e,t){let r=[];for(let i of t.ops){if(i.kind!==vt.LINK_FIELD)continue;let n=e.getLink(i.linkId);if(!n)continue;let o={};for(let a of["freeSlackHours","isCritical"])Object.is(i.before[a],n[a])||(o[a]={before:i.before[a],after:n[a]});Object.keys(o).length!==0&&r.push({id:i.linkId,kind:b.UPDATED,fields:o,after:Ut(n)})}return r}function TI(e,t){let r=[],i=new Map;for(let n of e){let o=i.get(n.id);if(o===void 0){i.set(n.id,r.length),r.push(n);continue}let a=r[o];if((a.kind===b.UPDATED||a.kind===b.CREATED)&&n.kind===b.UPDATED){r[o]={...a,fields:{...a.fields,...n.fields},after:n.after};continue}r[o]=n}for(let n of t){let o=i.get(n.id);if(o===void 0){i.set(n.id,r.length),r.push(n);continue}let a=r[o];if(a.kind===b.DELETED)continue;let s=a.kind===b.CREATED?Object.fromEntries(Object.entries(n.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):n.fields;r[o]={...a,fields:{...a.fields,...s},after:n.after}}return r}function DI(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 EI(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 _I(e,t,r,i,n){for(let o of t.dirty){if(r.has(o)||i.has(o))continue;let a=t.before.get(o),s=e.getActivity(o);!a||!s||Object.keys(Jo(a,s)).length!==0&&(i.set(o,a),n.add(o))}}function kI(e){return new Set(e.ops.filter(t=>t.kind===vt.INSERT).map(t=>t.activityId))}function bn(e,t,r){if(!e||e==="0")return;let i=r.getChildren(e);if(i.length===0)return;let n=new Map,o=new Set,a=0;for(let l of i){let d=PI(String(l),t,r);n.set(String(l),d),a+=d,nd(String(l),r)&&o.add(String(l))}let s=a?100/a:0,c=o.size?100/o.size:0;for(let l of i){let d=r.getActivity(l);if(!d)continue;let u=RI(String(l),d,n,o,a,s,c);u!==null&&r.setActivityField(l,E.PONDERATOR,u)}}function RI(e,t,r,i,n,o,a){return t.type===D.PROJECT||Ct(t)?n?o*(r.get(e)??0):i.has(e)?a:0:!Array.isArray(t.baselinePoints)||t.baselinePoints.length===0?0:null}function nd(e,t){let r=t.getActivity(e);return r?Ct(r)?!0:r.type!==D.PROJECT?!1:t.getChildren(e).some(i=>nd(String(i),t)):!1}function PI(e,t,r){let i=r.getActivity(e);if(!i)return 0;if(i.type===D.PROJECT)return od(e,t,r);let n=Ct(i);return!n||i.type===D.MILESTONE?0:ad(n,t)}function od(e,t,r){let i=0;for(let n of r.getChildren(e)){let o=r.getActivity(n);if(!o)continue;if(o.type===D.PROJECT){i+=od(String(n),t,r);continue}let a=Ct(o);a&&o.type!==D.MILESTONE&&(i+=ad(a,t))}return i}function ad(e,t){return t===It.COST?Ra(e.cost):t===It.WORK_HOURS?Ra(e.workHours):Ra(e.durationDays)}function Ra(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}var yt={ROOTS:"roots"};async function X(e,t){bI(e);let r=xI(e.adapter),i=LI(e.adapter,t),n=FI(i,r);n.has(Dt.AUTOSCHEDULE)&&await jI(e.adapter,i);let o=n.has(Dt.AUTOSCHEDULE)?await BI(e,i.autoscheduleFrom,i.preventSummaryTargetPullback):VI();return await KI(e.adapter,i,o.scheduledIds,n,r),await GI(e,n,t.now),o}function LI(e,t){let r=OI(e,t.autoscheduleFrom);return r===t.autoscheduleFrom?t:{...t,autoscheduleFrom:r}}function OI(e,t){if(t===yt.ROOTS)return yt.ROOTS;let r=NI(e);if(r.size===0)return t;if(t!==null&&r.add(String(t)),r.size!==1)return yt.ROOTS;let[i]=r;return i===void 0||!e.activityExists(i)||e.hasChildren(i)?yt.ROOTS:i}function NI(e){let t=new Set,r=e.peekWriteCapture();if(!r)return t;for(let i of r.ops){if(i.kind===vt.LINK_REMOVE){t.add(String(i.before.target));continue}if(i.kind===vt.LINK_ADD){let n=e.getLink(i.linkId);n&&t.add(String(n.target));continue}if(i.kind===vt.LINK_FIELD){t.add(String(i.before.target));let n=e.getLink(i.linkId);n&&t.add(String(n.target))}}return t}function bI(e){let t=e.adapter.peekWriteCapture();if(!t)return;let r=new Set,i=e.sector.activityCreter??It.DURATION;for(let[n,o]of t.before){let a=e.adapter.getActivity(n);if(o.type===D.PROJECT||a?.type!==D.PROJECT||Ct(a)||!wI(n,e.adapter))continue;let s=n;for(;s!==null&&!B(s);)r.has(s)||(bn(s,i,e.adapter),r.add(s)),s=e.adapter.getParentId(s)}}function wI(e,t){let r=[...t.getChildren(e)];for(;r.length>0;){let i=r.pop();if(i===void 0)continue;let n=t.getActivity(i);if(n&&Ct(n))return!0;r.push(...t.getChildren(i))}return!1}async function sd(e,t,r){if(e.activityId!==void 0&&!r.adapter.activityExists(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let i=await Q(r.adapter,new Set(r.adapter.getAllIds()));r.scheduler.invalidateAllCaches();let n=e.activityId===void 0?r.adapter.getRootIds():[e.activityId],{scheduledIds:o}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId??yt.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await $(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function FI(e,t){let r=e.autoscheduleFrom!==null,i=!e.options.skipAutoSchedule&&r,n=new Set(rd(e.action,{requested:r,ran:i},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&n.add(Dt.PARENT_PROGRESS),n}function xI(e){let t=new Set,r=new Set,i=e.peekWriteCapture();if(!i)return{affectedParents:t,dirtySeeds:r};let n=o=>{if(o===null||B(o))return;let a=String(o);t.add(a);let s=e.getChildren(a)[0];s!==void 0&&r.add(s)};return MI(e,i.ops,n),UI(e,i.before,r,n),{affectedParents:t,dirtySeeds:r}}function MI(e,t,r){for(let i of t)if(i.kind===vt.INSERT){let n=e.getActivity(i.activityId);n&&r(n.parentId)}else i.kind===vt.REMOVE&&r(i.before.parentId)}function UI(e,t,r,i){for(let[n,o]of t){let a=e.getActivity(n);if(!a)continue;let s=!Object.is(o.progress,a.progress),c=!Object.is(o.ponderator,a.ponderator),l=!Object.is(o.parentId,a.parentId);(s||c)&&(i(a.parentId),r.add(String(n))),l&&(i(o.parentId),i(a.parentId),r.add(String(n)))}}async function BI(e,t,r=!1){let i=t===yt.ROOTS?{}:{triggerId:t};r&&(i.preventSummaryTargetPullback=!0);let n=await e.scheduler.schedule(i),o=HI(e.adapter,n.updatedIds),a=WI(e.adapter,n);return Qr(e.adapter,n),{...o,warnings:a}}function WI(e,t){let r=[];for(let i of t.plans.values()){let n=i.earliestSchedulingStart;if(!n||i.startDate>=n)continue;let o=e.getActivity(i.activityId);!o?.constraintType||!o.constraintDate||r.push({kind:qe.VIOLATION,activityId:o.id,constraintType:o.constraintType,constraintDate:o.constraintDate,projectedDate:n,messageKey:qe.VIOLATION})}return r}function HI(e,t){let r=[];for(let i of t){let n=String(i);r.push(n);let o=e.getActivity(n);o&&e.noteScheduledBefore(n,o)}return{scheduledIds:r,warnings:[]}}function VI(){return{scheduledIds:[],warnings:[]}}async function jI(e,t){let r=t.collectDirty?t.collectDirty([]):Xo(t.recomputeParentsFrom,[]);r.size!==0&&await Cr(e,r,!1)}async function KI(e,t,r,i,n){i.has(Dt.PARENT_PROGRESS)&&YI(e,n.affectedParents);let o=t.collectDirty?t.collectDirty(r):Xo(t.recomputeParentsFrom,r);for(let a of n.dirtySeeds)o.add(a);await Cr(e,o,i.has(Dt.PARENT_PROGRESS),{recomputeRealWork:i.has(Dt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function YI(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 GI(e,t,r){t.has(Dt.EXPECTED_PROGRESS)&&r!==null&&($I(e.adapter)&&Pr(e.adapter,r,e.defaultBaseCalendarId??null),Xe(e.adapter,r),ye(e.adapter,e.sector.statusCriteria)),t.has(Dt.REAL_COST)&&Lr(e.adapter),t.has(Dt.BASELINE_VARIANCE)&&Ze(e.adapter,e.sector.hoursPerDay),t.has(Dt.CRITICAL_PATH)&&await Jl(e.adapter,e.sector.hoursPerDay)}function $I(e){let t=!1;return e.forEachActivity(r=>{Ct(r)&&(t=!0)}),t}var zI=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),qI=new Set([C.MSO,C.MFO]);function Or(e){return zI.has(e)}function wn(e){return e===E.CONSTRAINT_DATE}function Fn(e,t,r,i){let n=r.getActivity(e);if(!n)return!1;let o=n.constraintType;if(!o||Pe.has(o)||qI.has(o))return!1;let a=Pa(n.startDate),s=Pa(r.getLastStartDate(e));if(!s||!a||a.getTime()!==s.getTime())return!1;let c=JI(t,o,String(n.calendarId??""),i),l=Pa(n.constraintDate);return XI(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function JI(e,t,r,i){if(e===null)return null;let n=i.getCalendar(r);return n?ue(e,n,t):e}function Pa(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 XI(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function xn(e,{postMutationArgs:t,revertTargets:r,revert:i}){let{scheduledIds:n}=await X(e,cd(t)),o=!1;for(let{activityId:a,priorConstraintDate:s}of r){let c=i(a,s);o=o||c}if(o){let a=await X(e,cd(t));n=QI(n,a.scheduledIds)}return rr(t.action)&&await X(e,ZI(t)),{scheduledIds:n}}function cd(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function ZI(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function QI(e,t){let r=new Set(e);for(let i of t)r.add(i);return[...r]}function Nr(e,t,r){let i=[];for(let{op:n,finalLinkId:o,rejected:a}of e){if(a!==null)continue;if(n.kind===Et.CREATE){if(!o)continue;let d=r.getLink(o);if(!d)continue;let u=t.get(o);if(u){let p={};String(u.source)!==String(d.source)&&(p.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(p.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(p.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(p.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(p).length>0&&i.push({id:String(o),kind:b.UPDATED,fields:p,after:Ut(d)});continue}i.push({id:String(o),kind:b.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:Ut(d)});continue}if(n.kind===Et.DELETE){if(r.getLink(n.linkId))continue;let d=t.get(n.linkId);i.push({id:String(n.linkId),kind:b.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&&String(s.source)!==String(c.source)&&(l.source={before:String(s.source),after:String(c.source)}),s&&String(s.target)!==String(c.target)&&(l.target={before:String(s.target),after:String(c.target)}),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:b.UPDATED,fields:l,after:Ut(c)})}return i}function br(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 wr(e,t,r){let i=[];if(!t.getActivity(r))return i;for(let n of t.getIncomingLinkIds(r)){let o=t.getLink(n);if(!o)continue;let a=e.get(String(o.id));a===void 0||a===Number(o.lag)||i.push({id:String(o.id),kind:b.UPDATED,fields:{lag:{before:a,after:Number(o.lag)}},after:Ut(o)})}return i}function ld(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function dd(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r,s=Oe(e.column);if(!s)return{ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN};e.column===E.DURATION&&o.invalidateExpandedLinksCache();let c=n.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let l=s.canEdit(c,n.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??S.CANNOT_EDIT,alertKey:l.alertKey};let d=s.parseInput(e.newValue,c,n);if(!d.ok)return{ok:!1,reason:d.reason??S.PARSE_ERROR};let u=Reflect.get(c,s.targetField),p=s.validate(c,u,d.value,n);if(!p.valid)return{ok:!1,reason:p.reason??S.INVALID,alertKey:p.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let v=i.getActivity(e.activityId),N=v?v.customId:null,j=typeof N=="string"?N:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),j))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let f=s.transform(c,d.value,n,d.raw),y=Ne(e.activityId,f),m=await Q(i,y),g=br(i,String(e.activityId)),_=c.constraintDate;be(i,e.activityId,f),_e(e.activityId,f.postProcessors??[],i,m.get(String(e.activityId))??null);let k=wr(g,i,String(e.activityId));if(e.column===E.CUSTOM_ID){let v=m.get(String(e.activityId)),N=v?v.customId:null,j=typeof N=="string"?N:null,K=typeof d.value=="string"?d.value:null;j!==K&&r.customIdTracker.trackCustomIdChange(j,K)}let O=()=>({action:e,autoscheduleFrom:f.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:v=>En(e.activityId,y,v),now:r.now,options:t}),T=Or(e.column),{scheduledIds:P}=await(T?xn({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:O(),revertTargets:wn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:_}],revert:(v,N)=>Fn(v,N,i,n.calendars)}):X({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},O())),M=(f.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));s.trackEvent&&!(e.column===E.PROGRESS&&Number(d.value)<=0)&&M.unshift({name:s.trackEvent,properties:{activity_name:c.name,activity_id:c.id,activity_index:c.correlativeId}});let A=Je(e.activityId,f.constraintWarning);return{ok:!0,changes:await $(i,{source:e,beforeSnap:m,touchedIds:y,scheduledIds:P,sirDetection:Lt.BEFORE_DIFF,links:k,trackingEvents:M,...A?{warnings:[A]}:{},hoursPerDay:a.hoursPerDay})}}function Mn(e){return _i(e)}function Un(e,t){return Object.hasOwn(e,t)}function tg(e){if(e.kind===h.LINK_CREATE)return Mn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE;if(e.kind===h.LINK_UPDATE){if(Un(e,"type")&&!Mn(e.type))return S.INVALID_LINK_TYPE;if(Un(e,"lag")&&!Number.isFinite(e.lag))return S.INVALID_LINK_LAG}return null}function eg(e){return e.kind===nt.CREATE?Mn(e.type)?e.lag===void 0||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:S.INVALID_LINK_TYPE:e.kind===nt.UPDATE?Un(e,"type")&&!Mn(e.type)?S.INVALID_LINK_TYPE:!Un(e,"lag")||Number.isFinite(e.lag)?null:S.INVALID_LINK_LAG:e.kind===nt.DELETE?null:S.INVALID_VALUE}function rg(e){for(let t of e){let r=eg(t);if(r!==null)return r}return null}function ig(e,t){let r=new Set,i=new Map;for(let n of e){if(n.kind===nt.CREATE){r.add(String(n.source)),r.add(String(n.target));continue}let o=t.getLink(n.linkId);o&&(r.add(String(o.source)),r.add(String(o.target)),n.kind===nt.UPDATE&&(n.source!==void 0&&r.add(String(n.source)),n.target!==void 0&&r.add(String(n.target))),i.set(n.linkId,{...o}))}return{activityIds:r,links:i}}function ng(e,t,r,i,n=!1){return e.map((o,a)=>{let s=o.kind===nt.CREATE?i?.get(a):void 0,c=Te(o,{port:t,newLinkId:s?()=>s:r.next,rejectParentLinkMutations:n});return{op:o,finalLinkId:c.applied?c.linkId:null,rejected:c.applied?null:c.rejected??S.INVALID}})}function og(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function ud(e,t,r){let i=tg(e);return i!==null?{ok:!1,reason:i}:La([ug(e,r.sector.hoursPerDay)],e,t,r,e.kind===h.LINK_CREATE&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function pd(e,t,r){let i=rg(e.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:n}=r.sector,o=e.operations.map(s=>cg(s,n)),a=ag(e.operations);return La(o,e,t,r,a)}function ag(e){let t=new Map;return e.forEach((r,i)=>{r.kind===nt.CREATE&&r.linkId&&t.set(i,r.linkId)}),t.size>0?t:void 0}function sg(e,t){if(e===void 0)return;let r=new Map,i=new Set,n=()=>{let o=t.linkIdGen.next();for(;t.adapter.getLink(o)!==null||t.isLinkIdReserved(String(o))||i.has(String(o));)o=t.linkIdGen.next();return o};for(let[o,a]of e){let s=t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||i.has(String(a)),c=s?n():a;s||t.linkIdGen.bump(a),i.add(String(c)),r.set(o,c)}return r}function cg(e,t){return e.kind===nt.CREATE?{kind:nt.CREATE,source:e.source,target:e.target,type:e.type,lag:Kt(e.lag??0,t)}:e.kind===nt.UPDATE?{kind:nt.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Kt(e.lag,t)}:{kind:nt.DELETE,linkId:e.linkId}}async function La(e,t,r,i,n){let{adapter:o,scheduler:a,sector:s,linkIdGen:c}=i;a.invalidateAllCaches();let{activityIds:l,links:d}=ig(e,o),u=await Q(o,l),p=ng(e,o,c,sg(n,i),r.rejectParentLinkMutations);if(e.length===1&&p[0]&&p[0].rejected!==null&&t.kind!==h.INLINE_EDIT)return{ok:!1,reason:p[0].rejected};let f=lg(p,d,o),{scheduledIds:y,warnings:m}=await X({adapter:o,scheduler:a,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:t,autoscheduleFrom:f,recomputeParentsFrom:l,now:i.now,options:r}),g=Nr(p,d,o);return{ok:!0,linkVerdicts:p.map((_,k)=>_.rejected===null?{operationIndex:k,kind:_.op.kind,ok:!0,linkId:String(_.finalLinkId)}:{operationIndex:k,kind:_.op.kind,ok:!1,reason:_.rejected}),__beforeLinks:og(d),changes:await $(o,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:y,links:g,warnings:m,hoursPerDay:s.hoursPerDay})}}function lg(e,t,r){for(let i of e){if(i.rejected!==null)continue;let n=dg(i.op,t,r);if(n!==null)return r.hasChildren(n)?yt.ROOTS:String(n)}return null}function dg(e,t,r){return e.kind===nt.CREATE?e.target:e.kind===nt.DELETE?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function ug(e,t){return e.kind===h.LINK_CREATE?{kind:nt.CREATE,source:e.source,target:e.target,type:e.type,lag:Kt(e.lag??0,t)}:e.kind===h.LINK_UPDATE?{kind:nt.UPDATE,linkId:e.linkId,source:e.source,target:e.target,type:e.type,lag:e.lag===void 0?void 0:Kt(e.lag,t)}:{kind:nt.DELETE,linkId:e.linkId}}async function fd(e,t,r){let{adapter:i,sector:n}=r;if(typeof e.newValue!="string")return{ok:!1,reason:S.INVALID_VALUE};if(!i.getActivity(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=e.column===E.CUSTOM_PREDECESSORS,{specs:s,errors:c}=nn(e.newValue,{daysPerWeek:n.hoursPerWeek/n.hoursPerDay});if(c.length>0)return{ok:!1,reason:S.INVALID_VALUE};let l=s.map(m=>({...m,lag:Kt(cn(m.lag),n.hoursPerDay)})),d=new Map;i.forEachActivity(m=>{m.correlativeId!=null&&d.set(String(m.correlativeId),m.id)});let u=m=>d.get(m)??null,p=a?i.getIncomingLinkIds(e.activityId):i.getOutgoingLinkIds(e.activityId),f=[];for(let m of p){let g=i.getLink(m);g&&f.push(g)}let y=a?an({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:l,resolveActivityByCorrelative:u}):sn({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:l,resolveActivityByCorrelative:u});return La(y.operations,e,t,r)}var Gt={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 kt(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(o=>{B(o.parentId)&&t.push(o)}),t.sort(md);let r=[];yd(r,t);let i=[],n=0;for(;r.length>0;){let o=r.pop();if(o.correlativeId!==n){let s=typeof o.correlativeId=="number"?o.correlativeId:void 0;i.push({activityId:String(o.id),before:s}),s!==void 0&&e.noteCorrelativeBefore?.(String(o.id),s),pg(o,n)}n+=1;let a=Jr(String(o.id),e);a.sort(md),yd(r,a)}return i}function yd(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function hd(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Lo}var md=(e,t)=>hd(e)-hd(t);function pg(e,t){e.correlativeId=t}function Oa(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:i,realWorkHours:n}=Ad(r,t);t.setActivityField(r,w.WORK_HOURS,i),t.setActivityField(r,w.REAL_WORK_HOURS,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function Id(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Oa(i,t)}function gd(e,t,r){for(let i of e){if(r.hasChildren(i))continue;let n=r.getActivity(i);n&&r.setActivityField(i,w.REAL_WORK_HOURS,Mt(yi(n,w.WORK_HOURS),yi(n,w.PROGRESS)))}for(let i of t)r.setActivityField(i,w.REAL_WORK_HOURS,Ad(i,r).realWorkHours)}function Ad(e,t){let r=0,i=0;for(let n of t.getChildren(e)){let o=t.getActivity(n);if(!o)continue;let a=yi(o,w.WORK_HOURS);r+=a,i+=fg(n,o,a,t)}return{workHours:r,realWorkHours:i}}function yi(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function fg(e,t,r,i){return i.hasChildren(e)?yi(t,w.REAL_WORK_HOURS):Mt(r,yi(t,w.PROGRESS))}function Na(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+=yg(c,w.USED_COST))}t.setActivityField(r,w.USED_COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function vd(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||Na(i,t)}function yg(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function ba(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+=hg(c,w.COST))}t.setActivityField(r,w.COST,n);let o=t.getActivity(r);if(!o)break;let a=o.parentId;if(!a||B(a))break;r=a}}function Cd(e,t){let r=t.getActivity(e);if(!r)return;let i=r.parentId;!i||B(i)||ba(i,t)}function hg(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var Bn=Object.freeze({proplannerId:null,description:"",type:D.TASK,progress:0,constraintType:C.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,baselineVarianceDays:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),Sd="New Master Plan",Td="New Activity";var mg=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Wn=new Set(mg);function Ig(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"||!Wn.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Dd(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,i=Ig(e.activityOverrides??{}),n=e.numTasksInGantt===0?Sd:Td,o=i.name??n,a=i.durationHours??e.sector.hoursPerDay,s=i.calendarId??e.sector.defaultCalendar,c=gg(r,e.fallbackStartDate,i.startDate),l={...Bn,...i,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:o,durationHours:a,calendarId:s,startDate:c,endDate:c},d=i.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:Y.FUTURE,task:l});if(!i.startDate&&r&&le(r.type)){let f=new Date(r.startDate);f.setUTCHours(0,0,0,0);let y=new Date(d);y.setUTCHours(0,0,0,0),y.getTime()!==f.getTime()&&(d=t.getClosestWorkTime({date:f,dir:Y.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:ie({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function gg(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Fr(e,t,r,i){let n=t,o=n==="0",a=wa(e,n);if(i!==void 0){let c=a.find(l=>l.id===i);if(c){let l=Ot(c),d=a.map(Ot).filter(p=>p<l);return d.length===0?l-1:(Math.max(...d)+l)/2}}if(r!==void 0){let c=a.find(l=>l.id===r);if(c){let l=Ot(c),d=a.map(Ot).filter(p=>p>l);if(d.length===0)return l+1;let u=Math.min(...d);return(l+u)/2}}return a.length===0?0:Math.max(...a.map(Ot))+1}var ir=Number.MAX_SAFE_INTEGER,Ed=Number.MAX_SAFE_INTEGER-1;function Ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:ir}function wa(e,t){return Jr(t,e)}function _d(e,t,r){let i=e,n=ae(e,r);for(;n!=null&&t.has(n);)i=n,n=ae(n,r);return i}function xr(e,t,r){let i=new Set([e]),n=zt(r.getActivity(e)?.parentId);for(;n!=="0"&&!i.has(n);){if(t.has(n))return!0;i.add(n),n=zt(r.getActivity(n)?.parentId)}return!1}function ae(e,t){let r=t.getActivity(e);if(!r)return null;let i=zt(r.parentId),n=jt(i,t),o=n.findIndex(a=>String(a)===String(e));return o<=0?null:n[o-1]??null}function kd(e,t,r,i){let n=jt(t,e).filter(c=>String(c)!==String(i)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(n.length===0)return 0;let o=n.map(Ot);if(r<=0)return o[0]-1;if(r>=o.length)return o[o.length-1]+1;let a=o[r-1],s=o[r];return(a+s)/2}var Ag=new Set([...[...Wn].filter(e=>e!==w.DURATION_HOURS),"durationDays"]);function Hn(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:S.INVALID_VALUE};for(let o of Reflect.ownKeys(e))if(typeof o=="symbol"||!Ag.has(o))return{ok:!1,reason:S.INVALID_VALUE};let{durationDays:i,...n}=e;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:S.INVALID_VALUE}:{ok:!0,value:{...n,...i===0&&(n.type===void 0||n.type===D.TASK)?{type:D.MILESTONE}:{},...i===void 0?{}:{durationHours:Ge(i,t)}}}}function wt(e,t){Oa(e,t),Na(e,t),ba(e,t)}function Vn(e,t){let r=new Set,i=[];for(let n of e){let o=String(n);r.has(o)||(r.add(o),i.push(o))}for(;i.length>0;){let n=i.pop(),o=t.getChildren(n);for(let a of o){let s=String(a);r.has(s)||(r.add(s),i.push(s))}}return r}function jn(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 vg(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 Cg(e,t,r){let i=e.startDate;return!r||!(i instanceof Date)?{}:{endDate:r(i,t)}}function Fe(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,i=Number.isFinite(r),n=vg(e.promotionSnapshot)??(i?{type:Ir,durationHours:r,progress:0,autoScheduling:!0,constraintType:C.ASAP,constraintDate:null,hasNewActivities:!1,...Cg(t,r,e.computeEndDate)}:{type:Ir});if(e.idsRemoved&&e.idsRemoved.size>0){let o=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(o.length>0){let a=o.filter(s=>!e.idsRemoved.has(s)&&!e.idsRemoved.has(String(s)));a.length!==o.length&&(n.newActivityIds=a)}}return t.hasLookaheadTasks&&(n.isLookahead=!0),{parentId:String(t.id),fields:n}}function Kn(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 Rd=200;async function Pd(e,t,r){let{adapter:i,scheduler:n,customIdTracker:o,sector:a}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};for(let v of e.activityIds)if(!i.getActivity(v))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=e.activityIds.filter(v=>{let N=i.getActivity(v);return!(N?.correlativeId===0&&N.type===D.PROJECT)}),c=Vn(s,i),l=jn(c,i),d=new Set;for(let v of e.activityIds){let N=i.getActivity(v);if(!N)continue;let j=N.parentId;if(B(j))continue;let K=String(j);c.has(K)||d.add(K)}let u=new Set([...c,...d]),p=await Q(i,u),f=new Map;for(let v of l){let N=i.getLink(v);N&&f.set(v,{...N})}let y=new Set,m=0;for(let v of c){m+=1,m%Rd===0&&await ut();let N=i.getActivity(v);if(!N)continue;let j=B(N.parentId)?null:i.getActivity(String(N.parentId)),K=j?.hasNewActivities===!0&&j.newActivityIds.some(st=>String(st)===String(v));(N.isNewActivity===!0||K)&&y.add(v);let Z=N.customId;typeof Z=="string"&&Z.length>0&&o.releaseCustomId(Z)}for(let v of l)i.removeLink(v);let g=hi(i,c),_=0;for(let v of c)_+=1,_%Rd===0&&await ut(),i.removeActivity(v);for(let v of d){let N=i.getActivity(v);if(!N)continue;Sg(N,y,i);let j=i.getChildren(v),K=Fe({parent:N,remainingChildIds:j.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(v),computeEndDate:(Z,st)=>i.calculateEndDate({startDate:Z,durationHours:st,task:N}),idsRemoved:c});if(!K){dn(v,i);continue}for(let[Z,st]of Object.entries(K.fields))Tt(i,v,Z,st);if(N.customId==null||N.customId===""){let Z=ae(v,i),st=Z?i.getActivity(Z)?.customId:null,lt=o.generateCustomIdForRestoredChild(typeof st=="string"&&st?st:null);i.setActivityField(v,w.CUSTOM_ID,lt)}}for(let v of d)wt(v,i);let k=kt(i),{scheduledIds:O}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:yt.ROOTS,recomputeParentsFrom:d,now:r.now,options:t}),T={name:Gt.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(T.properties.event_source=e.eventSource);let P=new Map;for(let[v,N]of f)P.set(v,N);let M=new Map;for(let v of c){let N=p.get(String(v));N&&M.set(String(v),N)}let A=await $(i,{source:e,beforeSnap:p,touchedIds:u,scheduledIds:O,sirDetection:Lt.AFTER_DIFF,links:Zt(f),trackingEvents:[T],hoursPerDay:a.hoursPerDay,correlativeShifts:k});return{ok:!0,changes:g.length>0?{...A,viewState:g}:A,__beforeSnap:M,__beforeLinks:P}}function Sg(e,t,r){let i=Kn({parent:e,idsRemoved:t});if(i)for(let[n,o]of Object.entries(i.fields))Tt(r,i.parentId,n,o)}function hi(e,t){let r=[];for(let i of t){let n=e.isChecked(i),o=e.isVisible(i);!n&&o||r.push({activityId:String(i),...n?{checked:{before:!0,after:!1}}:{},...o?{}:{visible:{before:!1,after:!0}}})}return r}function Zt(e){let t=[];for(let[r,i]of e.entries())t.push({id:r,kind:b.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}var Mr={CREATE:"create",REPARENT:"reparent"};function Tg(e){let t=e.type;if(t!==D.TASK&&t!==D.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 Ld(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ce(t.type):Dg(t),i=Array.isArray(t.newActivityIds)?t.newActivityIds:[],o={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(a=>String(a)===String(e.newChildId))?[...i]:[...i,e.newChildId]};return t.customId!=null&&t.customId!==""&&(o.customId=null),r&&(o.type=xo,(e.promotionSource??Mr.CREATE)===Mr.CREATE&&(o.constraintType=C.ASAP,o.constraintDate=null)),{parentId:e.parentId,fields:o,promotionSnapshot:Tg(t)}}function Dg(e){return Ce(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function xe(e,t){let i=t.adapter.getActivity(e.parentId)?.customId??null,n=Ld({...e,getParent:a=>t.adapter.getActivity(a)??null});if(!n)return{applied:!1,removedLinks:new Map};let o=n.fields.type===D.PROJECT?Eg(e.parentId,t):new Map;for(let[a,s]of Object.entries(n.fields))Tt(t.adapter,n.parentId,a,s);return n.promotionSnapshot&&t.adapter.setPromotionSnapshot(n.parentId,n.promotionSnapshot),n.fields.customId===null&&t.customIdTracker.releaseCustomId(i),{applied:!0,removedLinks:o}}function Eg(e,t){let r=new Map,i=new Set([...t.adapter.getIncomingLinkIds(e),...t.adapter.getOutgoingLinkIds(e)]);for(let n of i){let o=t.adapter.getLink(n);o&&(r.set(String(n),{...o}),t.adapter.removeLink(n))}return r}async function mi(e,t,r={}){let{adapter:i,scheduler:n,sector:o,calendars:a,activityIdGen:s,uidGen:c}=t;r.skipCacheInvalidation||n.invalidateAllCaches();let l=_g(e,i);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:p}=l,f=Rg(e.activityId,i,s,t.isActivityIdReserved),y=c.next(),m={id:f,parentId:p?null:e.parentId,sector:{id:o.id,hoursPerDay:o.hoursPerDay,defaultCalendar:bg(a)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:e.overrides??{}},_=Dd(m,{getActivity:v=>i.getActivity(v),calculateEndDate:v=>i.calculateEndDate(v),getClosestWorkTime:v=>i.getClosestWorkTime(v)}).newTask;_.realWorkHours=Mt(_.workHours,_.progress),Lg(_,e,t,u,d,r);let k=r.insertionCorrelativeId??Fr(i,p?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);_.correlativeId=k;let O=new Set([f]);d&&O.add(d.id);let T=d!==null&&i.getChildren(d.id).length===0,P=r.skipBeforeSnap?new Map:await Q(i,O);i.addActivity(_);let M=d?xe({parentId:d.id,newChildId:f,isCurrentlyLeaf:T},t).removedLinks:new Map;r.skipRollupCascades||(Id(f,i),vd(f,i),Cd(f,i));let A=Og(i,f,O,r);return{ok:!0,newId:f,parent:d,newActivity:_,beforeSnap:P,initialTouched:O,correlativeShifts:A,removedParentLinks:M}}function _g(e,t){let r=B(e.parentId),i=r?null:t.getActivity(e.parentId);if(!r&&!i)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(i!==null&&dr(i))return{ok:!1,reason:S.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let a=e.afterSiblingId??e.beforeSiblingId,s=kg(e,t,r,a);return s||{ok:!0,parent:i,anchorSiblingId:a,isRoot:r}}function kg(e,t,r,i){if(i===void 0)return null;let n=t.getActivity(i);if(!n)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};let o=r?"0":e.parentId;return(n.parentId==null?"0":String(n.parentId))!==o?{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}:null}function Rg(e,t,r,i){let n=()=>{let o=r.next();for(;t.activityExists(o)||i(String(o));)o=r.next();return o};return e===void 0||t.activityExists(e)||i(String(e))?n():(r.bump(e),e)}function Pg(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Lg(e,t,r,i,n,o){let{adapter:a,customIdTracker:s}=r,c=Pg(t);if(c!==void 0){if(c.length===0)return;if(!s.isCustomIdInUse(c)){s.registerCustomId(c);return}}let l=o.customIdReferenceId??i,d=l!==void 0,u=d?a.getActivity(l):n;e.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Og(e,t,r,i){if(i.skipCorrelativeRecompute)return[];let n=kt(e).filter(o=>o.activityId!==String(t));for(let o of n)r.add(o.activityId);return n}async function Ng(e,t,r,i,n){let{newId:o,newActivity:a,beforeSnap:s,initialTouched:c,correlativeShifts:l,removedParentLinks:d}=r,u={name:Gt.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:o,created_duration:a.durationHours}};return t.eventSource!==void 0&&(u.properties.event_source=t.eventSource),$(e,{source:t,beforeSnap:s,touchedIds:c,scheduledIds:i,correlativeShifts:l,trackingEvents:[u],links:Zt(new Map(d)),hoursPerDay:n})}async function Od(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=Hn(e.overrides,o.hoursPerDay);if(!a.ok)return a;let s=await mi({...e,overrides:a.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 X({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 Ng(i,e,s,u,o.hoursPerDay),...s.removedParentLinks.size>0?{__beforeLinks:new Map(s.removedParentLinks)}:{}}}function bg(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"}async function wd(e,t,r){let i=wg(e,r);if(i)return{ok:!1,reason:i};let n=xg(e,r);if(!n.ok)return n;let o=e.mode===mt.REPLACE?new Set(r.adapter.getAllIds().map(T=>String(T))):new Set,a=e.mode===mt.REPLACE?await Q(r.adapter,o):new Map,s=e.mode===mt.REPLACE?Vg(r):new Map,c=e.mode===mt.REPLACE?hi(r.adapter,o):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode===mt.REPLACE){for(let T of s.keys()){let P=Te({kind:nt.DELETE,linkId:T},{port:r.adapter});if(!P.applied)return{ok:!1,reason:P.rejected??S.INVALID};l.push({op:{kind:nt.DELETE,linkId:T},finalLinkId:T,rejected:null})}for(let T of o){let P=r.adapter.getActivity(T)?.customId;typeof P=="string"&&P.length>0&&r.customIdTracker.releaseCustomId(P),r.adapter.removeActivity(T)}}let d=await Hg(e,n.plan.items,r);if(!d.ok)return d;for(let[T,P]of d.removedParentLinks)s.set(T,P),l.push({op:{kind:nt.DELETE,linkId:T},finalLinkId:T,rejected:null});let u=Fd(e)?[]:kt(r.adapter),p=new Set(n.plan.items.map(T=>String(T.activityId))),f=u.filter(T=>!p.has(T.activityId)),y=e.mode===mt.REPLACE?new Set(o):new Set;kr(r.adapter,u,p,a,y);for(let T of n.plan.items)y.add(String(T.activityId));let m=n.plan.links.map(T=>({operation:{kind:nt.CREATE,source:T.source,target:T.target,type:T.type,lag:Kt(T.lag??0,r.sector.hoursPerDay)},linkId:T.linkId})),g=tn(m,{port:r.adapter,preserved:s,rejectParentLinkMutations:t.rejectParentLinkMutations??!1});if(!g.applied)return{ok:!1,reason:g.rejected??S.INVALID};for(let{operation:T,linkId:P}of m)l.push({op:T,finalLinkId:P,rejected:null});let _=n.plan.items.map(T=>T.activityId),{scheduledIds:k}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?yt.ROOTS:null,recomputeParentsFrom:_,now:r.now,options:t}),O=await $(r.adapter,{source:e,beforeSnap:a,touchedIds:y,scheduledIds:k,links:Nr(l,s,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:f,...e.mode===mt.REPLACE?{sirDetection:Lt.AFTER_DIFF}:{}});return{ok:!0,changes:c.length>0?{...O,viewState:c}:O,...e.mode===mt.REPLACE||s.size>0?{...e.mode===mt.REPLACE?{__beforeSnap:a}:{},__beforeLinks:jg(s)}:{}}}function wg(e,t){if(e.mode!==mt.APPEND&&e.mode!==mt.REPLACE)return S.INVALID;let r=new Set,i=new Set;for(let o of e.items){if(o.batchId.length===0||r.has(o.batchId))return S.INVALID;if(r.add(o.batchId),o.index!==void 0&&(!Number.isInteger(o.index)||o.index<0))return S.INVALID;if(o.activityId!==void 0){let a=String(o.activityId);if(a.length===0||a==="0"||i.has(a))return S.INVALID;i.add(a)}}for(let o of e.items)if(!xa(o.parent,!0,e.mode,r,t))return S.PARENT_NOT_FOUND;if(Fg(e.items))return S.INVALID;let n=new Set;for(let o of e.links){if(!Object.values(H).includes(o.type))return S.INVALID_LINK_TYPE;if(o.lag!==void 0&&!Number.isFinite(o.lag))return S.INVALID_LINK_LAG;if(!xa(o.source,!1,e.mode,r,t)||!xa(o.target,!1,e.mode,r,t))return S.ACTIVITY_NOT_FOUND;if(o.linkId!==void 0){let a=String(o.linkId);if(a.length===0||n.has(a))return S.INVALID;n.add(a)}}return null}function xa(e,t,r,i,n){return typeof e=="string"?e==="0"?t:r===mt.APPEND&&n.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&i.has(e.batchId)}function Fg(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,o=i.batchId;for(;o!==void 0&&!r.has(o);){if(n.has(o))return!0;n.add(o),o=t.get(o)}for(let a of n)r.add(a)}return!1}function xg(e,t){let r=new Map;for(let d of e.items){let u=Hn(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=Mg(d.activityId,e.mode,n,t);n.add(String(u)),i.set(d.batchId,u)}let o=new Set,a=e.links.map(d=>{let u=Ug(d.linkId,e.mode,o,t);return o.add(String(u)),u}),s=Bg(e,i,t),c=[];for(let d of e.items){let u=i.get(d.batchId),p=s.get(d.batchId);if(u===void 0||p===void 0)return{ok:!1,reason:S.INVALID};let f=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:S.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:y,parentBatchId:f,insertionCorrelativeId:p,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let p=bd(u.source,i),f=bd(u.target,i),y=a[d];if(p===null||f===null||y===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};l.push({source:p,target:f,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:c,links:l}}}function Mg(e,t,r,i){if(e!==void 0&&(t===mt.REPLACE||i.adapter.getActivity(e)===null&&!i.isActivityIdReserved(String(e)))&&!r.has(String(e)))return i.activityIdGen.bump(e),e;let o=i.activityIdGen.next();for(;r.has(String(o))||t===mt.APPEND&&(i.adapter.getActivity(o)!==null||i.isActivityIdReserved(String(o)));)o=i.activityIdGen.next();return o}function Ug(e,t,r,i){if(e!==void 0&&(t===mt.REPLACE||i.adapter.getLink(e)===null&&!i.isLinkIdReserved(String(e)))&&!r.has(String(e)))return i.linkIdGen.bump(e),e;let o=i.linkIdGen.next();for(;r.has(String(o))||t===mt.APPEND&&(i.adapter.getLink(o)!==null||i.isLinkIdReserved(String(o)));)o=i.linkIdGen.next();return o}function Bg(e,t,r){if(Fd(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===mt.REPLACE||typeof s.parent!="string"&&t.has(s.parent.batchId)?[]:wa(r.adapter,d).sort((m,g)=>Ot(m)-Ot(g)||String(m.id).localeCompare(String(g.id))).map(m=>String(m.id)),newIdsByTarget:new Map},n.set(d,u));let p=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),f=u.newIdsByTarget.get(p)??[];f.push(String(c)),u.newIdsByTarget.set(p,f)}let o=new Map,a=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 p of s.newIdsByTarget.get(d)??[])c.push(p);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,p=d>0?Nd(c[d-1],r):null,f=l<c.length?Nd(c[l],r):null;for(let y=0;y<u;y+=1){let m=c[d+y],g=a.get(m);g!==void 0&&o.set(g,Wg(p,f,y+1,u))}}}return o}function Fd(e){return e.mode===mt.APPEND&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Nd(e,t){let r=t.adapter.getActivity(e);return r?Ot(r):0}function Wg(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 Hg(e,t,r){let i=new Map,n=new Map,o=[];for(let s of t){if(s.parentBatchId===null){o.push(s);continue}let c=i.get(s.parentBatchId)??[];c.push(s),i.set(s.parentBatchId,c)}for(let s=0;s<o.length;s+=1){let c=o[s],l=await mi({kind:h.ACTIVITY_CREATE,parentId:c.parentId,activityId:c.activityId,overrides:c.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:c.insertionCorrelativeId});if(!l.ok)return l;for(let[d,u]of l.removedParentLinks)n.set(d,u);for(let d of i.get(c.input.batchId)??[])o.push(d)}if(o.length!==t.length)return{ok:!1,reason:S.INVALID};let a=new Set;for(let s=o.length-1;s>=0;s-=1){let c=o[s].parentId;c==="0"||a.has(String(c))||(a.add(String(c)),wt(c,r.adapter))}return{ok:!0,removedParentLinks:n}}function bd(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Vg(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function jg(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function xd(e,t){let{adapter:r}=t,i=e.activityId,n=r.getActivity(i);if(!n)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=n.pendingRequestIds??[],a=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",a);let s=r.getActivity(i);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c={id:i,kind:b.UPDATED,fields:{pendingRequestIds:{before:o,after:a}},after:it(s)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Md(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 Ud(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 Kg(e,t,r,i,n,o){let a=String(e.id);if(a.length===0||n.has(a))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${a}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(o.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let s=r(a);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${a}"`);if(s.current!==null&&s.current!==0&&s.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${a}" already has proplannerId ${String(s.current)}`);let c=i.get(e.proplannerId);if(c!==void 0&&c!==a)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);n.add(a),o.add(e.proplannerId)}function Bd(e,t,r,i){let n=new Set,o=new Set;for(let a of e)Kg(a,t,r,i,n,o)}async function Wd(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=ni(t.adapter,i),o=new Set(i);for(let s of n)o.add(String(s));let a=await Q(t.adapter,o);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",Ke(s.progress))}Mc(n,t.adapter),gd(i,n,t.adapter)}),[...await Dn(t.adapter,a,o)]}async function Hd(e,t){let r=e.activities??[],i=e.links??[],n=t.adapter.getAllActivities(),o=t.adapter.getAllLinks(),a=e.checkpoint?.activities??n,s=e.checkpoint?.links??o,c=new Map(a.map(y=>[String(y.id),y])),l=new Map(s.map(y=>[String(y.id),y])),d=Md(a),u=Md(s);Bd(r,"activity",y=>{let m=c.get(y);return{exists:m!==void 0,current:m?.proplannerId??null}},d),Bd(i,"link",y=>{let m=l.get(y);return{exists:m!==void 0,current:m?.proplannerId??null}},u),Ud(a,r,"activity"),Ud(s,i,"link");let p=[],f=[];return t.adapter.batchUpdate(()=>{for(let y of r){let m=t.adapter.getActivity(y.id);if(!m||m.proplannerId===y.proplannerId)continue;let g=m.proplannerId;t.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),p.push({id:y.id,kind:b.UPDATED,fields:{proplannerId:{before:g,after:y.proplannerId}},after:{...m,proplannerId:y.proplannerId}})}for(let y of i){let m=t.adapter.getLink(y.id);if(!m||m.proplannerId===y.proplannerId)continue;let g=m.proplannerId;t.adapter.setLinkProplannerId(y.id,y.proplannerId),f.push({id:y.id,kind:b.UPDATED,fields:{proplannerId:{before:g,after:y.proplannerId}},after:{...m,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:e,activities:p,links:f,calendars:[],trackingEvents:[]}}}async function Vd(e,t,r){if(Yg(e))return{ok:!1,reason:S.INVALID_VALUE};let i=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&i.some(s=>!r.isActivityIdReserved(s)))return{ok:!1,reason:S.INVALID};let o=i.map(s=>r.adapter.getActivity(s));if(o.some(s=>!s))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=[];for(let[s,c]of i.entries()){let l=o[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&&a.push({id:c,kind:b.UPDATED,fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await Wd([{activityId:i[0],progress:e.persistedProgress}],r)).length>0?(await X({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 $(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:a,links:[],calendars:[],trackingEvents:[]}}}function Yg(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function Ua(e,t){let{adapter:r}=t,i=new Set(e.conversionRootIds.map(p=>String(p)));if(i.size===0)throw new Error("Conversion requires at least one root");for(let p of i)eA(p,r);let n=r.getVisualOrderIds().filter(p=>i.has(p)&&!xr(p,i,r)),o=n.map(p=>Gg(p,r)),a=o.map(({conversionRootId:p,convertedActivities:f})=>({conversionRootId:p,convertedActivities:f})),s=o.flatMap(p=>p.milestoneMoves),c=o.flatMap(p=>p.activityIdsToDelete),l=o.map(p=>p.formerParent),d=new Set(c),u=jn(d,r);return{sourceStateRevision:t.stateRevision,conversionRootIds:n,conversionGroups:a,milestoneMoves:s,activityIdsToDelete:c,linkIdsToDelete:u,formerParents:l}}async function Yd(e,t,r){if(e.expectedStateRevision!==r.stateRevision)return{ok:!1,reason:S.STALE_STATE_REVISION};let i=Ua(e,r);if(!rA(i,r.adapter))return{ok:!1,reason:S.HIERARCHY_CYCLE};let{adapter:n,scheduler:o}=r;o.invalidateAllCaches();let a=await Jg(i,n);Xg(i,r),Gd(i,n),Zg(i,a.deletedIds,n);let s=Qg(i,n);kr(n,s,a.deletedIds,a.beforeSnap,a.touchedIds);let{scheduledIds:c}=await X({adapter:n,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:a.touchedIds,now:r.now,options:t,recomputeParentProgress:!0}),l=await $(n,{source:e,beforeSnap:a.beforeSnap,touchedIds:a.touchedIds,scheduledIds:c,sirDetection:"after-diff",links:Zt(a.beforeLinks),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:s});return tA(i,a,l)}function Gg(e,t){let r=Ma(e,t),i=Vn([e],t);if(i.delete(e),i.size===0)throw new Error(`Conversion root ${e} has no descendants`);let n=t.getVisualOrderIds().filter(c=>i.has(c)).map(c=>Ma(c,t));Kd(r);for(let c of n)Kd(c);let o=n.filter(c=>c.type!==D.MILESTONE),a=n.filter(c=>c.type===D.MILESTONE),s=$g(r,o);return{conversionRootId:e,convertedActivities:o.map(c=>zg(c,s)),milestoneMoves:qg(r,a),activityIdsToDelete:o.map(c=>c.id),formerParent:{activity:it(r),hasConvertedActivities:o.length>0}}}function $g(e,t){let r=new Map;t.length>0&&r.set(e.id,jd(e));for(let i of t)r.set(i.id,jd(i));return r}function zg(e,t){let r=it(e),i=zt(e.parentId),n=t.get(i);return r.parentId=n===void 0?null:String(n),r}function qg(e,t){let r=[],i=zt(e.parentId),n=e.id;for(let o of t)r.push({activityId:o.id,parentId:i,afterSiblingId:n}),n=o.id;return r}async function Jg(e,t){let r=new Set(e.activityIdsToDelete),i=new Set([...e.conversionRootIds,...e.activityIdsToDelete,...e.milestoneMoves.map(({activityId:n})=>n),...e.milestoneMoves.map(({parentId:n})=>n).filter(n=>n!=="0")]);return{deletedIds:r,touchedIds:i,beforeSnap:await Q(t,i),beforeLinks:iA(e.linkIdsToDelete,t),viewStateChanges:hi(t,r)}}function Xg(e,t){for(let r of e.activityIdsToDelete){let i=t.adapter.getActivity(r)?.customId;i&&t.customIdTracker.releaseCustomId(i)}}function Gd(e,t){for(let r of e.milestoneMoves)t.setActivityFields(r.activityId,{parentId:r.parentId,correlativeId:Fr(t,r.parentId,r.afterSiblingId,void 0)});for(let r of e.linkIdsToDelete)t.removeLink(r);for(let r of[...e.activityIdsToDelete].reverse())t.removeActivity(r);for(let{activity:r}of e.formerParents)t.setActivityField(r.id,w.TYPE,D.TASK)}function Zg(e,t,r){for(let{activity:i,hasConvertedActivities:n}of e.formerParents){let o=Ma(i.id,r),a=Kn({parent:o,idsRemoved:t});r.setActivityFields(i.id,{isLookahead:i.isLookahead||n,hasLookaheadTasks:i.hasLookaheadTasks||n,...a?.fields??{}})}}function Qg(e,t){for(let{activity:r}of e.formerParents)wt(r.parentId,t);return kt(t)}function tA(e,t,r){let i=new Map;for(let n of t.deletedIds){let o=t.beforeSnap.get(n);o&&i.set(n,o)}return{ok:!0,changes:t.viewStateChanges.length===0?r:{...r,viewState:t.viewStateChanges},conversionGroups:e.conversionGroups.map(({conversionRootId:n,convertedActivities:o})=>({conversionRootId:n,convertedActivities:o.map(a=>it(a))})),__beforeSnap:i,__beforeLinks:t.beforeLinks}}function eA(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion root ${e} was not found`);if(r.type===D.PROJECT&&r.correlativeId===0)throw new Error(`Conversion root ${e} is the visual project root`)}function Ma(e,t){let r=t.getActivity(e);if(!r)throw new Error(`Conversion activity ${e} is missing`);return r}function jd(e){if(e.proplannerId==null)throw new Error(`Conversion activity ${e.id} has no persisted identifier`);return e.proplannerId}function Kd(e){if(!Number.isFinite(e.startDate.getTime()))throw new Error(`Conversion activity ${e.id} has invalid startDate`);if(!Number.isFinite(e.endDate.getTime()))throw new Error(`Conversion activity ${e.id} has invalid endDate`)}function rA(e,t){let r=t.fork();return Gd(e,r),Se({port:t,proposedPort:r,currentLinks:t.getAllLinks(),proposedLinks:r.getAllLinks()}).ok}function iA(e,t){let r=new Map;for(let i of e){let n=t.getLink(i);n&&r.set(i,{...n})}return r}function Ur(e,t){let r=new Set;for(let n of e)r.add(String(n));let i=[];for(let n of t.getAllLinks()){let o=String(n.source),a=String(n.target);!r.has(o)&&!r.has(a)||zd(n,t)&&i.push(String(n.id))}return i}function zd(e,t){let r=String(e.source),i=String(e.target);return $d(i,r,t)||$d(r,i,t)}function Yn(e,t){return[...e].filter(([,r])=>zd(r,t)).map(([r])=>String(r))}function $d(e,t,r){let i=String(e),n=new Set;for(;i!=null;){if(n.has(i))return!1;n.add(i);let o=r.getActivity(i);if(!o)return!1;let a=o.parentId;if(a===null||B(a))return!1;let s=a;if(s===t)return!0;i=s}return!1}function Gn(e,t){let r=e.getAllLinks();return!Se({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function $n(e,t){let r=new Set;if(e.length===0)return r;let i=new Map(e.map(o=>[o.activityId,o.newParentId]));if(!Gn(t,i))return r;let n=new Map;for(let o of e){let a=new Map(n);if(a.set(o.activityId,o.newParentId),Gn(t,a)){r.add(o.activityId);continue}n.set(o.activityId,o.newParentId)}return r}async function qd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;n.invalidateAllCaches();let a=i.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=B(e.parentId);if(!s&&!i.getActivity(e.parentId))return{ok:!1,reason:S.PARENT_NOT_FOUND};if(!s&&(e.parentId===e.activityId||i.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:S.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let A=i.getActivity(c);if(!A)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};if((A.parentId===null?"0":String(A.parentId))!==e.parentId)return{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}}let l=a.parentId,d=zt(l),u=String(e.parentId),p=d!==u;if(p){let A=new Map([[e.activityId,s?null:e.parentId]]);if(Gn(i,A))return{ok:!1,reason:S.HIERARCHY_CYCLE}}let f=new Set([e.activityId]);p?(d!=="0"&&f.add(d),u!=="0"&&f.add(u)):d!=="0"&&f.add(d);let y=await Q(i,f),m=new Map;p&&i.setActivityField(e.activityId,w.PARENT,u);let g=Fr(i,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(i.setActivityField(e.activityId,w.CORRELATIVE_ID,g),p){if(!s){let A=i.getActivity(e.parentId);if(A){let v=Ce(A.type)&&i.getChildren(e.parentId).filter(j=>j!==e.activityId).length===0,N=xe({parentId:e.parentId,newChildId:e.activityId,isCurrentlyLeaf:v,promotionSource:Mr.REPARENT},r);if(N.applied)for(let[j,K]of N.removedLinks)m.set(j,K)}}if(d!=="0"){let A=i.getActivity(d);if(A){let v=i.getChildren(d),N=Fe({parent:A,remainingChildIds:v.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(j,K)=>i.calculateEndDate({startDate:j,durationHours:K,task:A}),idsRemoved:new Set([e.activityId])});if(N){for(let[lt,dt]of Object.entries(N.fields))Tt(i,d,lt,dt);let j=ae(d,i),K=j?i.getActivity(j)?.customId:null,Z=typeof K=="string"&&K?K:null,st=r.customIdTracker.generateCustomIdForRestoredChild(Z);i.setActivityField(d,w.CUSTOM_ID,st)}}}}p&&(d!=="0"&&wt(d,i),s||wt(e.parentId,i));let _=kt(i);for(let A of _){if(f.add(A.activityId),y.has(A.activityId))continue;let v=i.getActivity(A.activityId);if(!v)continue;let N=it(v);A.before!==void 0&&(N.correlativeId=A.before),y.set(A.activityId,N)}let k=p&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:O}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...k],now:r.now,options:t,recomputeParentProgress:p}),T=p?Ur([e.activityId],i):[],P=Yn(m,i),M={name:Gt.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:[...new Set([...P,...T.map(String)])]}};return e.eventSource!==void 0&&(M.properties.event_source=e.eventSource),{ok:!0,changes:await $(i,{source:e,beforeSnap:y,touchedIds:f,scheduledIds:O,sirDetection:Lt.BEFORE_DIFF,links:Zt(m),trackingEvents:[M],hoursPerDay:o.hoursPerDay}),...m.size>0?{__beforeLinks:m}:{}}}function zn(e,t){let r=new Set(e),i=[],n=[],o=new Set,a=new Set(r),s=[...e].sort((d,u)=>{let p=t.getActivity(d),f=t.getActivity(u),y=p?Ot(p):ir,m=f?Ot(f):ir;return y-m});for(let d of s){if(!t.getActivity(d)){i.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),a.delete(d);continue}if(xr(d,o,t))continue;let p=rc(d,a,t);if(p==null){i.push({activityId:d,reason:S.INDENT_NO_ELIGIBLE_SIBLING}),a.delete(d);continue}let f=t.getActivity(d)?.parentId,y=B(f)?"0":String(f);n.push({activityId:d,newParentId:p,oldParentId:y}),o.add(d)}let c=$n(n,t);for(let d of c)i.push({activityId:d,reason:S.HIERARCHY_CYCLE});let l=n.filter(d=>!c.has(d.activityId));return{moves:n,cyclicMoveIds:c,allowedMoves:l,failed:i}}async function Jd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set,s=[],c=zn(e.activityIds,i),l=[...c.failed];for(let P of c.moves)a.add(String(P.activityId)),a.add(String(P.newParentId)),P.oldParentId!=="0"&&a.add(String(P.oldParentId));let d=c.allowedMoves,u=await Q(i,a);for(let{activityId:P,newParentId:M}of d)i.setActivityField(P,w.PARENT,M),i.setActivityField(P,w.CORRELATIVE_ID,Ed),s.push(P);let p=new Set,f=new Map;for(let{activityId:P,newParentId:M}of d){if(p.has(M))continue;p.add(M);let A=i.getActivity(M);if(!A)continue;let v=A.customId,N=Ce(A.type)&&i.getChildren(M).filter(Z=>!s.includes(Z)).length===0,j=A.hasNewActivities&&A.newActivityIds.some(Z=>String(Z)===String(P)),K=xe({parentId:M,newChildId:P,isCurrentlyLeaf:N,promotionSource:Mr.REPARENT},r);if(K.applied){for(let[Z,st]of K.removedLinks)f.set(Z,st);j||(i.setActivityField(M,w.HAS_NEW_ACTIVITIES,!1),i.setActivityField(M,w.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(M,w.CONSTRAINT_TYPE,C.ASAP),i.setActivityField(M,w.CONSTRAINT_DATE,null),i.setActivityField(M,w.CUSTOM_ID,null),K.applied||ld(v,r.customIdTracker)}let y=new Set;for(let P of d)P.oldParentId!=="0"&&y.add(P.oldParentId),y.add(P.newParentId);for(let P of y)wt(P,i);let m=kt(i);for(let P of m){if(a.add(P.activityId),u.has(P.activityId))continue;let M=i.getActivity(P.activityId);if(!M)continue;let A=it(M);P.before!==void 0&&(A.correlativeId=P.before),u.set(P.activityId,A)}let g=Yn(f,i),_=Ur(s,i);for(let P of _){let M=i.getLink(P);M&&(f.set(P,{...M}),i.removeLink(P))}let{scheduledIds:k}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:s,now:r.now,options:t}),O={name:Gt.ACTIVITY_INDENT,properties:{activity_ids:s,failed:l.map(P=>({activity_id:P.activityId,reason:P.reason})),invalid_link_ids:[...new Set([...g,..._.map(String)])]}};e.eventSource!==void 0&&(O.properties.event_source=e.eventSource);let T=await $(i,{source:e,beforeSnap:u,touchedIds:a,scheduledIds:k,links:Zt(f),trackingEvents:[O],hoursPerDay:o.hoursPerDay});return{ok:!0,activityVerdicts:e.activityIds.map(P=>{let M=l.find(A=>String(A.activityId)===String(P));return M?{activityId:String(P),ok:!1,reason:M.reason}:{activityId:String(P),ok:!0}}),changes:T,__beforeLinks:f}}async function Xd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;if(n.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let a=new Set(e.activityIds),s=new Map,c=new Map;for(let A of e.activityIds){let v=A;i.getActivity(v)&&(s.set(v,Oo(v,i)),c.set(v,_d(v,a,i)))}let l=new Set,d=[],u=[],p=new Set,f=[],y=new Set,m=[...e.activityIds].sort((A,v)=>{let N=i.getActivity(A),j=i.getActivity(v),K=N?Ot(N):ir,Z=j?Ot(j):ir;return K-Z});for(let A of m){let v=A,N=i.getActivity(v);if(!N){d.push({activityId:v,reason:S.ACTIVITY_NOT_FOUND});continue}if(xr(v,y,i))continue;let j=N.parentId;if(B(j)){d.push({activityId:v,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let K=String(j),Z=i.getActivity(K);if(!Z){d.push({activityId:v,reason:S.ACTIVITY_NOT_FOUND});continue}let st=Z.parentId;if(B(st)){d.push({activityId:v,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(st),dt=Oo(K,i)+1,re=c.get(v);if(re!=null&&a.has(re)){let Ft=s.get(re)??-1,sr=s.get(v)??-1;Ft>=0&&sr>=0&&(dt+=sr-Ft)}f.push({activityId:v,grandparentKey:lt,oldParentKey:K,targetIndexInGrandparent:dt}),y.add(v),l.add(String(v)),l.add(String(K)),lt!=="0"&&l.add(String(lt)),p.add(K)}let g=$n(f.map(A=>({activityId:A.activityId,newParentId:A.grandparentKey})),i);for(let A of g)d.push({activityId:A,reason:S.HIERARCHY_CYCLE});let _=f.filter(A=>!g.has(A.activityId)),k=await Q(i,l);for(let A of _){i.setActivityField(A.activityId,w.PARENT,A.grandparentKey);let v=kd(i,A.grandparentKey,A.targetIndexInGrandparent,A.activityId);i.setActivityField(A.activityId,w.CORRELATIVE_ID,v),u.push(A.activityId)}for(let A of p){let v=i.getActivity(A);if(!v)continue;let N=i.getChildren(A),j=Fe({parent:v,remainingChildIds:N.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(A),computeEndDate:(dt,re)=>i.calculateEndDate({startDate:dt,durationHours:re,task:v}),idsRemoved:new Set(_.filter(dt=>dt.oldParentKey===A).map(dt=>dt.activityId))});if(!j){dn(A,i);continue}for(let[dt,re]of Object.entries(j.fields))Tt(i,A,dt,re);let K=ae(A,i),Z=K?i.getActivity(K)?.customId:null,st=typeof Z=="string"&&Z?Z:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(st);i.setActivityField(A,w.CUSTOM_ID,lt)}let O=new Set;for(let A of p)O.add(String(A));for(let A of _)A.grandparentKey!=="0"&&O.add(String(A.grandparentKey));for(let A of O)wt(A,i);let T=kt(i);for(let A of T){if(l.add(A.activityId),k.has(A.activityId))continue;let v=i.getActivity(A.activityId);if(!v)continue;let N=it(v);A.before!==void 0&&(N.correlativeId=A.before),k.set(A.activityId,N)}let{scheduledIds:P}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?yt.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t}),M={name:Gt.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(A=>({activity_id:String(A.activityId),reason:A.reason}))}};return e.eventSource!==void 0&&(M.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(A=>{let v=d.find(N=>String(N.activityId)===String(A));return v?{activityId:String(A),ok:!1,reason:v.reason}:{activityId:String(A),ok:!0}}),changes:await $(i,{source:e,beforeSnap:k,touchedIds:l,scheduledIds:P,trackingEvents:[M],hoursPerDay:o.hoursPerDay})}}async function Zd(e,t,r){let{adapter:i,scheduler:n,sector:o}=r,a=i.getActivity(e.activityId);if(!a)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};if(!Gr(e.type))return{ok:!1,reason:S.INVALID_VALUE};let s=i.getChildren(e.activityId),c=e.type===D.PROJECT;if(c!==s.length>0)return{ok:!1,reason:S.INVALID_VALUE};let l=new Set(i.getAllIds()),d=await Q(i,l);n.invalidateAllCaches();let u=c&&a.type!==D.PROJECT?xe({parentId:e.activityId,newChildId:s[0],isCurrentlyLeaf:!0},r).removedLinks:new Map;!c&&a.type===D.PROJECT&&nA(e.activityId,r),e.type!==D.PROJECT?(oA(e.activityId,e.type,r),aA(e.activityId,r)):wt(e.activityId,i);let p=sA(e.activityId,r);for(let[y,m]of u)p.set(y,m);let{scheduledIds:f}=await X({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId],recomputeParentProgress:!0,now:r.now,options:t});return{ok:!0,changes:await $(i,{source:e,beforeSnap:d,touchedIds:l,scheduledIds:f,sirDetection:Lt.BEFORE_DIFF,links:Zt(p),hoursPerDay:o.hoursPerDay}),__beforeLinks:new Map(p)}}function nA(e,t){let r=t.adapter.getActivity(e);if(!r)return;let i=Fe({parent:r,remainingChildIds:[],defaultDurationHours:t.sector.hoursPerDay,promotionSnapshot:t.adapter.getPromotionSnapshot(e),computeEndDate:(n,o)=>t.adapter.calculateEndDate({startDate:n,durationHours:o,task:r})});if(i)for(let[n,o]of Object.entries(i.fields))Tt(t.adapter,e,n,o)}function oA(e,t,r){let i=r.adapter.getActivity(e);if(!i)return;r.adapter.setActivityField(e,w.TYPE,t);let n=t===D.MILESTONE?0:i.durationHours===0?r.sector.hoursPerDay:i.durationHours;n!==i.durationHours&&r.adapter.setActivityField(e,w.DURATION_HOURS,n);let o=r.adapter.getActivity(e);if(!o)return;let a=r.adapter.calculateEndDate({startDate:o.startDate,durationHours:n,task:o});r.adapter.setActivityField(e,w.END_DATE,a)}function aA(e,t){if(t.adapter.getActivity(e)?.customId)return;let i=ae(e,t.adapter),n=i?t.adapter.getActivity(i)?.customId:null,o=t.customIdTracker.generateCustomIdForRestoredChild(n||null);t.adapter.setActivityField(e,w.CUSTOM_ID,o)}function sA(e,t){let r=new Map;for(let i of Ur([e],t.adapter)){let n=t.adapter.getLink(i);n&&(r.set(String(i),{...n}),t.adapter.removeLink(i))}return r}async function Qd(e,t,r){let{adapter:i,ctx:n,scheduler:o,sector:a}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:S.INVALID_PROGRESS_VALUE};let s=n.activityReader.getActivity(e.activityId);if(!s)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c=Oe(E.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===vn.ACTION_BUTTON&&(l.reason===ai.HAS_LOOKAHEAD_TASKS||l.reason===ai.SUMMARY)))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(s,e.newValue,n,e.newValue),u=Ne(e.activityId,d),p=await Q(i,u);be(i,e.activityId,d),Bc(e.activityId,e.newValue,i),_e(e.activityId,d.postProcessors??[],i);let f=d.needsAutoSchedule?n.hierarchy.hasChildren(e.activityId)?yt.ROOTS:e.activityId:null,{scheduledIds:y}=await X({adapter:i,scheduler:o,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:f,recomputeParentsFrom:[],collectDirty:g=>En(e.activityId,u,g),now:r.now,options:t}),m=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await $(i,{source:e,beforeSnap:p,touchedIds:u,scheduledIds:y,trackingEvents:m,hoursPerDay:a.hoursPerDay})}}function cA(e){return e===E.START_DATE||e===E.END_DATE}async function tu(e,t,r){if(e.edits.some(y=>!cA(y.column)))return{ok:!1,reason:S.INVALID_VALUE};let{adapter:i,scheduler:n,sector:o}=r,a=[],s=new Map,c=new Set,l=[],d=[],u=[],p=!1;for(let y of e.edits){let m=lA(y,r);if(a.push(m.verdict),!m.verdict.ok||!m.changes)continue;let g=Ne(y.activityId,m.changes);dA(s,g,r);for(let T of g)c.add(T);let _=br(i,y.activityId),k=Tn(i,String(y.activityId));be(i,y.activityId,m.changes),_e(y.activityId,m.changes.postProcessors??[],i,k),d.push(...wr(_,i,y.activityId)),p||=!!m.changes.needsAutoSchedule;for(let T of m.changes.trackingEvents??[])l.push({name:T.name,properties:T.properties??{}});let O=Je(y.activityId,m.changes.constraintWarning);O&&u.push(O)}let{scheduledIds:f}=await X({adapter:i,scheduler:n,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:p?yt.ROOTS:null,recomputeParentsFrom:c,now:r.now,options:t});return{ok:!0,verdicts:a,changes:await $(i,{source:e,beforeSnap:s,touchedIds:c,scheduledIds:f,sirDetection:Lt.BEFORE_DIFF,links:d,trackingEvents:l,warnings:u,hoursPerDay:o.hoursPerDay})}}function lA(e,t){let{ctx:r}=t,i=e.activityId,n=Oe(e.column);if(!n)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);let o=r.activityReader.getActivity(e.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${e.activityId}" not found`);let a=n.canEdit(o,r.hierarchy);if(!a.allowed)return{verdict:{activityId:i,ok:!1,reason:a.reason??S.CANNOT_EDIT,...a.alertKey?{alertKey:a.alertKey}:{}},changes:null};let s=n.parseInput(e.newValue,o,r);if(!s.ok)return{verdict:{activityId:i,ok:!1,reason:s.reason??S.PARSE_ERROR},changes:null};let c=Reflect.get(o,n.targetField),l=n.validate(o,c,s.value,r);if(!l.valid)return{verdict:{activityId:i,ok:!1,reason:l.reason??S.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=n.transform(o,s.value,r,s.raw);return{verdict:{activityId:i,ok:!0},changes:d}}function dA(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 o=r.adapter.getActivity(n);o&&e.set(n,it(o))}}var Ba=E.CUSTOM_ID,uA="sir-apply";async function eu(e,t,r){let{adapter:i,scheduler:n,sector:o}=r;e.edits.some(A=>A.column===E.DURATION)&&n.invalidateExpandedLinksCache();let s=[],c=new Map,l=new Map,d=new Set,u=new Set,p=[],f=[],y=[],m=new Set,g=new Map,_=new Map,k=!1;for(let A of e.edits){let v=IA(A,r,e.eventSource);if(s.push(v.verdict),e.eventSource===uA&&!v.verdict.ok&&v.verdict.reason!==hn.UNCHANGED)return{ok:!1,reason:v.verdict.reason??S.INVALID,...v.verdict.alertKey?{alertKey:v.verdict.alertKey}:{}};if(!v.verdict.ok||!v.changes)continue;let N=Je(A.activityId,v.changes.constraintWarning);N&&y.push(N);let j=Ne(A.activityId,v.changes);CA(c,j,r);for(let dt of j)u.add(dt);vA(l,A,c),wn(A.column)&&d.add(String(A.activityId)),yA(g,A);let K=br(i,A.activityId),Z=Tn(i,String(A.activityId)),st=gA(A,r),lt=v.changes;be(i,A.activityId,lt),_e(A.activityId,v.changes.postProcessors??[],i,Z),pA(m,y,A),fA(_,A,i.getActivity(A.activityId)),AA(A,st,r),f.push(...wr(K,i,A.activityId)),k||=!!v.changes.needsAutoSchedule;for(let dt of v.changes.trackingEvents??[])p.push({name:dt.name,properties:dt.properties??{}})}let O={action:e,autoscheduleFrom:k?yt.ROOTS:null,recomputeParentsFrom:u,now:r.now,options:t},T=hA(g,_,c,y,m,r),P=l.size>0,{scheduledIds:M}=await(P?xn({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:O,revertTargets:[...l].filter(([A])=>!d.has(A)).map(([A,v])=>({activityId:A,priorConstraintDate:v})),revert:(A,v)=>Fn(A,v,i,r.ctx.calendars)}):X({adapter:i,scheduler:n,sector:o,defaultBaseCalendarId:r.defaultBaseCalendarId},O));return{ok:!0,verdicts:s,changes:await $(i,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:M,sirDetection:Lt.BEFORE_DIFF,links:f,trackingEvents:p,warnings:T,hoursPerDay:o.hoursPerDay})}}function pA(e,t,r){if(!Or(r.column))return;let i=String(r.activityId);for(let n of t)String(n.activityId)===i&&e.add(n)}function fA(e,t,r){!Or(t.column)||!r||e.set(String(t.activityId),{constraintType:r.constraintType,constraintDate:r.constraintDate?new Date(r.constraintDate.getTime()):null})}function yA(e,t){if(t.column!==E.START_DATE&&t.column!==E.END_DATE)return;let r=String(t.activityId),i=e.get(r)??new Set;i.add(t.column),e.set(r,i)}function hA(e,t,r,i,n,o){let a=new Set,s=[],c=new Set;for(let[l,d]of e){if(!d.has(E.START_DATE)||!d.has(E.END_DATE))continue;let u=t.get(l);if(u){o.adapter.setActivityFields(l,u);for(let g of n)String(g.activityId)===l&&c.add(g);continue}let p=r.get(l),f=o.adapter.getActivity(l);if(!p?.constraintType||!p.constraintDate||!f)continue;let y=Me(p.constraintType,f.startDate,f.endDate),m=mA(p.constraintType,p.constraintDate,y);if(a.add(l),m){o.adapter.setActivityField(l,"constraintType",C.SNET),o.adapter.setActivityField(l,"constraintDate",new Date(f.startDate.getTime()));let g=Je(l,Ei(p.constraintType,p.constraintDate,y));g&&s.push(g);continue}o.adapter.setActivityField(l,"constraintType",p.constraintType),o.adapter.setActivityField(l,"constraintDate",p.constraintDate)}return[...i.filter(l=>!c.has(l)&&!a.has(String(l.activityId))),...s]}function mA(e,t,r){return e===C.MSO||e===C.MFO?t.getTime()!==r.getTime():Di(e,t,r).violated}function IA(e,t,r){let{ctx:i}=t,n=e.activityId,o=Oe(e.column);if(!o)return{verdict:{activityId:n,ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN},changes:null};let a=i.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:S.ACTIVITY_NOT_FOUND},changes:null};let s=o.canEdit(a,i.hierarchy,{eventSource:r,newValue:e.newValue});if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??S.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let c=o.parseInput(e.newValue,a,i);if(!c.ok)return{verdict:{activityId:n,ok:!1,reason:c.reason??S.PARSE_ERROR},changes:null};let l=Reflect.get(a,o.targetField),d=o.validate(a,l,c.value,i);if(!d.valid)return{verdict:{activityId:n,ok:!1,reason:d.reason??S.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(e.column===Ba&&c.value!==null){let p=t.adapter.getActivity(e.activityId),f=p?p.customId:null,y=typeof f=="string"?f:null;if(t.customIdTracker.isCustomIdInUse(String(c.value),y))return{verdict:{activityId:n,ok:!1,reason:S.CUSTOM_ID_DUPLICATE},changes:null}}let u=o.transform(a,c.value,i,c.raw);return{verdict:{activityId:n,ok:!0},changes:u}}function gA(e,t){if(e.column!==Ba)return null;let r=t.adapter.getActivity(e.activityId),i=r?r.customId:null;return typeof i=="string"?i:null}function AA(e,t,r){if(e.column!==Ba)return;let i=r.adapter.getActivity(e.activityId),n=i?i.customId:null,o=typeof n=="string"?n:null;t!==o&&r.customIdTracker.trackCustomIdChange(t,o)}function vA(e,t,r){if(!Or(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 CA(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 o=r.adapter.getActivity(n);o&&e.set(n,it(o))}}var Nt={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},SA=[Nt.INVALID_BASELINE_POINT,Nt.UNKNOWN_CONSTRAINT,Nt.ORPHAN_ACTIVITY,Nt.INVALID_LINK,Nt.DUPLICATE_LINK],Br=()=>{};function ru(){let e=new Map,t=new Map;return{record:(n,o)=>{e.set(n,(e.get(n)??0)+1);let a=t.get(n)??[];a.length<10&&!a.includes(o)&&(a.push(o),t.set(n,a))},snapshot:()=>Object.freeze(SA.flatMap(n=>{let o=e.get(n);return o===void 0?[]:[Object.freeze({code:n,count:o,sampleIds:Object.freeze([...t.get(n)??[]])})]}))}}function iu(e){return typeof e=="string"&&e.length>0?fe(e):e instanceof Date?e:null}function Wa(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 qn(e,t,r,i=!1){let n=Wa(e.duration),o=Wa(e.cost),a=Wa(e.hh_work);if(n===null||o===null||a===null)return r&&r.record(Nt.INVALID_BASELINE_POINT,r.sampleId),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;let s=iu(e.start_date),c=iu(e.end_date),l=i&&n===0&&s!==null&&c!==null&&c<s;return l&&t.warn("[baseline] normalizing inverted zero-duration milestone to one instant"),{startDate:s,endDate:l?s:c,durationDays:n,cost:o,workHours:a,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 nu(e,t,r,i=Br){let n=new Map;e.forEachActivity((s,c)=>{let l=s.proplannerId;typeof l=="number"&&n.set(l,c)});let o=new Map;for(let s of t){let c=s.activityId;if(typeof c!="number"){i(Nt.INVALID_BASELINE_POINT,String(c??"unknown"));continue}let l=n.get(c);if(l===void 0){i(Nt.INVALID_BASELINE_POINT,String(c));continue}let d=o.get(l);d?d.push(s):o.set(l,[s])}let a=[];for(let[s,c]of o){let l=e.getActivity(s)?.type===D.MILESTONE;e.setActivityField(s,"baselinePoints",c.map(d=>qn(d,r,{record:i,sampleId:s},l)).filter(d=>d!==null)),a.push(s)}return e.forEachActivity((s,c)=>{if(o.has(c))return;let l=s.baselinePoints;Array.isArray(l)&&l.length>0&&(e.setActivityField(c,"baselinePoints",[]),a.push(c))}),a}function TA(e){let t=Ct(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function ou(e){let t=[];return e.forEachActivity((r,i)=>{let n=TA(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 Jn(e,t,r,i,n=null,o=Br){let a=new Set;for(let s of nu(e,t,i,o))a.add(s);if(r)for(let s of Pr(e,r,n))a.add(s);for(let s of ou(e))a.add(s);for(let s of Lr(e))a.add(s);return[...a]}function au(e,t){t.forEachActivity((r,i)=>{t.setActivityField(i,E.PONDERATOR,0)}),t.forEachActivity((r,i)=>{t.getChildren(i).length>0&&bn(String(i),e,t)})}function Xn(e,t){au(t,e.adapter),ri(e.adapter),e.now&&(Pr(e.adapter,e.now,e.defaultBaseCalendarId??null),Xe(e.adapter,e.now)),Lr(e.adapter),e.now&&ye(e.adapter,e.sector.statusCriteria)}function su(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 cu(e,t){let r=await Q(t.adapter,new Set(t.adapter.getAllIds())),i=su(t),n=Jn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Ze(t.adapter,t.sector.hoursPerDay),su(t)!==i&&Xn(t,t.sector.activityCreter??It.DURATION),{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:r,touchedIds:n,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function DA(e){return Object.values(It).includes(e)}async function lu(e,t){if(!DA(e.criterion))return{ok:!1,reason:S.INVALID_VALUE};let r=new Set(t.adapter.getAllIds()),i=await Q(t.adapter,r);return Xn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:i,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function du(e,t){let r=_n(e.criteria),i=new Set(t.adapter.getAllIds()),n=await Q(t.adapter,i),o=ye(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await $(t.adapter,{source:e,beforeSnap:n,touchedIds:o,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function pu(e,t,r){let i=new Map,n=new Set;for(let a of r.adapter.getAllActivities()){if(!EA(a,r))continue;let s=r.ctx.calendars.getCalendar(a.calendarId);if(!s)continue;let c=s.isWorkTime(a.startDate,ft.HOUR)?_A(a.startDate):a.startDate,l=s.getClosestWorkTime({date:c,direction:Y.FUTURE,unit:ft.HOUR}),d=s.calculateEndDate(l,a.durationHours);if(uu(l,a.startDate)&&uu(d,a.endDate))continue;let u=String(a.id);i.set(u,it(a)),n.add(u),r.adapter.setActivityFields(u,{startDate:l,endDate:d})}let{scheduledIds:o}=await X({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:yt.ROOTS,recomputeParentsFrom:n,now:r.now,options:t});return{ok:!0,changes:await $(r.adapter,{source:e,beforeSnap:i,touchedIds:n,scheduledIds:o,hoursPerDay:r.sector.hoursPerDay})}}function EA(e,t){return!qt(e.type,t.adapter.hasChildren(e.id))}function uu(e,t){return e.getTime()===t.getTime()}function _A(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var fu=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function kA(e){let t={};for(let r of fu)Object.assign(t,{[r]:F(e[r])});return t}function RA(e,t){let r=[],i=n=>{t.has(String(n))&&r.push(n);for(let o of e.getChildren(n))i(o)};for(let n of e.getRootIds())i(n);return r}function yu(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:S.NO_ACTIVITY_SELECTION};let i=RA(t.adapter,r);t.clipboard.value={activities:i.map(o=>{let a=t.adapter.getActivity(o);if(a===null)throw new Error(`Selected activity ${o} is missing`);return{originalId:o,originalParentId:a.parentId??"0",overrides:kA(a)}}),links:t.adapter.getAllLinks().filter(o=>r.has(String(o.source))&&r.has(String(o.target))).map(o=>F(o))};let n=Ri({kind:h.SELECTION_REPLACE,activityIds:[]},{adapter:t.adapter});return n.ok?{...n,changes:{...n.changes,source:e}}:n}function hu(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function PA(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id,beforeSiblingId:t.getChildren(r.id)[0]}:{ok:!0,parentId:"0",afterSiblingId:e}:t.hasChildren(r.id)?{ok:!0,parentId:r.id,beforeSiblingId:t.getChildren(r.id)[0]}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND}}var mu=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function Iu(e,t,r){let i=r.activityClipboard.value;if(i===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let n=PA(e.destination.afterSiblingId,r.adapter);if(!n.ok)return n;let o=await Q(r.adapter,new Set),a=new Set,s=new Map,c=[],l;for(let m of i.activities){let g=s.get(m.originalParentId),_=g===void 0?l??n.afterSiblingId:void 0,k=g===void 0&&_===void 0?n.beforeSiblingId:void 0,O=await mi({kind:h.ACTIVITY_CREATE,parentId:g??n.parentId,..._===void 0?{}:{afterSiblingId:_},...k===void 0?{}:{beforeSiblingId:k},overrides:F(m.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!O.ok)return O;s.set(m.originalId,O.newId),c.push(O.newId),g===void 0&&(l=O.newId)}let d=kt(r.adapter),u=new Set(c.map(String));kr(r.adapter,d,u,o,a);for(let m of c)a.add(String(m));let p=[];for(let m of i.links){let g=s.get(m.source),_=s.get(m.target);if(g===void 0||_===void 0)return mu();let k={kind:Et.CREATE,source:g,target:_,type:m.type,lag:m.lag},O=Te(k,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!O.applied)return mu();p.push({op:k,finalLinkId:O.linkId,rejected:null})}let{scheduledIds:f}=await X({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=Nr(p,new Map,r.adapter);return{ok:!0,changes:await $(r.adapter,{source:e,beforeSnap:o,touchedIds:a,scheduledIds:f,links:y,hoursPerDay:r.sector.hoursPerDay})}}async function gu(e,t,r){return e.kind===h.ACTIVITY_COPY?yu(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind===h.CALENDAR_RECONCILE?pu(e,t,r):e.kind===h.ACTIVITY_CLIPBOARD_CLEAR?hu(e,r.activityClipboard):e.kind===h.ACTIVITY_PASTE_COPIED?Iu(e,t,r):e.kind===Ie?wd(e,t,r):e.kind===h.PERSISTENCE_ACKNOWLEDGE?Hd(e,r):e.kind===h.BASELINE_APPLY?cu(e,r):e.kind===h.PONDERATOR_CRITERION_SET?lu(e,r):e.kind===h.STATUS_CRITERIA_SET?du(e,r):e.kind===h.LINK_CREATE||e.kind===h.LINK_UPDATE||e.kind===h.LINK_DELETE?ud(e,t,r):e.kind===h.LINKS_BATCH?pd(e,t,r):e.kind===h.ACTIVITY_CREATE?Od(e,t,r):e.kind===h.ACTIVITY_DELETE?Pd(e,t,r):e.kind===h.ACTIVITY_MOVE?qd(e,t,r):e.kind===h.ACTIVITY_INDENT?Jd(e,t,r):e.kind===h.ACTIVITY_OUTDENT?Xd(e,t,r):e.kind===h.ACTIVITY_TYPE_SET?Zd(e,t,r):e.kind===h.ACTIVITY_SET_PROGRESS?Qd(e,t,r):e.kind===h.DATES_BATCH?tu(e,t,r):e.kind===h.BULK_EDIT?eu(e,t,r):e.kind===h.SELECTION_TOGGLE?xs(e,Ha(r)):e.kind===h.SELECTION_REPLACE?Ri(e,Ha(r)):e.kind===h.VISIBILITY_SET?Ms(e,Ha(r)):e.kind===h.FILTER_SET?Zs(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.SORT_SET?nc(e,{adapter:r.adapter}):e.kind===h.VIEW_ATTRIBUTES_SET?sc(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.GROUP_SET?cc(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.WBS_DEPTH_SET?lc(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind===h.SIR_SYNC?xd(e,r):e.kind===h.ACTIVITY_LOOKAHEAD_SYNC?Vd(e,t,r):e.kind===h.ACTIVITY_LOOKAHEAD_CONVERT?Yd(e,t,r):e.kind===h.SCHEDULE_AUTO_SCHEDULE?sd(e,t,r):e.kind===h.INLINE_EDIT&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?fd(e,t,r):e.kind!==h.INLINE_EDIT?dc(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):dd(e,t,r)}function Ha(e){return{adapter:e.adapter}}var LA=new Set(["startDate","endDate","constraintDate"]);function Au(e,t){return LA.has(e)&&typeof t=="string"?new Date(t):t}function vu(e,t={}){let r=t.defaultUnit??ft.HOUR;return{getCalendar(i){let n=e.getCalendar(String(i));return n?OA(n,r):null}}}function OA(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 NA(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function nr(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function or(e){return nr(e)&&!isNaN(e.getTime())}var bA={}.constructor.toString();function wA(e){var t=e.constructor.toString();return t!==bA}function FA(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Qt(e){var t,r;if(e&&typeof e=="object")switch(!0){case nr(e):r=new Date(e);break;case NA(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Qt(e[t]);break;default:if(wA(e))r=Object.create(e);else{if(FA(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Qt(e[t]));break}return r||e}function Wr(e,t,r){for(var i in t)(e[i]===void 0||r)&&(e[i]=t[i]);return e}function Cu(e){return typeof e<"u"}var Zn;function Va(){return Zn||(Zn=new Date().valueOf()),Zn++,Zn}function Ht(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var MA=(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)},UA=(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 o="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(o=` Date.UTC(${o})`);let a=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${i} return new Date(${o});`);return s=>a(s,r.locale)},Su={date_to_str:MA,str_to_date:UA},BA=(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}}),WA=(e,t,r)=>i=>{let n=[0,0,1,0,0,0],o=i.match(/[a-zA-Z]+|[0-9]+/g),a=e.match(/%[a-zA-Z]/g);for(let s=0;s<a.length;s++)switch(a[s]){case"%j":case"%d":n[2]=o[s]||1;break;case"%n":case"%m":n[1]=(o[s]||1)-1;break;case"%y":n[0]=o[s]*1+(o[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":n[3]=o[s]||0;break;case"%i":n[4]=o[s]||0;break;case"%Y":n[0]=o[s]||0;break;case"%a":case"%A":n[3]=n[3]%12+((o[s]||"").toLowerCase()==="am"?0:12);break;case"%s":n[5]=o[s]||0;break;case"%M":n[1]=r.locale.date.month_short_hash[o[s]]||0;break;case"%F":n[1]=r.locale.date.month_full_hash[o[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])},Tu={date_to_str:BA,str_to_date:WA};function Du(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 o(){var s=!1;return e.config.csp==="auto"?(i===null&&n(),s=i):s=e.config.csp,s}var a={_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=Su;return o()&&(l=Tu),l.date_to_str(s,c,e)},str_to_date:function(s,c){var l=Su;return o()&&(l=Tu),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(),p=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),f=1+Math.floor(p/7);return f},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,p=r(s);if(p)return a._isoDateDetected?u&&(a._isoDateOnly=!1):(a._isoDateDetected=!0,a._isoDateOnly=!u),p}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 a}function ja(e,t,r,i,n){return this.date=e,this.unit=t,this.task=r,this.id=i,this.calendar=n,this}function Ka(e,t,r,i,n,o){return this.date=e,this.dir=t,this.unit=r,this.task=i,this.id=n,this.calendar=o,this}function Ya(e,t,r,i,n,o,a){return this.start_date=e,this.duration=t,this.unit=r,this.step=i,this.task=n,this.id=o,this.calendar=a,this}function HA(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 Eu=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(nr(t)?t={date:t}:t=Wr({},t),!or(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 ja)return t;var r;if(t.date?r=new ja(t.date,t.unit,t.task,null,t.calendar):r=new ja(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!or(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 Ka)return r;var i;if(nr(r)?i=new Ka(r):i=new Ka(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,!or(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=HA,i;if(t instanceof r)return t;if(nr(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,!or(i.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!or(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 o=arguments[0];if(o instanceof Ya)return o;var a;if(nr(o)?a=new Ya(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):a=new Ya(o.start_date,o.duration,o.unit,o.step,o.task,null,o.calendar),o.id!==null&&o.id!==void 0&&(a.task=o,a.unit=null,a.step=null),a.unit=a.unit||e.config.duration_unit,a.step=a.step||e.config.duration_step,!or(a.start_date))throw e.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return a}}};function _u(){}_u.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(o){var a=String(o);return a.length<2&&(a="0"+a),a}function i(o){var a=Math.floor(o/3600),s=o-a*60*60,c=Math.floor(s/60);return a+":"+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=[],o=0;o<r.length;o++)for(var a=r[o],s=0;s<i.length;s++){var c=i[s];c.start<a.end&&c.end>a.start&&(n.push({start:Math.max(a.start,c.start),end:Math.min(a.end,c.end)}),a.end>c.end&&(i.splice(s,1),s--,o--))}return n},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(o,a){return o.start-a.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=Qt(e.getConfig()),i=Qt(t.getConfig()),n=r.parsed,o=i.parsed;n.customWeeks=r.customWeeks,o.customWeeks=i.customWeeks;var a={hours:this._toHoursArray(this._mergeHoursConfig(n.hours,o.hours)),dates:{},customWeeks:{}};let s=(l,d)=>{for(let u in l.dates){let p=l.dates[u];+u>1e3&&(a.dates[u]=!1);for(let f in d.dates){let y=d.dates[f];if(f==u&&(a.dates[u]=!!(p&&y)),Array.isArray(p)){let m=Array.isArray(y)?y:d.hours;a.dates[u]=this._toHoursArray(this._mergeHoursConfig(p,m))}}}};if(s(n,o),s(o,n),n.customWeeks)for(var c in n.customWeeks)a.customWeeks[c]=n.customWeeks[c];if(o.customWeeks)for(var c in o.customWeeks)a.customWeeks[c]?a.customWeeks[c+"_second"]=o.customWeeks[c]:a.customWeeks[c]=o.customWeeks[c];return a}};var Ga=class{constructor(){this.clear()}getItem(t,r,i){if(this._cache.has(t)){let o=this._cache.get(t)[i.getUTCFullYear()];if(o&&o.has(r))return o.get(r)}return-1}setItem(t,r,i,n){if(!t||!r)return;let o=this._cache,a=n.getUTCFullYear(),s;o.has(t)?s=o.get(t):(s=[],o.set(t,s));let c=s[a];c||(c=s[a]=new Map),c.set(r,i)}clear(){this._cache=new Map}},$a=class{constructor(){this.clear()}getItem(t,r,i){let n=this._cache;if(n&&n[t]){let o=n[t];if(o===void 0)return-1;let a=o[i.getUTCFullYear()];if(a&&a[r]!==void 0)return a[r]}return-1}setItem(t,r,i,n){if(!t||!r)return;let o=this._cache;if(!o)return;o[t]||(o[t]=[]);let a=o[t],s=n.getUTCFullYear(),c=a[s];c||(c=a[s]={}),c[r]=i}clear(){this._cache={}}},za=class{constructor(t){this.getMinutesPerWeek=r=>{let i=r.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(r));for(let c=0;c<7;c++)a+=n.getHoursPerDay(s)*60,s=o.date.add(s,1,"day");return this._weekCache.set(i,a),a},this.getMinutesPerMonth=r=>{let i=r.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let n=this._calendar,o=this._calendar.$gantt,a=0,s=o.date.week_start(new Date(r)),c=o.date.add(s,1,"month").valueOf();for(;s.valueOf()<c;)a+=n.getHoursPerDay(s)*60,s=o.date.add(s,1,"day");return this._monthCache.set(i,a),a},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function VA(){return typeof Map<"u"?new Ga:new $a}var qa=class{constructor(){this.clear()}_getCacheObject(t,r,i){let n=this._cache;n[r]||(n[r]=[]);let o=n[r];o||(o=n[r]={});let a=o[i];a||(a=o[i]={});let s=t.getUTCFullYear(),c=a[s];return c||(c=a[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,o){let a=this._getCacheObject(t,i,n),s=t.valueOf(),c=this._endDateCacheKey(s,r),l;if(a.endDates[c]===void 0){let d=o(),u=d.valueOf();a.endDates[c]=u,a.durations[this._durationCacheKey(s,u)]=r,l=d}else l=new Date(a.endDates[c]);return l}getDuration(t,r,i,n,o){let a=this._getCacheObject(t,i,n),s=t.valueOf(),c=r.valueOf(),l=this._durationCacheKey(s,c),d;if(a.durations[l]===void 0){let u=o();a.durations[l]=u.valueOf(),d=u}else d=a.durations[l];return d}clear(){this._cache={}}};function Ja(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=VA(),this._largeUnitsCache=new za(this),this._dateDurationCache=new qa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ja.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,o=new Date(e),a=new Date(t);i=i||1;var s=0,c=null,l,d,u=!1;l=n[r+"_start"](new Date(o)),l.valueOf()!=o.valueOf()&&(u=!0);var p=!1;d=n[r+"_start"](new Date(t)),d.valueOf()!=t.valueOf()&&(p=!0);for(var f=!1;o.valueOf()<a.valueOf();){if(c=this._nextDate(o,r,i),f=c.valueOf()>a.valueOf(),this._isWorkTime(o,r))(u||p&&f)&&(l=n[r+"_start"](new Date(o)),d=n.add(l,i,r)),u?(u=!1,c=this._nextDate(l,r,i),s+=(d.valueOf()-o.valueOf())/(d.valueOf()-l.valueOf())):p&&f?(p=!1,s+=(a.valueOf()-o.valueOf())/(d.valueOf()-l.valueOf())):s++;else{var y=this._getUnitOrder(r),m=this.units[y-1];m&&!this._isWorkTime(o,m)&&(c=this._getClosestWorkTimeFuture(o,m))}o=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 o=i[n];if(t>=o.start&&r<=o.end)return 60;if(t<o.end&&r>o.start){var a=Math.min(r,o.end)-Math.max(t,o.start);return a/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,o=new Date(e),a=new Date(t),s;for(r=="minute"?s=Ht(this._getMinutesPerDay,this):s=Ht(this.getHoursPerDay,this);o.valueOf()<a.valueOf();){if(a-o>1e3*60*60*24*32&&o.getUTCDate()===0){var c=this._largeUnitsCache.getMinutesPerMonth(o);r=="hour"&&(c=c/60),n+=c,o=this.$gantt.date.add(o,1,"month");continue}else if(a-o>1e3*60*60*24*16){var l=this.$gantt.date.week_start(new Date(o));if(o.valueOf()===l.valueOf()){var c=this._largeUnitsCache.getMinutesPerWeek(o);r=="hour"&&(c=c/60),n+=c,o=this.$gantt.date.add(o,7,"day");continue}}n+=s(o),o=this._nextDate(o,"day",1)}return n/i},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),i=this._getWorkHours(e),n=0,o=0;o<i.length;o++){var a=i[o];if(r.end>=a.start&&r.start<=a.end){var s=Math.max(a.start,r.start),c=Math.min(a.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),o=new Date(t);i=i||1;var a=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(o.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(e,t);var c=this.$gantt.date.day_start(new Date(o)),l=o,d=this._getMinutesBetweenSingleDay(a,s),u=this._getMinutesBetweenSingleDay(c,l),p=this._getWorkUnitsForRange(s,c,r,i),f=d+p+u;return f},_getHoursBetween:function(e,t,r,i){var n=new Date(e),o=new Date(t);i=i||1;var a=new Date(n),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(n)),1,"day");if(o.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(e,t)/60);var c=this.$gantt.date.day_start(new Date(o)),l=o,d=this._getMinutesBetweenSingleDay(a,s,r,i)/60,u=this._getMinutesBetweenSingleDay(c,l,r,i)/60,p=this._getWorkUnitsForRange(s,c,r,i),f=d+p+u;return Math.round(f)},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 o=n.from,a=n.to;(!r||r>o.valueOf())&&(r=o.valueOf()),(!i||i<a.valueOf())&&(i=a.valueOf()),e.parsed.customWeeksBoundaries.push({from:o.valueOf(),fromReadable:new Date(o),to:a.valueOf(),toReadable:new Date(a),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 o=r[n],a=e.dates[o],s=t.dates[o];if(a!==s&&!(Array.isArray(a)&&Array.isArray(s)&&this._arraysEqual(a,s)))return!1}return!0},equals:function(e){if(!(e instanceof Ja))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],o=r.parsed.customWeeks[i];if(!o||!this._compareSettings(n,o))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 o=0;o<r.customWeeksBoundaries.length;o++)if(r.customWeeksBoundaries[o].from<=n&&r.customWeeksBoundaries[o].to>n){r=r.customWeeks[r.customWeeksBoundaries[o].name];break}}var a=!0;return r.dates[n]!==void 0?a=r.dates[n]:r.dates[e.getUTCDay()]!==void 0&&(a=r.dates[e.getUTCDay()]),a===!0?r.hours:a||[]},_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],o=t[i+1],a=o-n;r.push({start:n,end:o,startHour:Math.floor(n/3600),startMinute:Math.floor(n/60),endHour:Math.ceil(o/3600),endMinute:Math.ceil(o/60),durationSeconds:a,durationMinutes:a/60,durationHours:a/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(Ht(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),i=this.getConfig();if(r!==null?i.dates[r]=t:e.customWeeks||(i.hours=t),e.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof e.customWeeks=="string")r!==null?i.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(i.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var n in e.customWeeks)i.customWeeks[n]=e.customWeeks[n]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(Ht(function(){if(!e)this.reset_calendar();else{var t=this._timestamp(e);t!==null&&delete this.getConfig().dates[t]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(e,t){var r=-1,i=null;return i=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,i,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,i,r,e)),r},isWorkTime:function(){var e=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(e.date,e.unit)},calculateDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!e.unit)return!1;var t=this;return this._dateDurationCache.getDuration(e.start_date,e.end_date,e.unit,e.step,function(){return t._calculateDuration(e.start_date,e.end_date,e.unit,e.step)})},_calculateDuration:function(e,t,r,i){var n=0,o=1;if(e.valueOf()>t.valueOf()){var a=t;t=e,e=a,o=-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),o*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 o=new Date(t),a=new Date(r);for(n=n||1;o.valueOf()<a.valueOf();){if(this._isWorkTime(o,i))return!0;o=this._nextDate(o,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 o=e.duration>=0?1:-1;r=Math.abs(r*1);var a=this;return this._dateDurationCache.getEndDate(t,r,i,n*o,function(){return a._calculateEndDate(t,r,i,n*o)})},_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 o=0,a=e;o<t&&!(n&&n(a));){var s=this._nextDate(a,r,i),c=new Date(s.valueOf()+1);i>0&&(c=new Date(s.valueOf()-1));var l=this._isWorkTime(c,r);l&&o++,a=s}return{end:a,start:e,added:o}},_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,o=this._getIntervalTimestamp(e,r),a=this._getWorkHours(e),s=0;s<a.length&&i<t;s++){var c=a[s];if(o.end>=c.start&&o.start<=c.end){var l=Math.max(c.start,o.start),d=Math.min(c.end,o.end),u=(d-l)/3600;u>n&&(u=n,d=l+n*60*60);var p=Math.round((d-l)/3600);i+=p,n-=p,o.start=d}}var f=r;return i===t&&(f=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:i,end:f}},_calculateHourEndDate:function(e,t,r){var i=new Date(e),n=0;r=r||1,t=Math.abs(t*1);var o=this._addHoursUntilDayEnd(i,t);n=o.added,i=o.end;var a=t-n;if(a){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 a=t-n;o=this._addHoursUntilDayEnd(i,a),i=o.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,o=this._getIntervalTimestamp(e,r),a=this._getWorkHours(e),s=0;s<a.length&&i<t;s++){var c=a[s];if(o.end>=c.start&&o.start<=c.end){var l=Math.max(c.start,o.start),d=Math.min(c.end,o.end),u=(d-l)/60;u>n&&(u=n,d=l+n*60);var p=Math.round((d-l)/60);n-=p,i+=p,o.start=d}}var f=r;return i===t&&(f=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,o.start))),{added:i,end:f}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),i=0,n=t,o=r.getUTCHours()*60*60+r.getUTCMinutes()*60+r.getUTCSeconds(),a=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(a>l.start&&o<=l.end){var d=Math.min(a,l.end),u=Math.max(o,l.start),p=(d-u)/60;p>n&&(p=n,u=d-n*60);var f=Math.abs(Math.round((d-u)/60));n-=f,i+=f,a=u}}var y=r;return i===t&&(y=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a))),{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 o=this._isMinutePrecision(i),a=this._subtractMinutesUntilHourStart(i,t);n+=a.added,i=a.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 p=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();p!==s&&(c=this._getWorkHours(d),l=this._getMinutesPerDay(d),s=p);var f=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&&f>l){n+=l,i=this.$gantt.date.add(i,-1,"day");continue}for(var m=!1,g=null,_=null,k=c.length-1;k>=0;k--)if(c[k].start<y-1&&c[k].end>=y-1){m=!0,g=c[k],_=c[k-1];break}if(m)if(y===g.end&&f>=g.durationMinutes)n+=g.durationMinutes,i=this.$gantt.date.add(i,-g.durationMinutes,"minute");else if(!o&&f<=y/60-g.startMinute)n+=f,i=this.$gantt.date.add(i,-f,"minute");else if(o)f<=y/60-g.startMinute?(n+=f,i=this.$gantt.date.add(i,-f,"minute")):(n+=y/60-g.startMinute,_?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,_.end)):i=this.$gantt.date.day_start(i));else{var O=this._getMinutesPerHour(i);O<=f?(n+=O,i=this._nextDate(i,"hour",r)):(a=this._subtractMinutesUntilHourStart(i,f),n+=a.added,i=a.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var T=this._getClosestWorkTimePast(i,"hour");if(T.valueOf()===i.valueOf()){var T=this.$gantt.date.add(i,-1,"day"),P=this._getWorkHours(T);if(P.length){var M=P[P.length-1];T.setUTCSeconds(M.durationSeconds)}}i=T}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(n<t){var A=t-n;a=this._subtractMinutesUntilHourStart(i,A),n+=a.added,i=a.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 o=this._addMinutesUntilHourEnd(i,t);n+=o.added,i=o.end;for(var a=0,s=[],c=0,l=this._isMinutePrecision(i);n<t;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==a&&(s=this._getWorkHours(i),c=this._getMinutesPerDay(i),a=d);var u=t-n,p=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>=p&&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 f=!1,y=null,m=0;m<s.length;m++)if(s[m].start<=p&&s[m].end>p){f=!0,y=s[m];break}if(f)if(p===y.start&&u>=y.durationMinutes)n+=y.durationMinutes,i=this.$gantt.date.add(i,y.durationMinutes,"minute");else if(u<=y.endMinute-p/60)n+=u,i=this.$gantt.date.add(i,u,"minute");else{var g=this._getMinutesPerHour(i);g<=u?(n+=g,l?i=this.$gantt.date.add(i,g,"minute"):i=this._nextDate(i,"hour",r)):(o=this._addMinutesUntilHourEnd(i,u),n+=o.added,i=o.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(n<t){var _=t-n;o=this._addMinutesUntilHourEnd(i,_),n+=o.added,i=o.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),o=this._getClosestWorkTimePast(i,t);Math.abs(n-e)<=Math.abs(e-o)?i=n:i=o}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,o=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",t<0?"past":"future"),t<0&&(i=new Date(i.valueOf()-1),o=!0),r=this._getWorkHours(i));var a=this._getTimeOfDayStamp(i);if(o&&(a=this._getTimeOfDayStamp(new Date(i.valueOf()+1),o)),t>0){for(var s=0;s<r.length;s++)if(r[s].start>=a){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<=a){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,r[s].end));break}else if(r[s].end>a&&r[s].start<=a){n=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,a));break}return n},_getClosestWorkMinute:function(e,t,r){var i=new Date(e),n=this._getWorkHours(i),o=this._findClosestTimeInDay(i,r,n);return o||(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),o=this._findClosestTimeInDay(i,r,n)),r<0&&(o=this.$gantt.date.add(o,-1,t)),o},_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],o=e,a=3e3,s=0;!this._isWorkTime(o,t)&&!(n&&!this._isWorkTime(o,n)&&(r>0?o=this._getClosestWorkTimeFuture(o,n):o=this._getClosestWorkTimePast(o,n),this._isWorkTime(o,t)));){if(s++,s>a)return this.$gantt.assert(!1,"Invalid working time check"),!1;o=this.$gantt.date.add(o,r,t),this.$gantt.date[t+"_start"]&&(o=this.$gantt.date[t+"_start"](o))}return o},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),o=!1;return r.forEach((function(a){if(!o){var s=t[a];s===!0?o=n:Array.isArray(s)&&(o=this._checkWorkHours(s))}}).bind(this)),o},_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 Ii={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 jA(){function e(n){return n.map(function(o){return o&&o.resource_id?o.resource_id:o}).sort().join("-")}var t={};function r(n,o){return o.mergeCalendars(n.map(function(a){var s=a&&a.resource_id?a.resource_id:a;return o.getResourceCalendar(s)}))}function i(n,o){var a=e(n);if(n.length){if(n.length===1)return o.getResourceCalendar(a).id;if(t[a])return t[a].id;var s=r(n,o);return t[a]=s,o.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:i}}var KA=jA();function ku(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Ii.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))}ku.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 _u,n;return e.forEach((function(o){n?n=this._createCalendarFromConfig(i.merge(n,o)):n=o}).bind(this)),this.createCalendar(n)},_createCalendarFromConfig:function(e){var t=new Ja(this.$gantt,Eu(this.$gantt));t.id=String(Va());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=Qt(e.getConfig()):e.worktime?t=Qt(e.worktime):t=Qt(e);var r=Qt(this.defaults.fulltime.worktime);return Wr(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=Ii.getResourceProperty(t),Array.isArray(e[n])&&e[n].length)t.dynamic_resource_calendars?i=KA.getCalendarIdFromMultipleResources(e[n],this):r=this.getResourceCalendar(e[n]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Ii.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var i=Ii.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=Ii.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var o in i)if(i[o][t]){n=i[o][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 o=r;t.isTaskExists(o.parent)&&(o=t.getTask(o.parent),!(t.isSummaryTask(o)&&(i=this._getOwnCalendar(o),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||Va(),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 Xa(e,t){this.argumentsHelper=t,this.$gantt=e}Xa.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,o={week:1e3*60*60*24*7,day:1e3*60*60*24,hour:1e3*60*60,minute:1e3*60},a=0;if(o[r])a=Math.round((t-e)/(i*o[r]));else{for(var s=new Date(e),c=new Date(t);s.valueOf()<c.valueOf();)a+=1,s=n.add(s,i,r);s.valueOf()!=t.valueOf()&&(a+=(c-s)/(n.add(s,i,r)-s))}return Math.round(a)},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 Xa},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 Ru(e){this.$gantt=e.$gantt,this.argumentsHelper=Eu(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Xa(this.$gantt,this.argumentsHelper)}Ru.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 YA=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,o){return t.calculateEndDate(r,i,n,o)},mergeCalendars:Ht(e.mergeCalendars,e),createCalendar:Ht(e.createCalendar,e),addCalendar:Ht(e.addCalendar,e),getCalendar:Ht(e.getCalendar,e),getCalendars:Ht(e.getCalendars,e),getResourceCalendar:Ht(e.getResourceCalendar,e),getTaskCalendar:Ht(e.getTaskCalendar,e),deleteCalendar:Ht(e.deleteCalendar,e)}},GA={create:YA};function Pu(e){var t=new ku(e),r=new Ru(t),i=GA.create(t,r);Wr(e,i)}var Lu={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 Ou(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||Lu,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 o=e.onEvent;return o&&o(i,n),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Cu,mixin:Wr,copy:Qt,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=Du(r),r.date.init(),Pu(r),r}function $A(e={}){let t=Ou(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 Nu={createCalendar:$A};var tW=3600*1e3;function xu(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:zA}=Nu,gi="__replay_default__";function qA(e){if(!e||e.length===0||typeof e[0]=="string")return e;let t=e.map(Number);if(t.some(o=>Number.isNaN(o)))return e;let r=t[0],i=t[t.length-1];return t.every((o,a)=>o===r+a)?[`${r}:00-${i+1}:00`]:e}var bu={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},wu="__main_global__",JA={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Fu(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 XA(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:qA(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Mu(e){let t=zA({config:{work_time:!0}});t.addCalendar({id:gi,worktime:bu}),t.addCalendar({id:wu,worktime:JA});let r=new Set(e.filter(d=>!Fu(d.worktime)).map(d=>String(d.id))),i=e.filter(d=>Fu(d.worktime));for(let d of i)t.addCalendar({id:d.id,worktime:d.worktime?XA(d.worktime):bu});let n=vu(t),o=n.getCalendar(gi),a=n.getCalendar(wu);if(!o||!a)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([gi]);for(let d of i)s.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),p=c.get(u);if(p)return p;let f=o;return s.has(u)?f=n.getCalendar(d)??o:r.has(u)&&(f=a),c.set(u,f),f}}}}function Uu(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 ZA(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 o=e.getActivity(n);if(!o)break;r.push(String(n)),i=o}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 ZA(e,t){let r=[],i=new Bt;for(let n of e.getChildren(t))i.enqueue(n);for(;!i.isEmpty();){let n=i.dequeue();r.push(n);for(let o of e.getChildren(n))i.enqueue(o)}return r}var Qn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Bu(t);return this.reader.getCalendar(r??gi)}getClosestWorkTime(t){let r=`${Qa(t.task)}|${t.dir}|${t.date.getTime()}`;return Za(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ft.HOUR}))}calculateEndDate(t){let r=`${Qa(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Za(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Qa(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Za(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 Za(e,t,r){let i=e.get(t);if(i!==void 0)return i;let n=r();return e.set(t,n),n}var QA="__default__";function Bu(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Qa(e){return Bu(e)??QA}var to=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,o=this.activities.size;for(;i&&!B(i);){if(i===r)return!0;if(++n>o)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||B(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(B(t)){this._roots.push(r);return}let i=String(t),n=this._childrenByParent.get(i);n?n.push(r):this._childrenByParent.set(i,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(B(r.parentId)){this._roots.push(r.id);continue}let i=String(r.parentId),n=this._childrenByParent.get(i)??[];n.push(r.id),this._childrenByParent.set(i,n)}let t=(r,i)=>{let n=this.activities.get(r),o=this.activities.get(i);return n&&o?hr(n,o):String(r).localeCompare(String(i))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var eo=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}};function is(e,t,r,i,n,o){return{valueId:t,id:e,label:r,color:i,level:n,sequence:o,children:new Map,activities:[]}}function Wu(e,t,r,i,n){let{attributeKey:o,startLevel:a,depth:s}=t;for(let c of e){let l=r.assignmentByActivityId.get(String(c.id)),d=l===void 0?[]:js(r,l,a,s),u=d.length===0?[Ve]:d,p=i;u.forEach((f,y)=>{let m=p.children.get(f);if(m===void 0){let g=r.valueById.get(f);m=is(n?bi(p.id,o,f):Ni(o,f),f,g?.label??(f===Ve?Pi:f),g?.color??null,i.level+1+y,g?.sequence??Number.MAX_SAFE_INTEGER),p.children.set(f,m)}p=m}),p.activities.push(c)}return i}function Hu(e){let t=e.activities.length;for(let r of e.children.values())t+=Hu(r);return t}function ts(e,t){let r=[...e.children.values()];return r.sort((i,n)=>i.valueId===Ve?1:n.valueId===Ve?-1:i.sequence!==n.sequence?i.sequence-n.sequence:i.valueId.localeCompare(n.valueId)),t===Pt.DESCENDING&&r.reverse(),r}var tv=1,ev=Number.POSITIVE_INFINITY;function es(e){return{kind:fr.ACTIVITY,activityId:String(e.id)}}function rv(e,t,r){let i=[],n=new Map;for(let o of t){if(!e.has(String(o.id)))continue;let a=r(o.id),s=a===null?null:String(a);if(s===null||!e.has(s)){i.push(o);continue}let c=n.get(s);c===void 0?n.set(s,[o]):c.push(o)}return{roots:i,childrenOf:n}}function Vu(e,t){let{roots:r,childrenOf:i}=rv(e,t.activitiesInVisualOrder,t.parentOf),n=t.wbsDepth??ev,o=c=>i.get(String(c.id))??[],a=c=>{let l=[],d=u=>{for(let p of u){let f=o(p);f.length===0?l.push(p):d(f)}};return d(c),l},s=(c,l)=>{if(l>n){let d=a(c),u=t.comparator===null?d:Ui(d,t.comparator,t.orderMode,()=>!1);for(let p of u)t.rows.push(es(p));return}for(let d of c){t.rows.push(es(d));let u=o(d);u.length>0&&s(u,l+1)}};s(r,tv)}function iv(e,t){let r=new Set(e.map(i=>String(i.id)));for(let i of e){let n=t.parentOf(i.id);for(;n!==null;)r.add(String(n)),n=t.parentOf(n)}Vu(r,t)}function nv(e,t){let{rows:r}=t;if(t.group.includeWbs){iv(e.activities,{activitiesInVisualOrder:t.activitiesInVisualOrder,parentOf:t.parentOf,wbsDepth:t.wbsDepth,comparator:t.comparator,orderMode:t.orderMode,rows:r});return}for(let i of Ui([...e.activities],t.comparator,t.orderMode,t.hasChildren))r.push({kind:fr.ACTIVITY,activityId:String(i.id)})}function rs(e,t,r,i){let{group:n,rows:o}=i;if(o.push({kind:fr.GROUP,id:e.id,label:e.label,level:e.level,color:e.color,activityCount:Hu(e)}),n.collapsedIds.has(e.id))return;for(let s of ts(e,t))rs(s,t,r,i);if(e.activities.length===0)return;let a=n.secondary;if(r&&a!=null&&i.secondaryCatalog!=null){let s=Wu(e.activities,a,i.secondaryCatalog,is(e.id,"","",null,e.level,0),!0);for(let c of ts(s,a.direction))rs(c,a.direction,!1,i);return}nv(e,i)}function ju(e){let t=e.activitiesInVisualOrder.filter(s=>e.isVisible(s.id));if(e.group===null||e.catalog===null){if(e.wbsDepth===null)return t.map(es);let s=[];return Vu(new Set(t.map(c=>String(c.id))),{activitiesInVisualOrder:t,parentOf:e.parentOf,wbsDepth:e.wbsDepth,comparator:e.comparator,orderMode:e.orderMode,rows:s}),s}let{group:r,catalog:i}=e,n=Wu(t,r,i,is("","","",null,-1,0),!1),o=[],a={group:r,activitiesInVisualOrder:e.activitiesInVisualOrder,parentOf:e.parentOf,hasChildren:e.hasChildren,comparator:e.comparator,orderMode:e.orderMode,wbsDepth:e.wbsDepth,secondaryCatalog:e.secondaryCatalog,rows:o};for(let s of ts(n,r.direction))rs(s,r.direction,!0,a);return o}var ro=class e{catalogs=new Map;group=null;wbsDepth=null;getCatalog(t){return this.catalogs.get(t)??null}getCatalogMap(){return this.catalogs}setCatalogs(t){let r=new Map;for(let i of t)r.set(i.key,Hs(i));this.catalogs=r}getGroup(){return this.group}setGroup(t){this.group=t}getWbsDepth(){return this.wbsDepth}setWbsDepth(t){this.wbsDepth=t}clone(){let t=new e;return t.catalogs=new Map(this.catalogs),t.group=this.group===null?null:F(this.group),t.wbsDepth=this.wbsDepth,t}};var Hr=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,visualRows:null,orderComparator:null};_writeCapture=new Nn;_viewState=new eo;_viewAttributes=new ro;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=F(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 Qn(Mu(this._calendarSnapshot)),this._flags=av(t),this._hierarchy=new to(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(pe),links:this.getAllLinks().map(r=>({...r})),calendars:F(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(F(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,F(i)])),t._progressFallback=new Map(this._progressFallback),t._flags=F(this._flags),t._filterProjection=F(this._filterProjection),t._viewAttributes=this._viewAttributes.clone(),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=ec(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null,this.invalidateVisualRows()}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){this._captureViewStateOnce();let i=this._viewState.setVisible(String(t),r);return i&&this.invalidateVisualRows(),i}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null,this.invalidateVisualRows()}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._viewAttributes.getCatalogMap()),this._cache.orderComparator)}getOrderMode(){return this._viewState.getActiveOrder()?.mode??ce.STANDARD}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null,this.invalidateVisualRows()}getViewAttributeCatalogMap(){return this._viewAttributes.getCatalogMap()}setViewAttributeCatalogs(t){this._viewAttributes.setCatalogs(t),this.invalidateDerivedOrder()}getGroup(){return this._viewAttributes.getGroup()}setGroup(t){this._viewAttributes.setGroup(t),this.invalidateVisualRows()}getWbsDepth(){return this._viewAttributes.getWbsDepth()}setWbsDepth(t){this._viewAttributes.setWbsDepth(t),this.invalidateVisualRows()}invalidateVisualRows(){this._cache.visualRows=null}getVisualRows(){if(this._cache.visualRows)return this._cache.visualRows;let t=this._viewAttributes.getGroup(),r=t===null?null:this._viewAttributes.getCatalog(t.attributeKey),i=t?.secondary==null?null:this._viewAttributes.getCatalog(t.secondary.attributeKey),n=[];for(let o of this.getVisualOrderIds()){let a=this.getActivity(o);a!==null&&n.push(a)}return this._cache.visualRows=ju({activitiesInVisualOrder:n,isVisible:o=>this.isVisible(o),parentOf:o=>this.getParentId(o),hasChildren:o=>this.hasChildren(o),group:t,catalog:r,secondaryCatalog:i,comparator:this.getOrderComparator(),orderMode:this.getOrderMode(),wbsDepth:this._viewAttributes.getWbsDepth()}),this._cache.visualRows}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))??Ku}getIncomingLinkIds(t){return this._incoming.get(String(t))??Ku}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,os(n,r),r===w.PARENT&&this._hierarchy.markDirty(),ns(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,Au(r,i)),os(n,r),r===w.PARENT&&this._hierarchy.markDirty(),ns(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 o of Object.keys(r))Reflect.set(i,o,Reflect.get(r,o)),os(i,o),o===w.PARENT&&(n=!0),ns(o)&&(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){Yu(this._outgoing,String(t.source),t.id),Yu(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),as(r,t.id));let i=this._incoming.get(String(t.target));i&&this._incoming.set(String(t.target),as(i,t.id))}_removeLinkRef(t,r,i){let n=t.get(r);n&&t.set(r,as(n,i))}_insertLinkRefInOrder(t,r,i){let n=new Set;for(let s of this._links.keys()){if(String(s)===String(i))break;n.add(String(s))}let o=[...t.get(r)??[]],a=o.findIndex(s=>!n.has(String(s)));o.splice(a<0?o.length:a,0,i),t.set(r,o)}setLinkField(t,r,i){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n[r]=i)}setLinkEndpoints(t,r,i){let n=this.getLink(t);if(!n)return;let o=String(n.source)!==String(r),a=String(n.target)!==String(i);!o&&!a||(this._writeCapture.noteLinkField(String(t),n),o&&(this._removeLinkRef(this._outgoing,String(n.source),n.id),n.source=r,this._insertLinkRefInOrder(this._outgoing,String(r),n.id)),a&&(this._removeLinkRef(this._incoming,String(n.target),n.id),n.target=i,this._insertLinkRefInOrder(this._incoming,String(i),n.id)))}setLinkFieldDynamic(t,r,i){let n=this.getLink(t);if(n){if(r===xt.SOURCE){this.setLinkEndpoints(t,String(i),n.target);return}if(r===xt.TARGET){this.setLinkEndpoints(t,n.source,String(i));return}ov(r)&&(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:o,progressFallbackBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreActivityFields(o),this._restoreActivityFields(i),this._restoreCorrelatives(n),this._restoreProgressFallbacks(a),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===vt.LINK_ADD&&this._detachLink(r.linkId)}_undoInserts(t){for(let r of t)r.kind===vt.INSERT&&this._activities.delete(r.activityId)}_reInsertRemovedActivities(t){for(let r of t)r.kind===vt.REMOVE&&this._activities.set(r.activityId,r.before)}_reAddRemovedLinks(t){for(let r of t)r.kind===vt.LINK_REMOVE&&this._attachLink(r.before)}_restoreLinkFields(t){for(let r of t){if(r.kind!==vt.LINK_FIELD)continue;let i=this._links.get(r.linkId);if(i){this.setLinkEndpoints(r.linkId,r.before.source,r.before.target);for(let n of Object.keys(i))Object.hasOwn(r.before,n)||Reflect.deleteProperty(i,n);Object.assign(i,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))}},Ku=[];function ov(e){return e===xt.LAG||e===xt.TYPE||e===xt.FREE_SLACK_HOURS||e===xt.IS_CRITICAL}function ns(e){return e===w.PARENT||e===w.CORRELATIVE_ID}function os(e,t){t!==w.START_DATE&&t!==w.END_DATE&&t!==w.TYPE||(e.calendarDuration=ie(e))}function as(e,t){return e.filter(r=>String(r)!==String(t))}function Yu(e,t,r){let i=e.get(t);i?i.push(r):e.set(t,[r])}function av(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 ss(e,t){let r=e.getActivity(t);return r?F(r):null}function Gu(e){return e.getAllActivities().map(F)}function $u(e){return e.getAllIds().map(String)}function zu(e,t){e.forEachActivity((r,i)=>t(i))}function qu(e,t){let r=t==="0"?cs(e,"0"):e.getChildren(t),i=[];for(let n of r){let o=e.getActivity(n);o&&i.push(F(o))}return i.sort((n,o)=>(n.correlativeId??0)-(o.correlativeId??0)),i}function cs(e,t){return jt(t,e)}function Ju(e){return e.checkedIds().map(String)}function Xu(e,t){if(t==="0"){let r=!1;return e.forEachActivity(i=>{r||=B(i.parentId)}),r}return e.getChildren(t).length>0}function ls(e,t){let r=e.getLink(t);return r?Ut(r):null}function Zu(e){return e.getAllLinks().map(t=>Ut(t))}function io(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function sv(e){return e.reduce((t,r)=>io(r)<io(t)?r:t)}function cv(e){return e.reduce((t,r)=>io(r)>io(t)?r:t)}function lv(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Qu(e){let t=[...e].find(o=>o.is_default);if(!t)return null;let r=lv(t);if(r.length===0)return null;let i=r.map(o=>o.split("-")[0]),n=r.map(o=>o.split("-")[1]);return{startHour:sv(i),endHour:cv(n)}}function ds(e,t){return{calendars:e.calendarReader,hierarchy:Uu(e),activityReader:xu(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function tp(e){return rr(e)}var dv=new Set(["freeSlackHours","isCritical"]);function uv(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([i])=>!t.has(i)));return e.kind===b.UPDATED&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function np(e){let t=e.activities.map(n=>({...n,after:null})),r=e.links.map(n=>uv(n,dv)).filter(n=>n!==null),i=e.source.kind===Ie?{...e.source,items:[],links:[]}:e.source;return F({...e,source:i,activities:t,links:r})}function us(e,t,r,i,n,o,a){return{changeSet:e,beforeSnap:t,beforeLinks:ep(r),afterSnap:i,afterLinks:ep(n),progressFallbackBefore:o,progressFallbackAfter:a}}function ep(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function op(e,t){let r=new Map,i=new Map;for(let n of t.activities){if(n.kind!==b.CREATED)continue;let o=e.getActivity(String(n.id));o&&r.set(String(n.id),it(o))}for(let n of t.links){if(n.kind===b.DELETED)continue;let o=e.getLink(String(n.id));o&&i.set(String(n.id),{...o})}return{afterSnap:r,afterLinks:i}}function ap(e){return e.kind!==h.INLINE_EDIT||!pi.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function rp(e){return e.changeSet.activities.length===1&&e.changeSet.activities[0]?.kind===b.UPDATED&&e.changeSet.links.length===0&&!e.beforeSnap?.size&&!e.afterSnap?.size}function sp(e,t){if(!rp(e)||!rp(t))return!1;let r=e.changeSet.activities[0],i=t.changeSet.activities[0];return!!r&&!!i&&String(r.id)===String(i.id)}function cp(e,t){let r=e.changeSet.activities[0],i=t.changeSet.activities[0];if(!r||!i)return t;let n=r.fields??{},o=i.fields??{},a={};for(let c of new Set([...Object.keys(n),...Object.keys(o)])){let l=n[c],d=o[c];a[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let s={...t.changeSet,activities:[{...i,fields:a}]};return us(s)}var Vr={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},pt={BEFORE:"before",AFTER:"after"};function lp(e){return e.kind===h.PERSISTENCE_ACKNOWLEDGE?Vr.CHECKPOINT_ON_SUCCESS:e.kind===h.SIR_SYNC||e.kind===h.CALENDAR_RECONCILE||e.kind===h.ACTIVITY_LOOKAHEAD_SYNC||e.kind===h.BASELINE_APPLY||e.kind===h.PONDERATOR_CRITERION_SET||e.kind===h.STATUS_CRITERIA_SET||e.kind===h.ACTIVITY_CLIPBOARD_CLEAR||e.kind===h.ACTIVITY_COPY||e.kind===h.SELECTION_TOGGLE||e.kind===h.SELECTION_REPLACE||e.kind===h.VISIBILITY_SET||e.kind===h.FILTER_SET||e.kind===h.SORT_SET||e.kind===h.VIEW_ATTRIBUTES_SET||e.kind===h.GROUP_SET||e.kind===h.WBS_DEPTH_SET?Vr.SKIP:Vr.RECORD}function ps(e){for(let t of e.changeSet.activities)if(t.kind===b.CREATED||t.kind===b.DELETED||t.kind===b.UPDATED&&t.fields&&E.CUSTOM_ID in t.fields)return!0;return!1}function fs(e,t,r){let i=[],n=[];for(let a of t.changeSet.activities){let s=String(a.id);if(a.kind===b.UPDATED){let c=e.getActivity(s);i.push({id:s,kind:b.UPDATED,fields:ip(a.fields,r),after:c?it(c):null})}else if(a.kind===b.DELETED)if(r===pt.BEFORE){let c=e.getActivity(s);i.push({id:s,kind:b.CREATED,after:c?it(c):null})}else i.push({id:s,kind:b.DELETED,after:null});else if(r===pt.BEFORE)i.push({id:s,kind:b.DELETED,after:null});else{let c=e.getActivity(s);i.push({id:s,kind:b.CREATED,after:c?it(c):null})}}for(let a of t.changeSet.links){let s=String(a.id);if(a.kind===b.UPDATED){let c=e.getLink(s);n.push({id:s,kind:b.UPDATED,fields:ip(a.fields,r),after:c?Ut(c):null})}else if(a.kind===b.DELETED)if(r===pt.BEFORE){let c=e.getLink(s);n.push({id:s,kind:b.CREATED,after:c?Ut(c):null})}else n.push({id:s,kind:b.DELETED,after:null});else if(r===pt.BEFORE)n.push({id:s,kind:b.DELETED,after:null});else{let c=e.getLink(s);n.push({id:s,kind:b.CREATED,after:c?Ut(c):null})}}let o=(t.changeSet.viewState??[]).map(a=>r===pt.BEFORE?pv(a):a);return{source:{kind:r===pt.BEFORE?ne.UNDO:ne.REDO},activities:i,links:n,calendars:[],trackingEvents:[],effects:[],viewState:o}}function ip(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,t===pt.BEFORE?{before:F(i.after),after:F(i.before)}:{before:F(i.before),after:F(i.after)}]))}function pv(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 ys(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function dp(e,t){pp(e,t,pt.BEFORE)}function up(e,t){pp(e,t,pt.AFTER)}function pp(e,t,r){let i=t.changeSet;for(let o of i.activities)if(o.kind===b.UPDATED){if(!o.fields)continue;for(let[a,s]of Object.entries(o.fields))Tt(e,o.id,a,r===pt.BEFORE?s.before:s.after)}else if(o.kind===b.DELETED)if(r===pt.BEFORE){let a=t.beforeSnap?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);e.addActivity(it(a))}else e.removeActivity(String(o.id));else if(r===pt.BEFORE)e.removeActivity(String(o.id));else{let a=t.afterSnap?.get(String(o.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${o.id}`);e.addActivity(it(a))}for(let o of i.links)if(o.kind===b.UPDATED){if(!o.fields)continue;let a=e.getLink(String(o.id)),s=o.fields[xt.SOURCE],c=o.fields[xt.TARGET];a&&(s||c)&&e.setLinkEndpoints(String(o.id),String(s?r===pt.BEFORE?s.before:s.after:a.source),String(c?r===pt.BEFORE?c.before:c.after:a.target));for(let[l,d]of Object.entries(o.fields))l===xt.SOURCE||l===xt.TARGET||ml(e,String(o.id),l,r===pt.BEFORE?d.before:d.after)}else if(o.kind===b.DELETED)if(r===pt.BEFORE){let a=t.beforeLinks?.get(String(o.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${o.id}`);e.addLink(a)}else e.removeLink(String(o.id));else if(r===pt.BEFORE)e.removeLink(String(o.id));else{let a=t.afterLinks?.get(String(o.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${o.id}`);e.addLink(a)}for(let o of i.viewState??[])o.checked&&e.setChecked(o.activityId,r===pt.BEFORE?o.checked.before:o.checked.after),o.visible&&e.setVisible(o.activityId,r===pt.BEFORE?o.visible.before:o.visible.after);let n=r===pt.BEFORE?t.progressFallbackBefore:t.progressFallbackAfter;for(let[o,a]of n??[])e.setProgressFallback(o,a)}var fv=100,yv=600,no=class e{constructor(t=fv){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...F(this.undoStack)),t.redoStack.push(...F(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<=yv&&n!==void 0&&sp(n.entry,t)?(n.entry=cp(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:o,proplannerId:a})=>[String(o),a])),n=new Map(r.map(({id:o,proplannerId:a})=>[String(o),a]));for(let o of[...this.undoStack,...this.redoStack])o.entry=this.withPersistedIdentities(o.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=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,r.has(s)?{...c,proplannerId:r.get(s)}:c])),o=a=>a===void 0?void 0:new Map(Array.from(a,([s,c])=>[s,i.has(s)?{...c,proplannerId:i.get(s)}:c]));return{...t,beforeSnap:n(t.beforeSnap),afterSnap:n(t.afterSnap),beforeLinks:o(t.beforeLinks),afterLinks:o(t.afterLinks)}}};var hv=["parentId","correlativeId"];function yp(e,t){let r=new Set,i=n=>{let o=t(n);r.add(o===null?"0":String(o))};for(let n of e.activities){let o=String(n.id);if(n.kind===b.CREATED){i(o);continue}if(n.kind===b.DELETED){let c=n.fields;c&&"parentId"in c&&r.add(fp(c.parentId?.before));continue}let a=n.fields;!a||!hv.some(c=>c in a)||(i(o),"parentId"in a&&r.add(fp(a.parentId?.before)))}return r}function fp(e){return e==null?"0":String(e)}function mv(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Iv(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function hp(e){return{id:String(e.id),worktime:Iv(e.worktime)}}function oo(e,t,r,i=[]){let n=t.map(mv),o=[...r.map(hp),...i.map(hp)];return{activities:[...e],links:n,calendars:o}}var x={TRACKED:"tracked",IGNORED:"ignored"};var mp={id:x.IGNORED,proplannerId:x.IGNORED,parentId:x.TRACKED,name:x.TRACKED,description:x.TRACKED,type:x.TRACKED,startDate:x.TRACKED,endDate:x.TRACKED,durationHours:x.TRACKED,constraintType:x.TRACKED,constraintDate:x.TRACKED,autoScheduling:x.TRACKED,calendarId:x.TRACKED,assignedDefaultCalendar:x.IGNORED,dateOrigin:x.TRACKED,progress:x.TRACKED,cost:x.TRACKED,usedCost:x.TRACKED,realCost:x.TRACKED,workHours:x.TRACKED,realWorkHours:x.TRACKED,ponderator:x.TRACKED,hasCustomPonderator:x.TRACKED,correlativeId:x.TRACKED,uniqueCorrelativeId:x.TRACKED,customId:x.TRACKED,subcontractId:x.TRACKED,isLookahead:x.TRACKED,hasLookaheadTasks:x.IGNORED,newActivityIds:x.TRACKED,hasNewActivities:x.TRACKED,isNewActivity:x.IGNORED,pendingRequestIds:x.IGNORED,responsableIds:x.TRACKED,tagIds:x.TRACKED,baselinePoints:x.IGNORED,baselineSnapshot:x.IGNORED,recursiveDurationHours:x.IGNORED,isCritical:x.IGNORED,freeSlackHours:x.IGNORED,calendarDuration:x.IGNORED,baselineVarianceDays:x.IGNORED,expectedProgress:x.IGNORED,expectedProgressBaseline:x.IGNORED,status:x.IGNORED,criticalPath:x.IGNORED},Ip=Object.keys(mp).filter(e=>mp[e]===x.TRACKED),gp=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Ap=new Set(["newActivityIds","responsableIds","tagIds"]);function vp(e){let t=Ip.map(r=>[r,gv(r,e[r])]);return Object.fromEntries(t)}function gv(e,t){return gp.has(e)?t instanceof Date?new Date(t):null:Ap.has(e)?Array.isArray(t)?[...t]:[]:t}function Ai(e,t){return hs(e,t).length>0}function hs(e,t){return Ip.filter(r=>!Av(r,e[r],t[r]))}function Av(e,t,r){return gp.has(e)?vv(t,r):Ap.has(e)?Cv(t,r):(t??null)===(r??null)}function vv(e,t){let r=e instanceof Date?e.getTime():null,i=t instanceof Date?t.getTime():null;return r===i}function Cv(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 Cp={id:x.IGNORED,source:x.TRACKED,target:x.TRACKED,type:x.TRACKED,lag:x.TRACKED,freeSlackHours:x.IGNORED,isCritical:x.IGNORED,ganttId:x.IGNORED,sectorId:x.IGNORED,proplannerId:x.IGNORED},Sv=Object.keys(Cp).filter(e=>Cp[e]===x.TRACKED);function ao(e,t){return Sv.some(r=>e[r]!==t[r])}function Sp(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?ao(n,i):!1})}function te(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 Tp(e,t){for(let r of e)te(r.proplannerId);for(let r of t)te(r.proplannerId)}var so=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,F(i));for(let[r,i]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,F(i));return t}init(t,r){if(this.trackingEnabled){Tp(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=[],o,a){if(!this.trackingEnabled)return;let s=new Map(i.map(({id:f,proplannerId:y})=>[String(f),y])),c=new Map(n.map(({id:f,proplannerId:y})=>[String(f),y])),l=t.map(f=>({...f,proplannerId:s.get(String(f.id))??f.proplannerId})),d=r.map(f=>{let y=c.get(String(f.id));return y===void 0?{...f}:{...f,proplannerId:y}});if(Tp(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!o||!a)return;let u=new Map(o.map(f=>[String(f.id),f])),p=new Map(a.map(f=>[String(f.id),f]));for(let f of l){let y=String(f.id);this.activityIsDirty(y,u.get(y)??null)&&this.dirtyActivityIds.add(y)}for(let f of o){let y=String(f.id);this.activityIsDirty(y,f)&&this.dirtyActivityIds.add(y)}for(let f of d){let y=String(f.id);this.linkIsDirty(y,p.get(y)??null)&&this.dirtyLinkIds.add(y)}for(let f of a){let y=String(f.id);this.linkIsDirty(y,f)&&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(!te(r.proplannerId)){this.dirtyActivityIds.add(i);continue}let n=vp(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}}),Ai(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(!te(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 o of t){let a=String(o.id),s=i(a);this.activityIsDirty(a,s)?this.dirtyActivityIds.add(a):this.dirtyActivityIds.delete(a)}for(let o of r){let a=String(o.id),s=n(a);this.linkIsDirty(a,s)?this.dirtyLinkIds.add(a):this.dirtyLinkIds.delete(a)}}}activityIsDirty(t,r){let i=this.activitiesAtLastSave.get(t);return r===null?i!==void 0:this.initialCalendarRepairIds.has(t)||!te(r.proplannerId)||i===void 0||Ai(r,i.persistable)}linkIsDirty(t,r){let i=this.linksAtLastSave.get(t);return r===null?i!==void 0:!te(r.proplannerId)||i===void 0||ao(i,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let i=t.map(n=>{let o=typeof n=="string"?n:String(n.id),a=r(o),s=this.activitiesAtLastSave.get(o);if(a===null||s===void 0)throw new Error(`unknown persisted activity "${o}"`);return{activityId:o,acknowledgesLookahead:typeof n=="string"||!!n.fields?.isLookahead,acknowledgesProgress:typeof n!="string"&&!!n.fields?.progress,current:a,saved:s}});for(let{activityId:n,acknowledgesLookahead:o,acknowledgesProgress:a,current:s,saved:c}of i){let l={...c.persistable,...o?{isLookahead:s.isLookahead}:{},...a?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(n,{...c,persistable:l}),this.initialCalendarRepairIds.has(n)||!te(s.proplannerId)||Ai(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&&!te(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&&!te(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||!te(n.proplannerId))continue;let o=this.activitiesAtLastSave.get(i);(o===void 0||this.initialCalendarRepairIds.has(i)||Ai(n,o.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),o=this.activitiesAtLastSave.get(i);if(!n||!o)continue;let a=hs(n,o.persistable);a.length>0&&r.set(i,a)}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||!te(n.proplannerId))continue;let o=this.linksAtLastSave.get(i);(o===void 0||ao(o,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 Dp=1440*60*1e3,Ep=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,co=7,ms=[!1,!0,!0,!0,!0,!0,!1],_p=new Set(["1","true"]),Is=It.DURATION,kp=C.ASAP,Rp={ASAP:C.ASAP,ALAP:C.ALAP,SNET:C.SNET,SNLT:C.SNLT,FNET:C.FNET,FNLT:C.FNLT,MSO:C.MSO,MFO:C.MFO,"AS SOON AS POSSIBLE":C.ASAP,"AS LATE AS POSSIBLE":C.ALAP,"START NO EARLIER THAN":C.SNET,"START NO LATER THAN":C.SNLT,"FINISH NO EARLIER THAN":C.FNET,"FINISH NO LATER THAN":C.FNLT,"MUST START ON":C.MSO,"MUST FINISH ON":C.MFO};function Pp(e,t){let r=[],i=e.map(o=>{let a=Nv(o,t);return o.should_be_showed===!1&&r.push(a.id),a});wv(i);let n=new Set(i.map(o=>o.id));return Fv(i,n,t.reporter,t.recordDiagnostic),{activities:i,activityIds:n,hiddenIds:r}}function Tv(e,t,r,i){if(!e)return null;let n=Rp[e.toUpperCase()];return n===void 0?(r(Nt.UNKNOWN_CONSTRAINT,i),t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),kp):n}function Dv(e,t,r){let i=Tv(e.constraint,t,r,String(e.unique_id)),o=i!==C.ASAP&&i!==C.ALAP&&e.constraint_date?fe(e.constraint_date):null;return{constraintType:i,constraintDate:o}}function Ev(e,t,r){if(e==null)return r;let i=String(e);return t.has(i)?i:r}function _v(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 kv(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function gs(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)kv(r)&&t.push(String(r.id));return t}function Rv(e){return e==="0"?null:String(e)}function Pv(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 Lv(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 Ov(e,t,r,i,n){return Array.isArray(e)?e.map(o=>qn(o,t,{record:r,sampleId:i},n)).filter(o=>o!==null):[]}function Nv(e,t){let r=Ev(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),i=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),n=Number(e.progress),{constraintType:o,constraintDate:a}=Dv(e,t.reporter,t.recordDiagnostic),s=e.type===D.MILESTONE,c=fe(e.start_date),l=s?c:fe(e.end_date),d=s?0:Number(e.duration),u=Lv(e,t.reporter);return{id:String(e.unique_id),proplannerId:Pv(e.id),parentId:Rv(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ge(d,t.hoursPerDay),constraintType:o,constraintDate:a,autoScheduling:Ke(n),calendarId:r,assignedDefaultCalendar:r!=null&&i,dateOrigin:e.date_origin==null?null:fe(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:bv(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:_v(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:gs(e.pendingRequests),responsableIds:gs(e.responsables),tagIds:gs(e.tags),baselinePoints:Ov(e.baseline_points,t.reporter,t.recordDiagnostic,String(e.unique_id),s),baselineSnapshot:null,baselineVarianceDays:null,recursiveDurationHours:Ge(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:ie({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function bv(e){return e.has_childs?null:e.custom_id}function wv(e){let t=e.find(r=>r.correlativeId===0&&r.type===D.PROJECT);t&&(t.parentId=null)}function Fv(e,t,r,i){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)`),i(Nt.ORPHAN_ACTIVITY,n.id),n.parentId=null))}function bp(e,t,r,i=null){let a=(e!==void 0&&e.length>0?e:t??[]).map(c=>Mv(c,i)),s=(r??[]).map(c=>Uv(c,i));return{calendars:a,baseCalendars:s,knownCalendarIds:new Set(a.map(c=>c.id)),defaultCalendarId:xv(a)}}function xv(e){let t=e.find(i=>i.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function wp(e,t){let r=Kv(e.working_days),{days:i,hours:n}=jv(e,r),o=Bv(t.exceptionsSource,t.exceptionRange),a={days:i,hours:n};return o&&(a.dates=o),{id:`${String(e.id)}${t.idSuffix}`,name:e.name,is_default:t.isDefault,...t.baseDefault!==void 0?{baseDefault:t.baseDefault}:{},worktime:a}}function Mv(e,t){let r=e.baseDefault,i=typeof r=="boolean"?r:void 0;return wp(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:i,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Uv(e,t){return wp(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Bv(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let i of e){if(!i)continue;let n=Wv(i.from_date,i.to_date,t);if(n.length===0)continue;let o=Hv(i);if(o!==void 0)for(let a of n)r[a]=o}return Object.keys(r).length>0?r:null}function Wv(e,t,r){let i=Lp(e),n=Lp(t);if(i===null||n===null)return[];if(r&&(n<r.start||i>r.end))return[];let o=[],a=r?Math.max(i,r.start):i,s=r?Math.min(n,r.end):n;for(;a<=s;)o.push(String(a)),a+=Dp;return o}function Lp(e){if(typeof e!="string")return null;let t=Ep.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 Hv(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=Vv(t);if(r.length>0)return r}}var Op=/^\d{1,2}:\d{2}$/;function Vv(e){let t=[];for(let r of e){let i=Mp(r?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),c=i.endsCsv.trim();!lo(s)&&!lo(c)&&Op.test(s)&&Op.test(c)&&t.push(`${s}-${c}`);continue}let a=xp(i.startsCsv,i.endsCsv).find(s=>s!==null);a&&t.push(a)}return t.sort(Fp),t}function Np(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 Fp(e,t){return Np(e)-Np(t)}function jv(e,t){let r=Array.from({length:7},()=>[]),i=(l,d)=>{let u=xp(l,d);for(let p=0;p<7;p+=1){let f=u[p],y=r[p];f&&y&&y.push(f)}},n=Array.isArray(e.shifts)&&e.shifts.length>0,o=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(n)for(let l of e.shifts){let d=Mp(l?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else o&&i(e.shift_start,e.shift_end);for(let l of r)l.sort(Fp);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 xp(e,t){let r=Array.from({length:co},()=>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<=co))return r;let a=[...r];for(let s=0;s<i.length;s+=1){let c=i[s],l=n[s];lo(c)||lo(l)||(a[s]=`${c}-${l}`)}return a}function Mp(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 Kv(e){if(typeof e!="string")return[...ms];let t=e.split(",").map(r=>r.trim());return t.length!==co?[...ms]:t.map(r=>_p.has(r))}var Yv=new Set(["false","null"]);function lo(e){return!e||Yv.has(e)}function Gv(e){if(typeof e!="string")return null;let t=Lc(e);return t||(_i(e)?e:null)}function $v(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 Bp(e,t){let r=[];for(let i of e)try{r.push(zv(i,t.knownActivityIds,t.hoursPerDay))}catch(n){t.recordDiagnostic(Nt.INVALID_LINK,String(i.unique_id??i.id)),t.reporter.warn("[parseFromBackend] dropping invalid link",n)}return qv(r,t.recordDiagnostic)}function zv(e,t,r){let i=String(e.unique_id??e.id),n=String(e.source_id??e.source??""),o=String(e.target_id??e.target??"");if(!t.has(n))throw new Error(`[parseFromBackend] link "${i}" source "${n}" does not exist`);if(!t.has(o))throw new Error(`[parseFromBackend] link "${i}" target "${o}" does not exist`);let a=Gv(e.type);if(a===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(e.type)}"`);let s=e.ganttId,c=e.sectorId,l=$v(e.id);return{id:i,source:n,target:o,type:a,lag:Kt(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 qv(e,t){let r=new Map;for(let i of e){let n=`${i.source}-${i.target}-${i.type}`,o=r.get(n);if(!o){r.set(n,i);continue}let a=Up(i)>Up(o),s=a?o:i;t(Nt.DUPLICATE_LINK,s.id),a&&r.set(n,i)}return[...r.values()]}function Up(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Jv(e){if(typeof e!="string")return Is;switch(e.toUpperCase()){case It.DURATION:return It.DURATION;case It.COST:return It.COST;case It.WORK_HOURS:return It.WORK_HOURS;default:return Is}}function Xv(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function Zv(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Wp(e){let t=Xv(e),r=Zv(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:Jv(e.activity_creter),statusCriteria:Qo,ganttId:null}}function uo(e,t=Ar,r=Br){let i=Wp(e.sector),{calendars:n,baseCalendars:o,knownCalendarIds:a,defaultCalendarId:s}=bp(e.calendars,e.sector.calendars,e.baseCalendars,Qv(e.activities)),{activities:c,activityIds:l,hiddenIds:d}=Pp(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:i.hoursPerDay,reporter:t,recordDiagnostic:r}),u=Bp(e.links,{knownActivityIds:l,hoursPerDay:i.hoursPerDay,reporter:t,recordDiagnostic:r});return{sector:i,activities:c,links:u,calendars:n,baseCalendars:o,viewStateSeed:{hiddenIds:d}}}function Qv(e){let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o of e){let a=new Date(o.start_date).getTime(),s=new Date(o.end_date).getTime();Number.isFinite(a)&&(t=Math.min(t,a)),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 As(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 As({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 vs(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 vs({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 Cs(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 Cs({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 Hp(e){return!!e&&typeof e=="string"&&e.trim().length>0}function po(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function fo(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Vp(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function jp(e,t){return!t&&Hp(e)}function Kp(e,t){return t&&Hp(e)}function vi(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function yo(e){if(!vi(e))return 0n;try{return BigInt(e)}catch{return 0n}}function tC(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!vi(t))return r;let i=t.length;return r.padStart(i,"0")}function $t(e,t){let r=yo(e),i=yo(t),n=r+i;return tC(n,e)}function ho(e,t){let r=yo(e),i=yo(t);return r<i?-1:r>i?1:0}function mo(e,t){return ho(e,t)<=0?e:t}function Io(e,t){return ho(e,t)>=0?e:t}function Yp(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>mo(t,r))}function Gp(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Io(t,r))}var he={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function $p(e){return{prefix:e,baseSuffix:null}}function zp(e,t){let r=fo(e);return{prefix:po(e),baseSuffix:$t(r,t)}}function qp(e){return{prefix:e,baseSuffix:null}}function Jp(e,t){return jp(e,t)?he.PARENT_CONVERSION:Kp(e,t)?he.PASTE_REFERENCE:he.NO_CONTEXT}function Xp(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var go=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?Xp(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=Yp(i),r.max=Gp(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,Xp(i));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return po(t)}extractSuffix(t){return fo(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=mo(r,i.min),i.max=Io(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=mo(i,n.min),n.max=Io(i,n.max),n.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:i,max:i,next:$t(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}${$t(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let i=r&&vi(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(;ho(i,r.max)<0;){if(`${t}${i}`.length>20)return null;if(!r.usedSuffixes.has(i))return i;i=$t(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||!vi(r)){let s=$t(i.max,n);return`${t}${s}`.length>20?null:s}let o=r;for(let s=0;s<100;s++){if(`${t}${o}`.length>20)return null;if(!i.usedSuffixes.has(o))return o;o=$t(o,n)}let a=$t(i.max,n);return`${t}${a}`.length>20?null:a}generateNextCustomId(t){let r=this.getNextAvailableSuffix(t);if(r===null)return this._generateDefaultCustomId();if(this.prefixMap.has(t)){let n=this.prefixMap.get(t),o=0;for(;n.usedSuffixes.has(r)&&o<1e4;){let a=this.getNextAvailableSuffix(t,$t(r,this.suffixIncrement));if(a===null)return this._generateDefaultCustomId();r=a,o++}}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:o}=this.analyzeCustomId(i);(n||o)&&(this._updatePrefixStats(n,o),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:i=!1}=t,n=Vp(r),o=Jp(n,i),{prefix:a,baseSuffix:s}=this._applyGenerationStrategy(o,n),c=null;if(o===he.PARENT_CONVERSION&&this.prefixMap.has(a)){this._ensureFreshBounds(a);let p=this.prefixMap.get(a).max;c=$t(p,this.suffixIncrement)}o===he.PARENT_CONVERSION&&this.releaseCustomId(n);let l=o===he.PARENT_CONVERSION&&c?c:s,d=this.getNextAvailableSuffix(a,l);if(d===null){let p=this._generateDefaultCustomId();return this.registerCustomId(p),p}let u=`${a}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(t,r){switch(t){case he.PARENT_CONVERSION:return $p(this.defaultPrefix);case he.PASTE_REFERENCE:return zp(r,this.suffixIncrement);default:return qp(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let i=t.trim();if(i.length>0){let n=this.extractPrefix(i),o=this.extractSuffix(i),a=$t(o,this.suffixIncrement),s=this.getNextAvailableSuffix(n,a);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 eC=1,rC=-1;function iC(e,t){if(e===void 0&&t===void 0)return 0;if(e===void 0)return eC;if(t===void 0)return rC;let r=Math.min(e.length,t.length);for(let i=0;i<r;i+=1){let n=(e[i]??0)-(t[i]??0);if(n!==0)return n}return e.length-t.length}function Zp(e,t,r,i){let n=r.assignmentByActivityId.get(String(e.id)),o=r.assignmentByActivityId.get(String(t.id)),a=iC(n===void 0?void 0:r.sequencePathByValueId.get(n),o===void 0?void 0:r.sequencePathByValueId.get(o));return i===Pt.DESCENDING?-a:a}var nC=1,oC=-1;function aC(e,t){return!e&&!t?null:e&&t?0:e?nC:oC}function Qp(e){return e==null}function tf(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function sC(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 cC(e,t,r){if(yr(e)){let n=r.get(e.key);return n===void 0?null:(o,a)=>Zp(o,a,n,e.direction)}let i=ge(e.field);return i===null?null:(n,o)=>{let a=i.extract(n,t),s=i.extract(o,t),c=aC(Qp(a),Qp(s));if(c!==null)return c;let l=i.valueKind===L.ENUM?tf(a,i.order)-tf(s,i.order):sC(a,s,t.locale);return e.direction===Pt.DESCENDING?-l:l}}function ef(e,t,r=wi){let i=e.rules.map(n=>cC(n,t,r)).filter(n=>n!==null);return i.length===0?null:(n,o)=>{for(let a of i){let s=a(n,o);if(s!==0)return s}return 0}}function rf(e){let t=[];e.forEachActivity((r,i)=>{r.type===D.PROJECT&&e.getChildren(String(i)).length===0&&t.push(String(i))});for(let r of t)e.setActivityField(r,w.TYPE,Ir),lC(e,r)}function lC(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:Y.FUTURE,task:r});if(n.getTime()===r.startDate.getTime())return;let o=e.calculateEndDate({startDate:n,durationHours:r.durationHours,task:r});e.setActivityField(t,w.START_DATE,n),e.setActivityField(t,w.END_DATE,o)}function nf(e){let t=[],r=[];e.forEachActivity((n,o)=>{n.parentId===null&&t.push(String(o))});let i=n=>{let o=e.getActivity(n);if(!o)return 0;let a=[...e.getChildren(n)],s=a.length===0?Mt(o.workHours,o.progress):a.reduce((c,l)=>c+i(String(l)),0);return e.setActivityField(n,w.REAL_WORK_HOURS,s),r.push(n),s};for(let n of t)i(n);return r}async function of(e){let{state:t,sector:r,scheduler:i,skipAutoSchedule:n,now:o}=e;if(kt(t),r.updateDurationForPrimaveraEndDate&&uC(t),pC(t),nf(t),n){ri(t),o&&(Xe(t,o),ye(t,r.statusCriteria)),Ze(t,r.hoursPerDay);return}let a=await i.schedule({});Qr(t,a),fC(t),dC(t),await Cr(t,void 0,!1),ri(t),o&&(Xe(t,o),ye(t,r.statusCriteria)),Ze(t,r.hoursPerDay)}function dC(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=ie(t))})}function uC(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function pC(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let i=t.constraintDate;if(t.type===D.MILESTONE&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=ue(t.constraintDate,n,r))})}function fC(e){e.forEachActivity(t=>{if(t.type!==D.MILESTONE)return;let r=t.constraintType;if(!r||!t.constraintDate)return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=ue(t.constraintDate,i,r))})}var ee={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function af(e){let t=e.clock??null,r=t?.()??null,i=r?fn(r):null,n=e.reporter??Ar,o=ru(),a=uo({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n,o.record),s=a.sector;s.statusCriteria=_n(e.statusCriteria),s.ganttId=e.ganttId??null;let c=a.calendars,l=a.baseCalendars??[],d=oo(a.activities,a.links,a.calendars,l),u=(O,T)=>ef(O,je(s.hoursPerDay),T),p=new Hr(d,u);p.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new vr(p,n);rf(p);let y=As({knownIds:a.activities.map(O=>O.id)}),m=vs({seed:r?.getTime()??0,knownIds:a.links.map(O=>O.id)}),g=Cs({knownIds:a.activities.map(O=>O.uniqueCorrelativeId)}),_=new go({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(_.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let O=l.find(T=>T.baseDefault)?.id??null;Jn(p,e.baselinePoints,i,n,O,o.record)}let k=of({state:p,sector:s,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:i??void 0});return{sector:s,state:p,scheduler:f,activityIdGen:y,linkIdGen:m,uidGen:g,customIdTracker:_,calendars:c,baseCalendars:l,clock:t,reporter:n,loadDiagnostics:o.snapshot,initPromise:k}}function jr(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(jr)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[jr(t),jr(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,jr).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,jr(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function ar(e){return JSON.stringify(jr(e))}function Ss(e,t){let r=new Map(e.map(a=>[String(a.id),a])),i=new Map(t.map(a=>[String(a.id),a])),n=[...new Set([...r.keys(),...i.keys()])].sort(),o=[];for(let a of n){let s=i.get(a),c=r.get(a);if(c===void 0){o.push({id:a,kind:b.DELETED,after:null});continue}if(s===void 0){o.push({id:a,kind:b.CREATED,after:F(c)});continue}let l=yC(s,c);Object.keys(l).length>0&&o.push({id:a,kind:b.UPDATED,fields:l,after:F(c)})}return o}function yC(e,t){let r={},i=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let n of i)ar(e[n])!==ar(t[n])&&(r[n]={before:F(e[n]),after:F(t[n])});return r}function hC(e,t){let r=new Set(t.selectedIds.map(String)),i=new Set(e.selectedIds.map(String)),n=new Set(t.hiddenIds.map(String)),o=new Set(e.hiddenIds.map(String)),a=e.activities.map(({id:c})=>String(c)).sort(),s=[];for(let c of a){let l=r.has(c),d=i.has(c),u=!n.has(c),p=!o.has(c);l===d&&u===p||s.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===p?{}:{visible:{before:u,after:p}}})}return s}function Ts(e,t){let r=ar(e.order)!==ar(t.order);return{source:{kind:ne.INIT},activities:Ss(e.activities,t.activities),links:Ss(e.links,t.links),calendars:Ss(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:hC(e,t),...r?{order:F(e.order)}:{}}}var Kr={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},mC=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Ds=(e,t)=>e===null?t:Math.min(e,t),Es=(e,t)=>e===null?t:Math.max(e,t);function cf(e,t,r){let i=[...new Set(t.kind===Kr.MOVE?t.activityIds.map(String):[String(t.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let n=IC(e,t,i);return gC(e,i,n),{getDates(o,a){if(r(),!Number.isFinite(a))throw new Error("[ScheduleCore] invalid date gesture edge");let s=n.get(String(o));if(!s)return null;let c=vC(s,a),l=CC(s,a);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(o)}`);return{startTimeMs:c,endTimeMs:l}}}}function IC(e,t,r){let i=new Map,n=t.kind===Kr.MOVE?String(t.anchorActivityId):null,o=n===null?null:sf(e,n);if(n!==null&&!r.includes(n))throw new Error("[ScheduleCore] move anchor is not a participant");for(let a of r){let s=sf(e,a);if(t.kind===Kr.MOVE){let c=o.startDate.getTime();i.set(a,{constantStart:null,variableStartOffset:s.startDate.getTime()-c,constantEnd:null,variableEndOffset:s.endDate.getTime()-c})}else t.kind===Kr.RESIZE_START?i.set(a,{constantStart:null,variableStartOffset:0,constantEnd:s.endDate.getTime(),variableEndOffset:null}):i.set(a,{constantStart:s.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return i}function gC(e,t,r){let i=ni(e,new Set(t));for(let n of i){let o=mC();for(let a of e.getChildren(n)){let s=r.get(a);if(s){AC(o,s);continue}let c=e.getActivity(a);if(!c)throw new Error(`[ScheduleCore] missing child ${a} while previewing parent ${n}`);o.constantStart=Ds(o.constantStart,c.startDate.getTime()),o.constantEnd=Es(o.constantEnd,c.endDate.getTime())}r.set(n,o)}}function sf(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 AC(e,t){t.constantStart!==null&&(e.constantStart=Ds(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Ds(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=Es(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=Es(e.variableEndOffset,t.variableEndOffset))}function vC(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 CC(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 _s=Symbol("ScheduleCore.fork.source");function SC(e){return{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}function TC(e){return e.kind===h.PERSISTENCE_ACKNOWLEDGE||e.kind===h.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0}function DC(e){for(let t of e.activities)if(t.kind===b.DELETED||t.kind===b.UPDATED&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function EC(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 _C(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 Yr=class e{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;_activityClipboard={value:null};_status=ee.READY;coreRuntime;_isFork;_undo=new no;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Object.assign(this,Ns(this)),_s in t){this._isFork=!0;let n=t[_s],o=n.coreRuntime.state.fork();this.coreRuntime={state:o,scheduler:new vr(o,n.coreRuntime.reporter),sector:F(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,([a,s])=>[a,F(s)])),baseCalendars:F(n.coreRuntime.baseCalendars),clock:n.coreRuntime.clock,reporter:n.coreRuntime.reporter,loadDiagnostics:n.coreRuntime.loadDiagnostics},this._activityClipboard.value=F(n._activityClipboard.value),this._undo=n._undo.fork(),this._saveTracker=n._saveTracker.fork(),this._scheduleRevision=n._scheduleRevision,this._stateRevision=n._stateRevision,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=af(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,loadDiagnostics:r.loadDiagnostics},this._initPromise=r.initPromise.then(()=>{this._status!==ee.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({[_s]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return F(this.coreRuntime.sector)}getLoadDiagnostics(){return this.assertReady(),this.coreRuntime.loadDiagnostics()}getActivityView(t){return this.assertReady(),ss(this.coreRuntime.state,t)}calculateCalendarEndDate(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:r}):null}calculateCalendarDuration(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:r}):null}getClosestCalendarWorkTime(t){this.assertReady();let r=this.coreRuntime.state.getActivity(t.activityId);return r?this.coreRuntime.state.getClosestWorkTime({date:t.date,dir:t.direction,task:r}):null}getProgressEditability(t){this.assertReady();let r=ss(this.coreRuntime.state,t);if(!r)return null;let i=ds(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return mn.canEdit(r,i.hierarchy)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return cf(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),Gu(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=zn(t.map(i=>String(i)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(t){return this.assertReady(),qu(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ls(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,i=[],n=new Set,o=a=>{if(n.has(a))return;n.add(a);let s=ls(r,a);s&&i.push(s)};for(let a of r.getOutgoingLinkIds(t))o(a);for(let a of r.getIncomingLinkIds(t))o(a);return i}getAllLinksView(){return this.assertReady(),Zu(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),i=ei(t,r),n=Ji(i),o=0;for(let a of n)a.length>o&&(o=a.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:i.length,circularComponents:n,largestComponentSize:o}}getProperty(t,r){this.assertReady();let i=this.coreRuntime.state.getActivity(t);return i?F(i[r]):null}getAllIds(){return this.assertReady(),$u(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),zu(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),cs(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Ju(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(),F(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),F(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}getVisualRows(){return this.assertReady(),[...this.coreRuntime.state.getVisualRows()]}getActiveGroup(){return this.assertReady(),F(this.coreRuntime.state.getGroup())}getWbsDepth(){return this.assertReady(),this.coreRuntime.state.getWbsDepth()}hasChild(t){return this.assertReady(),Xu(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?F(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>F(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>F(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Qu(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(F)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(F)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(F)}getModifiedActivityFields(){return this.assertReady(),F(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(F)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}getStateRevision(){return this._stateRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}getCanonicalDigest(){this.assertReady();let t=(r,i)=>String(r.id).localeCompare(String(i.id));return ar({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){return this.assertReady(),t.assertReady(),Ts(this._snapshotProjection(),t._snapshotProjection())}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:ve(this.coreRuntime.state)}}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(F)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(F)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return fi(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 dispatchMany(t,r={}){let i=t.some(fi)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(t,r,i))}async applyActivityBatch(t,r={}){let i=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,i))}planLookaheadConversion(t){return this.assertReady(),Ua(t,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(t){return this.dispatch({...t,kind:h.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(t,r={},i=!1){let n=!1;try{let o=await this._runDispatch(t,r);return n=o.changedState,o.result}finally{this._settleScheduleMutation(i,n)}}async _dispatchManyInner(t,r,i){let n=this._snapshotProjection(),o={...r,skipAutoSchedule:!0,skipCriticalPath:!0},a=[],s=[],c=[],l=!1,d=!1,u,p=!1,f=null,y=!1,m=!1;try{for(let g of t){if(g.kind===h.SCHEDULE_AUTO_SCHEDULE){if(g.activityId!==void 0&&!this.coreRuntime.state.activityExists(g.activityId)){a.push({ok:!1,reason:S.ACTIVITY_NOT_FOUND});continue}let k=SC(g);a.push({ok:!0,changes:k}),s.push(k),c.push(g),d=!0,g.activityId===void 0||u!==void 0&&u!==g.activityId?p=!0:u=g.activityId;continue}let _=await this._runDispatch(g,o,!0);a.push(_.result),_.result.ok&&(s.push(_.result.changes),c.push(g)),_.changedState&&(l=!0,d=!0,p=!0)}if(d){let g=p||u===void 0?{kind:h.SCHEDULE_AUTO_SCHEDULE}:{kind:h.SCHEDULE_AUTO_SCHEDULE,activityId:u},_=await this._runDispatch(g,r,!0);_.result.ok&&(f=_.result.changes,s.push(_.result.changes),y=r.skipAutoSchedule!==!0),l||=_.changedState}return l&&this._recordScheduleMutation(f!==null&&r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0),m=!0,{results:a,autoScheduled:y,changeSet:this._aggregateDispatchManyChangeSets(n,s,c)}}finally{!m&&l&&this._recordScheduleMutation(!1),this._settleScheduleMutation(i,m&&l)}}_aggregateDispatchManyChangeSets(t,r,i){if(r.length===0)return null;let n=Ts(this._snapshotProjection(),t),o=r.flatMap(s=>s.effects??[]),a=r.flatMap(s=>s.warnings??[]);return{...n,source:{kind:ne.DISPATCH_MANY,actions:i},trackingEvents:r.flatMap(s=>s.trackingEvents),...o.length===0?{}:{effects:o},...a.length===0?{}:{warnings:a}}}async _runDispatch(t,r,i=!1){if(this.assertReady(),this._isFork&&TC(t))return{result:{ok:!1,reason:S.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=ds(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),o=lp(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,c;try{s=await gu(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:u=>this._saveTracker.hasCheckpointActivityId(u),isLinkIdReserved:u=>this._saveTracker.hasCheckpointLinkId(u),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(u=>u.baseDefault)?.id??null,now:this.coreRuntime.clock?fn(this.coreRuntime.clock()):null});let d=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;d&&d.size>0&&(c=new Map(d)),s.ok||this._rollback(a)}catch(d){throw this._rollback(a),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&o===Vr.RECORD&&ys(s.changes)){let d=op(this.coreRuntime.state,s.changes),u=c?new Map(Array.from(c.keys(),p=>[p,this.coreRuntime.state.getProgressFallback(p)])):void 0;this._undo.record(us(np(s.changes),s.__beforeSnap,s.__beforeLinks,d.afterSnap,d.afterLinks,c,u),ap(t),Date.now())}if(s.ok)if(o===Vr.CHECKPOINT_ON_SUCCESS){if(t.kind!==h.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let d=this.coreRuntime.state.getAllActivities(),u=this.coreRuntime.state.getAllLinks(),p=t.checkpoint,f=p?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(p?.activities??d,p?.links??u,t.activities,t.links,d,u),this._undo.discardThrough(f),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind===h.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,d=>this.coreRuntime.state.getActivity(d)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,d=>this.coreRuntime.state.getActivity(d),d=>this.coreRuntime.state.getLink(d));if(s=this._withReappliedViewState(t,s),!s.ok)return{result:s,changedState:!1};let l=ys(s.changes);return l&&this._stateRevision++,fi(t)&&l?(i||this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&rr(t)),{result:lf(s),changedState:!0}):{result:lf(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===h.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!td(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=yp(t,o=>r.getParentId(o));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:i};if(i.size===0)return{changes:null,touchedParents:i};let n=No(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:ve(i)};let o=new Set(r);for(let s of t.activities){if(s.kind===b.DELETED)return{...t,order:ve(i)};let c=i.getParentId(s.id);o.add(c===null?"0":String(c))}let a=No(i,o);return a.length===0?null:{...t,order:a}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,i=r.getActiveFilter();if(i===null)return null;let n=je(this.coreRuntime.sector.hoursPerDay),o=r.getFilterProjection(),a=_C(o,i,n),s=DC(t)?null:EC(t,r),c,l;if(s===null||!a){let p=Mi({activities:r.getAllActivities(),parentOf:f=>r.getParentId(f),filter:i,context:n,viewAttributeCatalogs:r.getViewAttributeCatalogMap()});r.setFilterProjection(p),l=p.visibleIds,c=r.getAllIds()}else c=zs(o,s,p=>r.getParentId(p)),l=o.visibleIds;let u=Be(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===ee.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 Hr(oo(this.coreRuntime.state.getAllActivities().map(s=>it(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),n=()=>!r.cancelled&&this._status!==ee.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,o=(async()=>{let s=await Da(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)Sa(this.coreRuntime.state,l,d);for(let[l,d]of s.links)Ta(this.coreRuntime.state,l,d);c=await $(this.coreRuntime.state,{source:{kind:ne.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:o};let a=()=>{this._activeCriticalPath?.promise===o&&(this._activeCriticalPath=null)};return o.then(a,a),o}undo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runUndo(t,o=>{i=o})}finally{this._settleScheduleMutation(r,i)}});return n.then(o=>{o&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(a=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",a)})},()=>{}),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;dp(this.coreRuntime.state,i),this._recordScheduleMutation(!1),r(!0),ps(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let n=fs(this.coreRuntime.state,i,pt.BEFORE);return this._saveTracker.recordChanges(n.activities,n.links,o=>this.coreRuntime.state.getActivity(o),o=>this.coreRuntime.state.getLink(o)),this._reapplyViewState(n)??n}}redo(t={}){let r=this._admitScheduleMutation(),i=!1,n=this._enqueue(async()=>{try{return await this._runRedo(o=>{i=o})}finally{this._settleScheduleMutation(r,i)}});return n.then(o=>{o&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(a=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",a)})},()=>{}),n}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;up(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),ps(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let i=fs(this.coreRuntime.state,r,pt.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=ee.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new so;assertReady(){if(this._status===ee.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===ee.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.scheduler.invalidateAllCaches(),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=ee.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function lf(e){let{__beforeSnap:t,__beforeLinks:r,...i}=e;return i}async function df(e){let t=new Yr(e);return await t.ready,t}var uf=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var pf={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 ff=8;var yf={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Cf(kC);})();
|
|
1
|
+
"use strict";var ScheduleCore=(()=>{var ys=Object.defineProperty;var yA=Object.getOwnPropertyDescriptor;var hA=Object.getOwnPropertyNames;var mA=Object.prototype.hasOwnProperty;var gA=(t,e)=>{for(var n in e)ys(t,n,{get:e[n],enumerable:!0})},AA=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of hA(e))!mA.call(t,r)&&r!==n&&ys(t,r,{get:()=>e[r],enumerable:!(i=yA(e,r))||i.enumerable});return t};var IA=t=>AA(ys({},"__esModule",{value:!0}),t);var OO={};gA(OO,{ACTIVITY_BATCH_ACTION_KIND:()=>qe,ACTIVITY_BATCH_MODE:()=>Dt,ACTIVITY_DATE_EDGE:()=>Qi,ACTIVITY_FIELD:()=>Ot,ACTIVITY_PONDERATOR_CRITERION:()=>_t,ACTIVITY_PROGRESS_ORIGIN:()=>Ya,ACTIVITY_TYPE:()=>k,CALENDAR_UNIT:()=>dt,CHANGE_SET_SOURCE_KIND:()=>Ht,COLUMN:()=>E,COMPLETED_PROGRESS:()=>Pt,CONFIRMATION_KIND:()=>wt,CONSTRAINT_TYPE:()=>D,CONSTRAINT_TYPE_TO_LABEL:()=>uA,CONSTRAINT_WARNING_KIND:()=>Un,CREATION_KIND:()=>fA,DATA_DATE_PROPERTY_CONTRACT:()=>dA,DATE_GESTURE_KIND:()=>Jt,DEFAULT_HOURS_PER_DAY:()=>pA,DISPATCH_ACTION_KIND:()=>I,DISPATCH_ACTION_KINDS:()=>ed,DISPATCH_LINK_OPERATION_KIND:()=>ut,DISPATCH_TRACK_EVENT:()=>se,DataDateCapabilityError:()=>ce,EDIT_ALERT_KEY:()=>Ba,EDIT_DENIAL_REASON:()=>ye,ENTITY_CHANGE_KIND:()=>x,FILTER_FIELD:()=>J,FILTER_LOGIC:()=>ni,FILTER_OPERATOR:()=>W,FILTER_REJECTION_REASON:()=>pt,FILTER_VALUE_KIND:()=>F,FLAT_WBS_DEPTH:()=>ea,GROUP_ID_PREFIX:()=>As,GROUP_ID_SEPARATOR:()=>ii,LINK_BATCH_OPERATION_KIND:()=>ti,LINK_CODE:()=>Ft,LINK_CODE_TO_TYPE:()=>Fn,LINK_REJECTION_REASON:()=>yt,LINK_RELATIONSHIP:()=>Pn,LINK_TYPE:()=>H,LINK_TYPE_CODE:()=>Ea,LookaheadActualTransitionError:()=>Wr,MINIMUM_GROUP_DEPTH:()=>ta,MINIMUM_GROUP_LEVEL:()=>Je,NEW_ACTIVITY_DEFAULTS:()=>fo,NOT_STARTED_PROGRESS:()=>Zt,ORDER_DIRECTION:()=>Ut,ORDER_MODE:()=>be,REJECTION_REASON:()=>_,ROOT_PARENT_ID:()=>$,SCHEDULE_CORE_STATUS:()=>Ie,SCHEDULE_EFFECT_KIND:()=>Ga,SIR_AUTO_REJECT_REASON:()=>$a,STATUS:()=>Mt,STATUS_CRITERIA:()=>Ge,ScheduleCore:()=>qi,UNASSIGNED_GROUP_LABEL:()=>Qr,UNASSIGNED_VALUE_ID:()=>On,VIEW_ATTRIBUTE_KIND:()=>kn,VISUAL_ROW_KIND:()=>ri,WORK_TIME_DIRECTION:()=>q,allowedSecondaryConstraintTypes:()=>Ks,appendGroupRowId:()=>ia,buildGroupRowId:()=>na,checkNoUpdatedLinks:()=>Oh,computeExpectedProgress:()=>qs,createLookaheadDerivedFields:()=>cA,createOutbuildDataDateScheduleSettings:()=>ps,createSchedule:()=>aA,expectedProgressFromBaseline:()=>Ci,formatUtcAsP6WallDate:()=>Xg,getActiveBaseline:()=>Lt,getUnsavedActivities:()=>oA,isRootParent:()=>V,isViewAttributeCriterion:()=>Ln,isViewAttributeOrderRule:()=>ai,mapDataDateScheduleOptions:()=>tA,normalizeParentKey:()=>de,parseFromBackend:()=>Wo,parseP6DayAsCalendarStart:()=>ds,parseP6WallDateAsUtc:()=>cs,planLookaheadProgressActuals:()=>Zc,prepareLookaheadProgressActuals:()=>sA,resolveExpectedFinishDateSelection:()=>lA,resolveLookaheadActualDateSelection:()=>fs,willRunCriticalPath:()=>uh,yieldToBrowser:()=>mt});var k={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},SA=Object.values(k);function Xi(t){return SA.includes(t)}var Gr={CONSTRAINT:"constraint",ALERT:"alert",WARNING:"warning"},q={FUTURE:"future",PAST:"past"},dt={MINUTE:"minute",HOUR:"hour",DAY:"day"},_t={DURATION:"DURATION",COST:"COST",WORK_HOURS:"HH"},Ge={BASELINE:"Baseline",ACTUAL:"Actual"},Mt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"},x={CREATED:"created",UPDATED:"updated",DELETED:"deleted"};var D={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},vA={[D.MSO]:()=>!0,[D.MFO]:()=>!0,[D.SNLT]:(t,e)=>t<e,[D.SNET]:(t,e)=>t>e,[D.FNLT]:(t,e)=>t<e,[D.FNET]:(t,e)=>t>e};function qr(t,e,n){if(!e)return{violated:!1};let i=vA[t];return i?i(e,n)?{violated:!0,constraintType:t,constraintDate:e}:{violated:!1}:{violated:!1}}var CA=new Set([D.MSO,D.SNET,D.SNLT]);function En(t,e,n){return CA.has(t)?e:n}function zr(t,e,n){return{type:Gr.CONSTRAINT,messageKey:"constraint_violation",data:{constraintType:t,constraintDate:e,...n?{projectedDate:n}:{}}}}var DA={[D.SNET]:{startOfDay:!0,direction:q.FUTURE},[D.SNLT]:{startOfDay:!0,direction:q.PAST},[D.FNET]:{startOfDay:!1,direction:q.FUTURE},[D.FNLT]:{startOfDay:!1,direction:q.PAST},[D.MSO]:{startOfDay:!0,direction:q.FUTURE},[D.MFO]:{startOfDay:!1,direction:q.PAST}},$r=t=>new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())),Qc=(t,e)=>new Date(t.getTime()+e*864e5),TA=(t,e)=>t.getUTCFullYear()===e.getUTCFullYear()&&t.getUTCMonth()===e.getUTCMonth()&&t.getUTCDate()===e.getUTCDate();function Zi(t,e){if(!t.constraintDate||!t.constraintType)return null;let n=DA[t.constraintType];if(!n)return t.constraintDate;let i=t.constraintDate,r=e.getClosestWorkTime({date:$r(i),dir:q.FUTURE,task:t});if(TA(r,i))return i.getTime()!==$r(i).getTime()?i:n.startOfDay?r:e.getClosestWorkTime({date:Qc($r(i),1),dir:q.PAST,task:t});let a=$r(e.getClosestWorkTime({date:i,dir:n.direction,task:t}));return n.startOfDay?e.getClosestWorkTime({date:a,dir:q.FUTURE,task:t}):e.getClosestWorkTime({date:Qc(a,1),dir:q.PAST,task:t})}function $e(t,e){let n={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},i=t.constraintType;if(!i||i===D.ASAP||i===D.ALAP)return n;let r=Zi(t,e);if(!r)return n;let a=s=>e.calculateEndDate({startDate:s,durationHours:t.durationHours,task:t}),o=s=>e.calculateEndDate({startDate:s,durationHours:-t.durationHours,task:t});switch(i){case D.SNET:return{earliestStart:r,latestStart:null,earliestEnd:a(r),latestEnd:null};case D.SNLT:return{earliestStart:null,latestStart:r,earliestEnd:null,latestEnd:a(r)};case D.FNET:return{earliestStart:o(r),latestStart:null,earliestEnd:r,latestEnd:null};case D.FNLT:return{earliestStart:null,latestStart:o(r),earliestEnd:null,latestEnd:r};case D.MSO:{let s=a(r);return{earliestStart:r,latestStart:r,earliestEnd:s,latestEnd:s}}case D.MFO:{let s=o(r);return{earliestStart:s,latestStart:s,earliestEnd:r,latestEnd:r}}default:return n}}function td(t,e){return!(e.earliestStart&&t<e.earliestStart||e.latestStart&&t>e.latestStart)}function hs(t,e){return e.latestStart&&t>e.latestStart?e.latestStart:e.earliestStart&&t<e.earliestStart?e.earliestStart:t}var H={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"},_A=Object.values(H);function Jr(t){return _A.includes(t)}var Qn={ACTUAL_START:"actualStart",ACTUAL_FINISH:"actualFinish",PLANNED_START:"plannedStart",PLANNED_FINISH:"plannedFinish",REMAINING_DURATION_HOURS:"remainingDurationHours",EXECUTION_STATUS:"executionStatus",EXPECTED_FINISH:"expectedFinish",SUSPEND_DATE:"suspendDate",RESUME_DATE:"resumeDate",SECONDARY_CONSTRAINT_TYPE:"secondaryConstraintType",SECONDARY_CONSTRAINT_DATE:"secondaryConstraintDate",PERCENT_COMPLETE_TYPE:"percentCompleteType",PHYSICAL_PERCENT_COMPLETE:"physicalPercentComplete"},EA={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",...Qn},PA={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",BASELINE_VARIANCE:"baseline_variance",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"},E={...EA,...PA};var Et={CREATE:"create",UPDATE:"update",DELETE:"delete"},yt={SELF_LINK:"self-link",CYCLE:"cycle",DUPLICATE:"duplicate",ACTIVITY_MISSING:"activity-missing",LINK_MISSING:"link-missing",HIERARCHY_LINK:"hierarchy-link"};var I={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_TYPE_SET:"activity-type-set",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_LOOKAHEAD_CONVERT:"activity-lookahead-convert",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",VIEW_ATTRIBUTES_SET:"view-attributes-set",GROUP_SET:"group-set",WBS_DEPTH_SET:"wbs-depth-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync",SCHEDULE_AUTO_SCHEDULE:"schedule-auto-schedule"},qe="activity-batch",ut=Et,ed=Object.values(I);function Lt(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isActiveVersion)??null}var Ot={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"},Qi={START:"start",END:"end"},Pn={FINISH_TO_START:"finish-to-start",START_TO_START:"start-to-start",FINISH_TO_FINISH:"finish-to-finish",START_TO_FINISH:"start-to-finish"},ti={CREATE:"create",UPDATE:"update",REMOVE:"remove"};var RA={[Ot.NAME]:E.TEXT,[Ot.DESCRIPTION]:E.DESCRIPTION,[Ot.DURATION_DAYS]:E.DURATION,[Ot.PROGRESS]:E.PROGRESS,[Ot.COST]:E.COST,[Ot.USED_COST]:E.USED_COST,[Ot.WORK_HOURS]:E.HH_WORK_TIME,[Ot.START_DATE]:E.START_DATE,[Ot.END_DATE]:E.END_DATE,[Ot.CONSTRAINT_TYPE]:E.CONSTRAINT_TYPE,[Ot.CONSTRAINT_DATE]:E.CONSTRAINT_DATE,[Ot.CALENDAR_ID]:E.CALENDAR_ID,[Ot.CUSTOM_ID]:E.CUSTOM_ID,[Ot.SUBCONTRACT_ID]:E.SUBCONTRACT_ID,[Ot.RESPONSABLE_IDS]:E.RESPONSABLES,[Ot.TAG_IDS]:E.TAGS};function ms(t,e){return{activityId:t,column:RA[e.field],newValue:e.value}}var kA={[Pn.FINISH_TO_START]:H.FINISH_TO_START,[Pn.START_TO_START]:H.START_TO_START,[Pn.FINISH_TO_FINISH]:H.FINISH_TO_FINISH,[Pn.START_TO_FINISH]:H.START_TO_FINISH};function tr(t){return kA[t]}function LA(t){return t.kind===ti.CREATE?{kind:ut.CREATE,source:t.sourceId,target:t.targetId,type:tr(t.relationship),...t.lagDays===void 0?{}:{lag:t.lagDays},...t.linkId===void 0?{}:{linkId:t.linkId}}:t.kind===ti.UPDATE?{kind:ut.UPDATE,linkId:t.linkId,...t.sourceId===void 0?{}:{source:t.sourceId},...t.targetId===void 0?{}:{target:t.targetId},...t.relationship===void 0?{}:{type:tr(t.relationship)},...t.lagDays===void 0?{}:{lag:t.lagDays}}:t.kind===ti.REMOVE?{kind:ut.DELETE,linkId:t.linkId}:t}function OA(t){return t===Qi.START?E.START_DATE:t===Qi.END?E.END_DATE:t}function bA(t){return{kind:qe,mode:t.mode,items:t.items,links:t.links.map(e=>({source:e.source,target:e.target,type:tr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}})),...t.eventSource===void 0?{}:{eventSource:t.eventSource}}}function NA(t){return{get:e=>t.getActivityView(e),list:()=>t.getAllActivitiesView(),ids:()=>t.getAllIds(),forEachId:e=>t.forEachActivityId(e),property:(e,n)=>t.getProperty(e,n),children:e=>t.getChildrenView(e),childIds:e=>t.getChildrenIds(e),hasChildren:e=>t.hasChild(e),indentTargetParentIds:e=>t.getIndentTargetParentIds(e),isCustomIdInUse:(e,n)=>t.isCustomIdInUse(e,n??null),create:(e,n)=>t.dispatch({...e,kind:I.ACTIVITY_CREATE},n),applyBatch:(e,n)=>t.applyActivityBatch(bA(e),n),editInline:(e,n,i)=>t.dispatch({...ms(e,n),kind:I.INLINE_EDIT},i),setType:(e,n,i)=>t.dispatch({kind:I.ACTIVITY_TYPE_SET,activityId:e,type:n},i),applyDragBatch:(e,n)=>t.dispatch({kind:I.DATES_BATCH,edits:e.map(i=>({activityId:i.activityId,column:OA(i.edge),newValue:i.value}))},n),editFields:(e,n)=>t.dispatch({kind:I.BULK_EDIT,edits:e.map(i=>ms(i.activityId,i))},n),remove:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_DELETE,activityIds:e}),move:(e,n)=>t.dispatch({...e,kind:I.ACTIVITY_MOVE},n),planLookaheadConversion:e=>t.planLookaheadConversion(e),applyLookaheadConversion:e=>t.applyLookaheadConversion(e),indent:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_INDENT,activityIds:e}),outdent:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_OUTDENT,activityIds:e}),setProgress:(e,n,i={})=>t.dispatch({...i,kind:I.ACTIVITY_SET_PROGRESS,activityId:e,newValue:n}),copy:(e={})=>t.dispatch({...e,kind:I.ACTIVITY_COPY}),paste:(e,n={})=>t.dispatch({...n,kind:I.ACTIVITY_PASTE_COPIED,destination:{afterSiblingId:e}}),clearClipboard:(e={})=>t.dispatch({...e,kind:I.ACTIVITY_CLIPBOARD_CLEAR}),lookaheadSync:e=>t.dispatch({...e,kind:I.ACTIVITY_LOOKAHEAD_SYNC}),autoSchedule:(e,n)=>t.dispatch({kind:I.SCHEDULE_AUTO_SCHEDULE,...e===void 0?{}:{activityId:e}},n),createDateGesturePreview:e=>t.createDateGesturePreview(e)}}function FA(t){return{get:e=>t.getLinkView(e),list:()=>t.getAllLinksView(),forActivity:e=>t.getLinksForActivityView(e),create:(e,n)=>t.dispatch({kind:I.LINK_CREATE,source:e.sourceId,target:e.targetId,type:tr(e.relationship),...e.lagDays===void 0?{}:{lag:e.lagDays},...e.linkId===void 0?{}:{linkId:e.linkId}},n),update:(e,n,i)=>t.dispatch({kind:I.LINK_UPDATE,linkId:e,...n.sourceId===void 0?{}:{source:n.sourceId},...n.targetId===void 0?{}:{target:n.targetId},...n.relationship===void 0?{}:{type:tr(n.relationship)},...n.lagDays===void 0?{}:{lag:n.lagDays}},i),remove:(e,n)=>t.dispatch({kind:I.LINK_DELETE,linkId:e},n),batch:(e,n)=>t.dispatch({kind:I.LINKS_BATCH,operations:e.map(LA)},n)}}function nd(t){let e=(n,i)=>t.dispatch({kind:I.BASELINE_APPLY,points:n},i);return{activities:NA(t),links:FA(t),calendars:{get:n=>t.getCalendar(n),list:()=>t.getAllCalendars(),listBase:()=>t.getBaseCalendars(),projectWorkHours:()=>t.getProjectWorkHours(),reconcile:n=>t.dispatch({kind:I.CALENDAR_RECONCILE},n)},selection:{ids:()=>t.getSelectedActivityIds(),toggle:({checked:n,...i})=>t.dispatch({...i,kind:I.SELECTION_TOGGLE,isChecked:n}),replace:(n,i={})=>t.dispatch({...i,kind:I.SELECTION_REPLACE,activityIds:n})},view:{hiddenActivityIds:()=>t.getHiddenActivityIds(),visibleActivityIds:()=>t.getVisibleActivityIds(),visualOrderIds:()=>t.getVisualOrderIds(),visualRows:()=>t.getVisualRows(),filter:()=>t.getActiveFilter(),setFilter:n=>t.dispatch({...n,kind:I.FILTER_SET}),order:()=>t.getActiveOrder(),setOrder:(n,i={})=>t.dispatch({...i,kind:I.SORT_SET,rules:n}),group:()=>t.getActiveGroup(),setViewAttributes:(n,i={})=>t.dispatch({...i,kind:I.VIEW_ATTRIBUTES_SET,catalogs:n}),setGroup:(n,i={})=>t.dispatch({...i,kind:I.GROUP_SET,group:n}),wbsDepth:()=>t.getWbsDepth(),setWbsDepth:(n,i={})=>t.dispatch({...i,kind:I.WBS_DEPTH_SET,wbsDepth:n}),setVisibility:(n,i={})=>t.dispatch({...i,kind:I.VISIBILITY_SET,visibleIds:n}),setStatusCriteria:(n,i)=>t.dispatch({kind:I.STATUS_CRITERIA_SET,criteria:n},i)},baselines:{refresh:e,setVisibility:e,setPonderatorCriterion:(n,i)=>t.dispatch({kind:I.PONDERATOR_CRITERION_SET,criterion:n},i),activeFor:n=>Lt(n)},impactRequests:{sync:n=>t.dispatch({...n,kind:I.SIR_SYNC})},persistence:{hasChanges:()=>t.hasUnsavedChanges(),modifiedActivities:()=>t.getModifiedActivities(),modifiedActivityFields:()=>t.getModifiedActivityFields(),newActivities:()=>t.getNewActivities(),deletedActivities:()=>t.getDeletedActivitiesSinceLastSave(),modifiedLinks:()=>t.getModifiedLinks(),newLinks:()=>t.getNewLinks(),deletedLinks:()=>t.getDeletedLinksSinceLastSave(),captureHistoryBoundary:()=>t.capturePersistenceHistoryBoundary(),readSnapshot:()=>t.readPersistenceCheckpoint(),acknowledge:n=>t.dispatch({kind:I.PERSISTENCE_ACKNOWLEDGE,checkpoint:n})},history:{undo:n=>t.undo(n),redo:n=>t.redo(n),canUndo:()=>t.canUndo(),canRedo:()=>t.canRedo(),clear:()=>t.clearHistory(),depth:()=>t.undoDepth()},projection:{changeSetFrom:n=>t.createProjectionChangeSetFrom(n)},criticalPath:{get ready(){return t.criticalPathReady},recompute:()=>t.recomputeCriticalPath(),isSettled:()=>t.isCriticalPathSettled(),whenSettled:()=>t.whenCriticalPathSettled()},diagnostics:{auditEffectiveGraph:()=>t.auditEffectiveGraph(),revision:()=>t.getScheduleRevision(),stateRevision:()=>t.getStateRevision(),canonicalDigest:()=>t.getCanonicalDigest(),canonicalFingerprint:()=>t.getCanonicalFingerprint()}}}var Xt=class{items=[];head=0;enqueue(e){this.items.push(e)}dequeue(){if(this.head>=this.items.length)return;let e=this.items[this.head];return this.head+=1,e}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=t=>String(t);function id(t){let{clickedId:e,isChecked:n,currentSelection:i,hierarchy:r,isFrozen:a,exists:o,autoCheckParents:s}=t,l=Xr(e),c=new Set([...i].map(String)),d=new Set(c),u=wA(l,r).filter(o),p=u.filter(y=>!a(y)),f=n&&p.length<u.length;n&&!f?d.add(l):d.delete(l);for(let y of p)n?d.add(y):d.delete(y);return f||xA({id:l,isChecked:n,autoCheckParents:s,hierarchy:r,isFrozen:a,exists:o,next:d}),{nextSelection:d,changed:MA(c,d),parentBlocked:f}}function wA(t,e){let n=[],i=new Xt;i.enqueue(t);let r=new Set([t]);for(;!i.isEmpty();){let a=i.dequeue();for(let o of e.getChildrenIds(a)){let s=Xr(o);r.has(s)||(r.add(s),n.push(s),i.enqueue(s))}}return n}function xA(t){let{id:e,isChecked:n,autoCheckParents:i,hierarchy:r,isFrozen:a,exists:o,next:s}=t,l=r.getParentId(e);for(;l!==null&&typeof l<"u";){let c=Xr(l);if(a(c))return;let d=r.getChildrenIds(c).map(Xr).filter(o),u=d.some(a),p=d.filter(m=>!a(m)),y=p.length>0&&p.every(m=>s.has(m))&&!u;if(n){if(!i||!y||s.has(c))return;s.add(c)}else{if(y||!s.has(c))return;s.delete(c)}l=r.getParentId(c)}}function MA(t,e){let n=[],i=[];for(let r of e)t.has(r)||n.push(r);for(let r of t)e.has(r)||i.push(r);return{checked:n,unchecked:i}}function ei(t){return(t.pendingRequestIds?.length??0)>0}var _={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",CONFIRMATION_REQUIRED:"confirmation_required",DATA_DATE_ACTUAL_START_LOCKED:"data_date_actual_start_locked",DATA_DATE_ACTIVITY_COMPLETED:"data_date_activity_completed",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",MANUAL_SCHEDULING_ACTIVE:"manual_scheduling_active",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",STALE_STATE_REVISION:"stale-state-revision",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var rd=(t,e)=>{let n=t.getActivity(e);return n!=null&&ei(n)},ad=(t,e,n)=>{let i=[],r=(a,o)=>{let s=e.isChecked(a);e.setChecked(a,o)&&i.push({activityId:a,checked:{before:s,after:o}})};for(let a of n.checked)r(a,!0);for(let a of n.unchecked)r(a,!1);return{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}};function od(t,e){let{adapter:n}=e,i=t.activityId;if(!n.getActivity(i))return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let r=t.frozenIds?new Set(t.frozenIds):null,a=r?s=>r.has(s):s=>rd(n,s),o=id({clickedId:i,isChecked:t.isChecked,currentSelection:new Set(n.checkedIds().map(String)),hierarchy:{getChildrenIds:s=>n.getChildren(s),getParentId:s=>{let l=n.getParentId(s);return!l||l==="0"?null:String(l)}},isFrozen:a,exists:s=>n.activityExists(s),autoCheckParents:t.autoCheckParents??!1});return{ok:!0,changes:ad(t,n,o.changed)}}function Zr(t,e){let{adapter:n}=e,i=new Set(t.activityIds.map(String).filter(o=>n.activityExists(o)).filter(o=>!rd(n,o))),r=new Set(n.checkedIds().map(String)),a={checked:[...i].filter(o=>!r.has(o)),unchecked:[...r].filter(o=>!i.has(o))};return{ok:!0,changes:ad(t,n,a)}}function Rn(t,e,n=t.getAllIds()){let i=[];for(let r of n){let a=String(r),o=e.has(a),s=t.isVisible(a);s!==o&&(t.setVisible(a,o),i.push({activityId:a,visible:{before:s,after:o}}))}return i}function sd(t,e){let{adapter:n}=e,i=new Set(t.visibleIds.map(String)),r=Rn(n,i);return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:r}}}var ld={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var kn="viewAttribute";var F={STRING:"string",NUMBER:"number",DATE:"date",ID_ARRAY:"id-array",ENUM:"enum",BOOLEAN:"boolean",REFERENCE:"reference"},J={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_VARIANCE_DAYS:"baselineVarianceDays",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",FLOAT_PATH:"floatPath",FLOAT_PATH_ORDER:"floatPathOrder"},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"};function Ln(t){return"kind"in t&&t.kind===kn}var ni={AND:"and",OR:"or"};var UA=2,HA=[Mt.WAITING,Mt.DONE,Mt.DOING,Mt.OVERDUE,Mt.ADVANCEMENT],BA=[D.MFO,D.MSO,D.SNLT,D.SNET,D.ALAP,D.ASAP,D.FNET,D.FNLT],jA=1e3*60*60*24;function gs(t,e){return t===null||e<=0?null:t/e}function WA(t,e){let n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()),i=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate());return Math.floor((i-n)/jA)+1}var VA={[J.NAME]:{valueKind:F.STRING,extract:t=>t.name},[J.DESCRIPTION]:{valueKind:F.STRING,extract:t=>t.description},[J.CUSTOM_ID]:{valueKind:F.STRING,extract:t=>t.customId},[J.CORRELATIVE_ID]:{valueKind:F.NUMBER,extract:t=>t.correlativeId},[J.UNIQUE_CORRELATIVE_ID]:{valueKind:F.NUMBER,extract:t=>{let e=Number(t.uniqueCorrelativeId);return Number.isFinite(e)?e:null}},[J.PROGRESS]:{valueKind:F.NUMBER,extract:t=>t.progress},[J.DURATION_DAYS]:{valueKind:F.NUMBER,extract:(t,e)=>gs(t.durationHours,e.hoursPerDay)},[J.CALENDAR_DURATION]:{valueKind:F.NUMBER,extract:t=>t.type===k.MILESTONE?0:WA(t.startDate,t.endDate)},[J.COST]:{valueKind:F.NUMBER,extract:t=>t.cost},[J.USED_COST]:{valueKind:F.NUMBER,extract:t=>t.usedCost},[J.REAL_COST]:{valueKind:F.NUMBER,extract:t=>t.realCost},[J.WORK_HOURS]:{valueKind:F.NUMBER,extract:t=>t.workHours},[J.REAL_WORK_HOURS]:{valueKind:F.NUMBER,extract:t=>t.realWorkHours},[J.PONDERATOR]:{valueKind:F.NUMBER,extract:t=>t.ponderator},[J.FREE_SLACK_DAYS]:{valueKind:F.NUMBER,extract:(t,e)=>gs(t.freeSlackHours,e.hoursPerDay)},[J.TOTAL_SLACK_DAYS]:{valueKind:F.NUMBER,extract:(t,e)=>gs(t.criticalPath?.totalSlackHours??null,e.hoursPerDay)},[J.EXPECTED_PROGRESS_BASELINE]:{valueKind:F.NUMBER,equalityPrecision:UA,extract:t=>t.expectedProgressBaseline},[J.EXPECTED_PROGRESS]:{valueKind:F.NUMBER,extract:t=>t.expectedProgress},[J.BASELINE_DURATION_DAYS]:{valueKind:F.NUMBER,extract:t=>t.baselineSnapshot?.durationDays??null},[J.BASELINE_VARIANCE_DAYS]:{valueKind:F.NUMBER,extract:t=>t.baselineVarianceDays},[J.BASELINE_COST]:{valueKind:F.NUMBER,extract:t=>t.baselineSnapshot?.cost??null},[J.BASELINE_WORK_HOURS]:{valueKind:F.NUMBER,extract:t=>t.baselineSnapshot?.workHours??null},[J.START_DATE]:{valueKind:F.DATE,extract:t=>t.startDate},[J.END_DATE]:{valueKind:F.DATE,extract:t=>t.endDate},[J.CONSTRAINT_DATE]:{valueKind:F.DATE,extract:t=>t.constraintDate},[J.BASELINE_START_DATE]:{valueKind:F.DATE,extract:t=>t.baselineSnapshot?.startDate??null},[J.BASELINE_END_DATE]:{valueKind:F.DATE,extract:t=>t.baselineSnapshot?.endDate??null},[J.EARLY_START]:{valueKind:F.DATE,extract:t=>t.criticalPath?.earlyStart??null},[J.EARLY_FINISH]:{valueKind:F.DATE,extract:t=>t.criticalPath?.earlyFinish??null},[J.LATE_START]:{valueKind:F.DATE,extract:t=>t.criticalPath?.lateStart??null},[J.LATE_FINISH]:{valueKind:F.DATE,extract:t=>t.criticalPath?.lateFinish??null},[J.RESPONSABLE_IDS]:{valueKind:F.ID_ARRAY,extract:t=>t.responsableIds},[J.TAG_IDS]:{valueKind:F.ID_ARRAY,extract:t=>t.tagIds},[J.STATUS]:{valueKind:F.ENUM,order:HA,extract:t=>t.status},[J.CONSTRAINT_TYPE]:{valueKind:F.ENUM,order:BA,extract:t=>t.constraintType},[J.CALENDAR_ID]:{valueKind:F.REFERENCE,extract:t=>t.calendarId===null?null:String(t.calendarId)},[J.SUBCONTRACT_ID]:{valueKind:F.REFERENCE,extract:t=>t.subcontractId===null?null:String(t.subcontractId)},[J.IS_CRITICAL]:{valueKind:F.BOOLEAN,extract:t=>t.isCritical},[J.FLOAT_PATH]:{valueKind:F.NUMBER,extract:t=>t.p6?.floatPath??null},[J.FLOAT_PATH_ORDER]:{valueKind:F.NUMBER,extract:t=>t.p6?.floatPathOrder??null}};function ze(t){return VA[t]??null}var ri={GROUP:"group",ACTIVITY:"activity"},On="unassigned",As="g",ii=":",Qr="Unassigned",ta=1,Je=1,ea=0;function na(t,e){return`${As}${ii}${t}${ii}${e}`}function ia(t,e,n){return`${t}${ii}${e}${ii}${n}`}var dd=null;function cd(t){return t===dd?"":t}function ud(t){let e=new Map,n=new Map;for(let l of t.values){e.set(l.id,l);let c=cd(l.parentId),d=n.get(c)??[];d.push(l),n.set(c,d)}for(let l of n.values())l.sort((c,d)=>c.sequence!==d.sequence?c.sequence-d.sequence:c.id.localeCompare(d.id));let i=new Map,r=new Map,a=(l,c,d)=>{let u=n.get(cd(l))??[];for(let p of u){let f=[...c,p.id],y=[...d,p.sequence];i.set(p.id,f),r.set(p.id,y),a(p.id,f,y)}};a(dd,[],[]);let o=new Map;for(let l of e.keys()){let c=new Set([l]);for(let[d,u]of i)u.includes(l)&&c.add(d);o.set(l,c)}let s=new Map;for(let l of t.assignments)e.has(l.valueId)&&s.set(String(l.activityId),l.valueId);return{key:t.key,valueById:e,pathByValueId:i,sequencePathByValueId:r,descendantIdsByValueId:o,assignmentByActivityId:s}}var ra=new Map;function pd(t,e){let n=new Set;for(let i of e){let r=t.descendantIdsByValueId.get(i);if(r===void 0){n.add(i);continue}for(let a of r)n.add(a)}return n}function fd(t,e,n,i){let r=Math.max(n,Je),a=t.pathByValueId.get(e);return a===void 0||a.length===0?r>Je?[]:[e]:a.slice(r-1,Math.max(i,r))}function yd(t,e,n){let i=n.get(e.key),r=i?.assignmentByActivityId.get(String(t.id))??null,a=i?pd(i,e.value):new Set(e.value),o=r!==null&&a.has(r);return e.operator===W.SOME_OF?o:e.operator===W.NOT_SOME_OF?!o:!1}function Is(t){return t instanceof Date?t:typeof t=="string"||typeof t=="number"?new Date(t):new Date(Number.NaN)}function Oe(t){return Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate())}function KA(t,e,n){let i=t===null;return n===W.INCLUDES?!i&&String(t).toLowerCase().includes(e.toLowerCase()):n===W.NOT_INCLUDES?i||!String(t).toLowerCase().includes(e.toLowerCase()):n===W.IS?!i&&String(t)===e:n===W.IS_NOT?i||String(t)!==e:!1}function YA(t,e,n,i){if(t===null||typeof t!="number")return n===W.NOT_EQUALS;let r=i===void 0?t:Number(t.toFixed(i));return n===W.EQUALS?r===e:n===W.NOT_EQUALS?r!==e:n===W.GREATER_THAN?t>e:n===W.LESS_THAN?t<e:n===W.GREATER_OR_EQUAL?t>=e:n===W.LESS_OR_EQUAL?t<=e:!1}function GA(t,e,n){return typeof t=="number"&&t>=e&&t<=n}function $A(t,e,n){if(!(t instanceof Date))return!1;let i=Oe(t),r=Oe(e);return n===W.AFTER?i>r:n===W.BEFORE?i<r:!1}function qA(t,e,n){if(!(t instanceof Date))return!1;let i=Oe(t);return i>=Oe(e)&&i<=Oe(n)}function zA(t,e,n){let r=(Array.isArray(t)?t:[]).some(a=>e.has(String(a)));return n===W.SOME_OF?r:n===W.NOT_SOME_OF?!r:!1}function JA(t,e,n){let i=t!==null&&e.has(String(t));return n===W.SOME_OF?i:n===W.NOT_SOME_OF?!i:!1}function hd(t){let e=Array.isArray(t)?t:[t];return new Set(e.map(n=>String(n)))}function oa(t){return t.viewAttributeCatalogs??ra}function aa(t,e,n,i){if(Ln(e))return yd(t,e,i);let r=ze(e.field);if(r===null)return!1;let a=r.extract(t,n),{operator:o}=e;return o===W.BETWEEN?r.valueKind===F.NUMBER?GA(a,Number(e.value),Number(e.valueTo)):r.valueKind===F.DATE?qA(a,Is(e.value),Is(e.valueTo)):!1:r.valueKind===F.STRING?KA(a,String(e.value),o):r.valueKind===F.NUMBER?YA(a,Number(e.value),o,r.equalityPrecision):r.valueKind===F.DATE?$A(a,Is(e.value),o):r.valueKind===F.ID_ARRAY?zA(a,hd(e.value),o):JA(a,hd(e.value),o)}function md(t,e,n,i){return e.criteria.length===0?!0:e.logic===ni.OR?e.criteria.some(r=>aa(t,r,n,i)):e.criteria.every(r=>aa(t,r,n,i))}function XA(t,e,n,i){return e.groups&&e.groups.length>0?e.logic===ni.OR?e.groups.some(r=>md(t,r,n,i)):e.groups.every(r=>md(t,r,n,i)):e.criteria.length===0?!0:e.logic===ni.OR?e.criteria.some(r=>aa(t,r,n,i)):e.criteria.every(r=>aa(t,r,n,i))}function ZA(t,e){let n=Oe(t.startDate),i=Oe(t.endDate),r=Oe(e.start),a=Oe(e.end),o=n>=r&&i<=a,s=n>=r&&n<=a,l=r>=n&&r<=i;return o||s||l}function Ss(t,e,n,i){let r=XA(t,e,n,i),a=e.dateRange,o=a===void 0||ZA(t,a);return r&&o}function QA(t,e,n){let i=e(t);for(;i!==null&&!n.has(String(i));)n.add(String(i)),i=e(i)}function gd(t){let{activities:e,parentOf:n,filter:i,context:r}=t,a=oa(t),o=new Set,s=[];for(let l of e)Ss(l,i,r,a)&&(o.add(String(l.id)),s.push(l.id));for(let l of s)QA(l,n,o);return o}function tI(t){let{activities:e,parentOf:n,filter:i,context:r}=t,a=oa(t),o=new Set,s=new Map,l=new Map,c=new Map;for(let d of e){let u=String(d.id),p=n(u);l.set(u,p),c.set(u,c.get(u)??0),p!==null&&c.set(p,(c.get(p)??0)+1);let f=Ss(d,i,r,a);s.set(u,f?1:0),f&&o.add(u)}return{matchedIds:o,visibleReferenceCounts:s,parentIds:l,remainingChildren:c}}function eI(t){let{visibleReferenceCounts:e,parentIds:n,remainingChildren:i}=t,r=[];for(let a of n.keys())i.get(a)===0&&r.push(a);for(;r.length>0;){let a=r.pop();if(a===void 0)break;let o=n.get(a);if(o==null)continue;let s=e.get(a)??0;e.set(o,(e.get(o)??0)+s);let l=(i.get(o)??1)-1;i.set(o,l),l===0&&r.push(o)}}function nI(t){let e=new Set;for(let[n,i]of t)i>0&&e.add(n);return e}function sa(t){let e=tI(t);eI(e);let n=nI(e.visibleReferenceCounts);return{filter:t.filter,context:t.context,matchedIds:e.matchedIds,visibleIds:n,visibleReferenceCounts:e.visibleReferenceCounts,viewAttributeCatalogs:oa(t)}}function Ad(t,e,n){let i=new Set;for(let r of e){let a=String(r.id);i.add(a);let o=t.matchedIds.has(a),s=Ss(r,t.filter,t.context,oa(t));if(o===s)continue;s?t.matchedIds.add(a):t.matchedIds.delete(a);let l=s?1:-1,c=a;for(;c!==null;){let d=t.visibleReferenceCounts.get(c)??0,u=d+l;t.visibleReferenceCounts.set(c,u);let p=d>0,f=u>0;p!==f&&(i.add(c),f?t.visibleIds.add(c):t.visibleIds.delete(c)),c=n(c)}}return i}function bn(t){return{hoursPerDay:t,locale:"en"}}var pt={UNKNOWN_FIELD:"unknown_field",UNKNOWN_OPERATOR:"unknown_operator",INVALID_VALUE:"invalid_value"},iI={[F.STRING]:new Set([W.INCLUDES,W.NOT_INCLUDES,W.IS,W.IS_NOT]),[F.NUMBER]:new Set([W.EQUALS,W.NOT_EQUALS,W.GREATER_THAN,W.LESS_THAN,W.GREATER_OR_EQUAL,W.LESS_OR_EQUAL,W.BETWEEN]),[F.DATE]:new Set([W.AFTER,W.BEFORE,W.BETWEEN]),[F.ID_ARRAY]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[F.ENUM]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[F.BOOLEAN]:new Set([W.SOME_OF,W.NOT_SOME_OF]),[F.REFERENCE]:new Set([W.SOME_OF,W.NOT_SOME_OF])};function Id(t){if(t===void 0)return{ok:!0,dateRange:void 0};if(typeof t!="object"||t===null)return{ok:!1,reason:pt.INVALID_VALUE};let{start:e,end:n}=t;if(!(e instanceof Date)||!(n instanceof Date))return{ok:!1,reason:pt.INVALID_VALUE};let i=e.getTime(),r=n.getTime();return!Number.isFinite(i)||!Number.isFinite(r)||i>r?{ok:!1,reason:pt.INVALID_VALUE}:{ok:!0,dateRange:{start:new Date(i),end:new Date(r)}}}function Ds(t){if(Ln(t))return aI(t);let e=ze(t.field);if(e===null)return{ok:!1,reason:pt.UNKNOWN_FIELD};if(!iI[e.valueKind].has(t.operator))return{ok:!1,reason:pt.UNKNOWN_OPERATOR};if(t.operator===W.BETWEEN)return rI(t,e.valueKind);if(e.valueKind===F.NUMBER){let i=vs(t.value);return i===null?{ok:!1,reason:pt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:i}}}if(e.valueKind===F.DATE){let i=Cs(t.value);return i===null?{ok:!1,reason:pt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:i}}}let n=oI(t,e.valueKind);return n!==null?{ok:!1,reason:n}:e.valueKind===F.BOOLEAN?{ok:!0,criterion:{...t,value:[...new Set(t.value)]}}:e.valueKind===F.ID_ARRAY||e.valueKind===F.ENUM||e.valueKind===F.REFERENCE?{ok:!0,criterion:{...t,value:[...new Set(t.value.map(String))]}}:{ok:!0,criterion:t}}function rI(t,e){if(e===F.NUMBER){let n=vs(t.value),i=vs(t.valueTo);return n===null||i===null||n>i?{ok:!1,reason:pt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:n,valueTo:i}}}if(e===F.DATE){let n=Cs(t.value),i=Cs(t.valueTo);return n===null||i===null||n.getTime()>i.getTime()?{ok:!1,reason:pt.INVALID_VALUE}:{ok:!0,criterion:{...t,value:n,valueTo:i}}}return{ok:!1,reason:pt.UNKNOWN_OPERATOR}}function aI(t){return Ln(t)?typeof t.key!="string"||t.key.length===0?{ok:!1,reason:pt.UNKNOWN_FIELD}:t.operator!==W.SOME_OF&&t.operator!==W.NOT_SOME_OF?{ok:!1,reason:pt.UNKNOWN_OPERATOR}:!Array.isArray(t.value)||t.value.some(e=>typeof e!="string")?{ok:!1,reason:pt.INVALID_VALUE}:{ok:!0,criterion:t}:{ok:!1,reason:pt.UNKNOWN_FIELD}}function oI(t,e){let{value:n}=t;return e===F.BOOLEAN?Array.isArray(n)&&n.every(i=>typeof i=="boolean")?null:pt.INVALID_VALUE:e===F.ID_ARRAY||e===F.ENUM||e===F.REFERENCE?Array.isArray(n)&&n.every(i=>typeof i=="string"||typeof i=="number")?null:pt.INVALID_VALUE:Array.isArray(n)?pt.INVALID_VALUE:null}function vs(t){if(typeof t=="string"&&t.trim()===""||typeof t!="string"&&typeof t!="number")return null;let e=typeof t=="number"?t:Number(t);return Number.isFinite(e)?e:null}function Cs(t){let e;if(t instanceof Date)e=new Date(t.getTime());else if(typeof t=="string")e=new Date(t);else if(typeof t=="number")e=new Date(t);else return null;return Number.isFinite(e.getTime())?e:null}function v(t){return structuredClone(t)}function Sd(t){return!(t.groups!==void 0&&t.groups.some(n=>n.criteria.length>0))&&t.criteria.length===0&&t.dateRange===void 0}function vd(t,e,n){let i=t.getAllActivities();if(Sd(e))return{visibleIds:gd({activities:i,parentOf:a=>t.getParentId(a),filter:e,context:bn(n),viewAttributeCatalogs:t.getViewAttributeCatalogMap()}),projection:null};let r=sa({activities:i,parentOf:a=>t.getParentId(a),filter:e,context:bn(n),viewAttributeCatalogs:t.getViewAttributeCatalogMap()});return{visibleIds:r.visibleIds,projection:r}}function sI(t){if(!t||t.length===0)return{ok:!0,groups:[]};let e=[];for(let n of t){let i=[];for(let r of n.criteria){let a=Ds(r);if(!a.ok)return{ok:!1,reason:a.reason};i.push(a.criterion)}e.push({criteria:i,logic:n.logic})}return{ok:!0,groups:e}}function Cd(t,e){let{adapter:n,hoursPerDay:i}=e,r=[];for(let p of t.criteria){let f=Ds(p);if(!f.ok)return{ok:!1,reason:f.reason};r.push(f.criterion)}let a=sI(t.groups);if(!a.ok)return{ok:!1,reason:a.reason};let o=Id(t.dateRange);if(!o.ok)return{ok:!1,reason:o.reason};let s=v({criteria:r,logic:t.logic,...a.groups.length>0?{groups:a.groups}:{},...o.dateRange!==void 0?{dateRange:o.dateRange}:{}});n.setActiveFilter(Sd(s)?null:s);let{visibleIds:l,projection:c}=vd(n,s,i);n.setFilterProjection(c);let d=Rn(n,l);return{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],viewState:d}}}function Dd(t,e){let n=t.getActiveFilter();if(n===null)return[];let{visibleIds:i,projection:r}=vd(t,n,e);return t.setFilterProjection(r),Rn(t,i)}var Ut={ASCENDING:"asc",DESCENDING:"desc"};function ai(t){return"kind"in t&&t.kind===kn&&"key"in t&&"direction"in t&&!("operator"in t)}var be={STANDARD:"standard",KEEP_WBS_IN_PLACE:"keepWbsInPlace"};var $="0";function V(t){return t==null||t===0||t==="0"}function de(t){return V(t)?"0":String(t)}var Ts=Number.MAX_SAFE_INTEGER;function ee(t,e){let n=er(t,e);return la(n,e.getOrderComparator?.()??null,e.getOrderMode?.()??be.STANDARD,r=>e.hasChildren(r)).map(r=>String(r.id))}function la(t,e,n,i){return e===null?(t.sort(oi),t):n===be.KEEP_WBS_IN_PLACE?lI(t,e,i):(t.sort((r,a)=>e(r,a)||oi(r,a)),t)}function lI(t,e,n){let i=[],r=[];for(let a of t)n(a.id)?r.push(a):i.push(a);return i.sort((a,o)=>e(a,o)||oi(a,o)),r.sort(oi),t.length=0,t.push(...i,...r),t}function _d(t){let e=[],n=r=>{e.push(r);let a=ee(String(r.id),t);for(let o of a){let s=t.getActivity(o);s&&n(s)}},i=ee("0",t);for(let r of i){let a=t.getActivity(r);a&&n(a)}return e}function Ed(t,e,n){let i=n.getActivity(t);if(!i)return null;let r=Pd(i),a=ee(r,n),o=a.findIndex(s=>String(s)===String(t));if(o<=0)return null;for(let s=o-1;s>=0;s--){let l=a[s];if(l!==void 0&&!cI(e,l))return l}return null}function _s(t,e){let n=e.getActivity(t);if(!n)return-1;let i=Pd(n);return ee(i,e).findIndex(a=>String(a)===String(t))}function er(t,e){let n=String(t)==="0"?e.getRootIds?.()??e.getChildren("0"):e.getChildren(t),i=[];for(let r of n){let a=e.getActivity(r);a&&i.push(a)}return i}function oi(t,e){let n=Td(t),i=Td(e);return n!==i?n-i:String(t.id).localeCompare(String(e.id))}function Td(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Ts}function Pd(t){let e=t.parentId;return e===null?"0":e}function cI(t,e){return t.has(e)?!0:t.has(String(e))}function Xe(t){let e=[],n=i=>{let r=ee(i,t);r.length>1&&e.push({parentId:i,childIds:r});for(let a of r)n(a)};return n("0"),e}function Es(t,e){let n=[];for(let i of e){let r=ee(i,t);r.length>1&&n.push({parentId:i,childIds:r})}return n}function dI(t){return ai(t)?typeof t.key!="string"||t.key.length===0?pt.UNKNOWN_FIELD:t.direction!==Ut.ASCENDING&&t.direction!==Ut.DESCENDING?pt.UNKNOWN_OPERATOR:null:ze(t.field)===null?pt.UNKNOWN_FIELD:t.direction!==Ut.ASCENDING&&t.direction!==Ut.DESCENDING?pt.UNKNOWN_OPERATOR:null}function Rd(t,e){let{adapter:n}=e;for(let o of t.rules){let s=dI(o);if(s!==null)return{ok:!1,reason:s}}let i=t.mode??be.STANDARD,r=t.rules.length===0?null:v({rules:t.rules,mode:i});return n.setActiveOrder(r),{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[],order:Xe(n)}}}function Ps(t){return Number.isInteger(t)&&Number.isFinite(t)}function kd(t){return t===Ut.ASCENDING||t===Ut.DESCENDING}function Ld(t){let e=t.startLevel??Je;return!Ps(e)||e<Je||!Ps(t.depth)||t.depth<ta||t.depth<e?null:{startLevel:e,depth:t.depth}}var si=Symbol("invalid-group-criterion");function uI(t){let e=t.secondary;if(e==null)return null;if(typeof e!="object"||typeof e.attributeKey!="string"||e.attributeKey.length===0||e.attributeKey===t.attributeKey)return si;let n=Ld(e);return n===null||!kd(e.direction)?si:{attributeKey:e.attributeKey,startLevel:n.startLevel,depth:n.depth,direction:e.direction}}function pI(t){if(typeof t.attributeKey!="string"||t.attributeKey.length===0)return null;let e=Ld(t);if(e===null||!kd(t.direction)||typeof t.includeWbs!="boolean"||!Array.isArray(t.collapsedIds)||t.collapsedIds.some(i=>typeof i!="string"))return null;let n=uI(t);return n===si?null:{attributeKey:t.attributeKey,startLevel:e.startLevel,depth:e.depth,direction:t.direction,includeWbs:t.includeWbs,collapsedIds:new Set(t.collapsedIds),secondary:n}}function ca(t){return{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}function Od(t,e){let{adapter:n,hoursPerDay:i}=e;if(!Array.isArray(t.catalogs))return{ok:!1,reason:pt.INVALID_VALUE};n.setViewAttributeCatalogs(t.catalogs);let r=Dd(n,i),a=n.getActiveOrder();return{ok:!0,changes:{...ca(t),viewState:r,...a===null?{}:{order:Xe(n)}}}}function bd(t,e){let{adapter:n}=e;if(t.group===null)return n.setGroup(null),{ok:!0,changes:ca(t)};let i=pI(t.group);return i===null?{ok:!1,reason:pt.INVALID_VALUE}:(n.setGroup(i),{ok:!0,changes:ca(t)})}function Nd(t,e){let{adapter:n}=e,{wbsDepth:i}=t;return i!==null&&(!Ps(i)||i<ea)?{ok:!1,reason:pt.INVALID_VALUE}:(n.setWbsDepth(i),{ok:!0,changes:ca(t)})}function Fd(t,e){throw new Error(e)}var Rs={OWN_BASELINE:"own-baseline",RECURSIVE_LEAF_SUM:"recursive-leaf-sum",ZERO:"zero"},ks={[k.PROJECT]:{alwaysSummary:!0,holdsConstraint:!1,carriesCustomId:!1,forcedDuration:null,ponderatorWeight:Rs.RECURSIVE_LEAF_SUM,promotesToProjectOnFirstChild:!1},[k.TASK]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:null,ponderatorWeight:Rs.OWN_BASELINE,promotesToProjectOnFirstChild:!0},[k.MILESTONE]:{alwaysSummary:!1,holdsConstraint:!0,carriesCustomId:!0,forcedDuration:0,ponderatorWeight:Rs.ZERO,promotesToProjectOnFirstChild:!0}};function ue(t,e){return e||Xi(t)&&ks[t].alwaysSummary}function Ne(t){return t===k.MILESTONE}function Ze(t){return Xi(t)&&ks[t].promotesToProjectOnFirstChild}var Ls=k.PROJECT,li=k.TASK;function nr(t,e){return e===0?k.MILESTONE:t===0&&e>0?k.TASK:null}var U={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",BASELINE_VARIANCE_DAYS:"baselineVarianceDays",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath",P6:"p6"},Gt={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 wd(t,e){return()=>e()===t}var Os=typeof window>"u",fI=!Os&&typeof MessageChannel<"u";function mt(){return fI?new Promise(t=>{let e=new MessageChannel;e.port1.onmessage=()=>{e.port1.close(),e.port2.close(),t()},e.port2.postMessage(null)}):Promise.resolve()}async function da(t,e){return performance.now()-t<ld.YIELD_SLICE_MS?{aborted:!1,newSliceStart:t}:(await mt(),e()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ci(t){return Os||await mt(),t()?{aborted:!1}:{aborted:!0}}function De(t,e){let{inDegree:n,successors:i}=yI(t,e),r=hI(n),a=mI(r,n,i),o=a.length<t.length,s=o?gI(t,a):[],l=[...a].reverse();return{ordered:a,reversed:l,hasCycles:o,cycleNodes:s}}function yI(t,e){let n=new Map,i=new Map;for(let r of t)n.set(r,0),i.set(r,[]);for(let r of e){let a=r.source,o=r.target;!n.has(a)||!n.has(o)||(i.get(a).push(o),n.set(o,(n.get(o)??0)+1))}return{inDegree:n,successors:i}}function hI(t){let e=new Xt;for(let[n,i]of t)i===0&&e.enqueue(n);return e}function mI(t,e,n){let i=[];for(;!t.isEmpty();){let r=t.dequeue();i.push(r);for(let a of n.get(r)??[]){let o=(e.get(a)??1)-1;e.set(a,o),o===0&&t.enqueue(a)}}return i}function gI(t,e){let n=new Set(e);return t.filter(i=>!n.has(i))}var ua=class{cached=null;invalidate(){this.cached=null}get(e,n){return this.cached?this.cached:(this.cached=De(e,n),this.cached)}};function xd(t,e){let n=[];for(let i of t)e.has(i)&&n.push(i);return n}function pa(t,e){let n=e.getActivity(t);return n?ue(n.type,e.getChildren(t).length>0):!1}function fa(t,e,n){let i=String(e),r=n.getActivity(t);for(;r?.parentId&&String(r.parentId)!=="0";){if(String(r.parentId)===i)return!0;r=n.getActivity(r.parentId)}return!1}function ha(t,e,n){let i=pa(t,n);return pa(e,n)&&fa(t,e,n)||i&&fa(e,t,n)}function Hd(t,e){let n=[],i=[t];for(;i.length>0;){let r=i.pop(),a=e.getChildren(r);if(a.length===0){String(r)!==String(t)&&n.push(r);continue}for(let o of a)i.push(o)}return n}function AI(t){let e=new Map;for(let n of t)Md(e,String(n.source),n),Md(e,String(n.target),n);return e}function Md(t,e,n){let i=t.get(e);if(i){i.push(n);return}t.set(e,[n])}function II(t,e,n,i){if(t.length<=1)return t;let r=new Set(t.map(String)),a=[];for(let o of t)SI(o,r,e,n,i)||a.push(o);return a.length>0?a:t}function SI(t,e,n,i,r){let a=String(t),o=n.getActivity(t);if(!o||o.autoScheduling===!1)return!1;let s=i.get(a)??[];for(let l of s)if(vI(l,a,o,e,n,r))return!0;return!1}function vI(t,e,n,i,r,a){if(CI(t)||!(a?String(t.source)===e:String(t.target)===e))return!1;let s=DI(t,e);if(!i.has(String(s)))return!1;let l=r.getActivity(s);return!!(l?.autoScheduling!==!1&&l&&TI(t,n,l))}function CI(t){return t.source===t.target}function DI(t,e){return String(t.source)===e?t.target:t.source}function TI(t,e,n){let i=t.lag??0,r=Math.abs(i);return String(t.target)===String(n.id)&&r<=n.durationHours||String(t.target)===String(e.id)&&r<=e.durationHours}function ma(t,e){let n=[],i=AI(t),r=0;for(let a of t){let o=pa(a.source,e),s=pa(a.target,e);if(_I(a,o,s,e))continue;if(!o&&!s){n.push(a);continue}let l=Ud(a.source,o,e,i,!0),c=Ud(a.target,s,e,i,!1);r=bI(n,l,c,a,e,r,i)}return n}function _I(t,e,n,i){return n&&fa(t.source,t.target,i)||e&&fa(t.target,t.source,i)}function Ud(t,e,n,i,r){return e?II(Hd(t,n),n,i,r):[t]}function EI(t,e,n){let i=Hd(t,e);if(i.length===0)return null;let r=null,a=null;for(let o of i){let s=n(o);if(!s)continue;(r===null||s.startDate<r)&&(r=s.startDate),(a===null||s.endDate>a)&&(a=s.endDate)}return r===null||a===null?null:{startDate:r,endDate:a}}function ya(t,e){return EI(t,e,n=>{let i=e.getActivity(n);return i?{startDate:i.startDate,endDate:i.endDate}:null})}function PI(t,e,n){return t?e?n.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:t}):t.durationHours:0}function RI(t,e,n,i){if(!e)return 0;let r=i.getActivity(t);return!n||!r?-e.durationHours:-i.calculateDuration({startDate:n.startDate,endDate:r.endDate,task:e})}function kI(t,e){let n=String(t);return(e.get(n)??[]).some(r=>String(r.target)===n)}function LI(t,e,n,i,r){if(kI(t,r))return 0;let a=i.getActivity(t);return!e||!a||!n?0:i.calculateDuration({startDate:e,endDate:a.startDate,task:n})}function OI(t,e){let n=e.getActivity(t.source),i=e.getActivity(t.target),r=ya(t.source,e),a=ya(t.target,e),o=t.type===H.START_TO_START||t.type===H.START_TO_FINISH,s=t.type===H.FINISH_TO_FINISH||t.type===H.START_TO_FINISH;return{source:n,sourceBounds:r,targetStart:a?.startDate??i?.startDate,userLag:t.lag??0,sourceEndpointIsStart:o,targetLag:s?-PI(i,a,e):0,summarySourceId:t.type===H.START_TO_START&&r?t.source:void 0,finishAnchoredSummaryTargetId:s&&a?t.target:void 0}}function bI(t,e,n,i,r,a,o){let s=OI(i,r),{source:l,sourceBounds:c,targetStart:d,userLag:u}=s,{sourceEndpointIsStart:p,targetLag:f,summarySourceId:y,finishAnchoredSummaryTargetId:m}=s,h=a;for(let A of e){let T=p?RI(A,l,c,r):0;for(let b of n){if(String(A)===String(b))continue;let S=LI(b,d,l,r,o);t.push(NI(i,A,b,h,T,f,u+S,y,m??(S!==0&&f===0?i.target:void 0))),h+=1}}return h}function NI(t,e,n,i,r,a,o,s,l){return{id:`virtual_${t.id}_${i}`,source:e,target:n,type:t.type,lag:t.lag,freeSlackHours:null,isCritical:!1,_sourceLag:r,_targetLag:a,_trueLag:o,...s===void 0?{}:{_summarySourceId:s},...l===void 0?{}:{_summaryTargetId:l}}}var ga=class{invalidate(){}get(e,n){return ma(e,n)}};function FI(t){let e=new Map,n=i=>(e.has(i)||e.set(i,new Set),e.get(i));for(let i of t)n(i.source).add(i.id),n(i.target).add(i.id);return{neighbors:e}}function wI(t,e,n){let i=new Set,r=new Map,a=new Xt;for(a.enqueue(t);!a.isEmpty();){let o=a.dequeue(),s=String(o);if(i.has(s))continue;i.add(s);let l=n.neighbors.get(o);if(l)for(let c of l){let d=e.get(c);if(!d)continue;let u=`${d.source}-${d.target}-${d.type}`;r.has(u)||r.set(u,d);let p=String(d.source)===s?d.target:d.source;i.has(String(p))||a.enqueue(p)}}return Array.from(r.values())}function Bd(t,e){let n=new Map;for(let o of e)n.set(o.id,o);let i=FI(e),r=wI(t,n,i),a=new Set([String(t)]);for(let o of r)a.add(String(o.source)),a.add(String(o.target));return{activityIds:a,links:r}}var Zt=0,Pt=100,bs=100+Number.EPSILON*100*2;function Aa(t){return t>=100&&t<=bs}function Nn(t){return t===0}var jd=36e5,Wd=1;function Qe(t,e){return new Date(t.getTime()+e*jd)}function ir(t){return new Date(t.getTime()+Wd)}function di(t){return new Date(t.getTime()-Wd)}function Vd(t,e){return(e.getTime()-t.getTime())/jd}function Kd(t,e,n){let i=n.type===H.FINISH_TO_START,r=n.type===H.FINISH_TO_FINISH;if(n._targetLag!==void 0)return{sourceLag:n._sourceLag??0,targetLag:n._targetLag,trueLag:n._trueLag??n.lag??0,isFS:i,isFF:r,isZeroDurationCase:!1};let a=n.lag??0;switch(n.type){case H.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:r,isZeroDurationCase:!1};case H.START_TO_START:return{sourceLag:-t.durationHours,targetLag:0,trueLag:a,isFS:i,isFF:r,isZeroDurationCase:!1};case H.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-e.durationHours,trueLag:a,isFS:i,isFF:r,isZeroDurationCase:!1};case H.START_TO_FINISH:return{sourceLag:-t.durationHours,targetLag:-e.durationHours,trueLag:a,isFS:i,isFF:r,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:i,isFF:r,isZeroDurationCase:!1}}}function xI(t,e,n){if(t._summarySourceId===void 0)return null;let i=n.getActivity(t._summarySourceId);if(!i)return null;let r=ya(t._summarySourceId,n);return r?-n.calculateDuration({startDate:r.startDate,endDate:e.endDate,task:i}):null}function MI(t,e,n,i,r){let a=e.durationHours===0&&r;return{successorStart:i.getClosestWorkTime({date:t.endDate,dir:a?"past":"future",task:e}),link:n}}function UI(t,e,n,i){return n===null?new Date(t.endDate):i.getClosestWorkTime({date:t.endDate,dir:"future",task:e})}function Yd(t,e,n,i){return n===null?Qe(t,e):i.calculateEndDate({startDate:t,durationHours:e,task:n})}function HI(t,e,n){return e===null?new Date(t.startDate):n.getClosestWorkTime({date:t.startDate,dir:"past",task:e})}function Ia(t,e,n,i,r=e){let{sourceLag:a,targetLag:o,trueLag:s,isFS:l,isFF:c}=Kd(t,e,n),d=xI(n,t,i)??a,u=d+o+s;if(!(e.durationHours===0?u!==0:d!==0||o!==0||s!==0))return MI(t,e,n,i,l||c);let m=UI(t,l?e:t,r,i);if(d!==0&&(m=i.calculateEndDate({startDate:m,durationHours:d,task:t})),o!==0&&(m=i.calculateEndDate({startDate:m,durationHours:o,task:e})),s!==0&&(m=Yd(m,s,r,i)),e.durationHours===0){if(l||c)return{successorStart:i.getClosestWorkTime({date:m,dir:"past",task:e}),link:n};let h=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()));return{successorStart:i.getClosestWorkTime({date:h,dir:"future",task:e}),link:n}}return{successorStart:i.getClosestWorkTime({date:m,dir:"future",task:e}),link:n}}function Sa(t,e,n,i,r=t){let{sourceLag:a,targetLag:o,trueLag:s}=Kd(e,t,n),l=HI(t,r,i);return s!==0&&(l=Yd(l,-s,r,i)),o!==0&&(l=i.calculateEndDate({startDate:l,durationHours:-o,task:t})),a!==0&&(l=i.calculateEndDate({startDate:l,durationHours:-a,task:e})),l}function Gd(t,e,n){for(let i of t){let r=e.getActivity(i);if(!r)continue;let a=r.constraintType;if(!a||a===D.ASAP||a===D.ALAP)continue;let o=$e(r,e);!o.earliestStart&&!o.latestStart&&!o.earliestEnd&&!o.latestEnd||n.set(i,{activityId:i,startDate:r.startDate,endDate:r.endDate,drivingLinkId:null,kind:D.ASAP,conflict:!1,earliestStart:o.earliestStart,latestStart:o.latestStart,earliestEnd:o.earliestEnd,latestEnd:o.latestEnd})}}function ui(t,e,n){let i={earliestStart:e.earliestStart??null,latestStart:e.latestStart??null,earliestEnd:e.earliestEnd??null,latestEnd:e.latestEnd??null},r=e.earliestSchedulingStart??e.latestSchedulingStart??null,a;r===null?a=hs(t.startDate,i):td(r,i)?a=r:a=hs(r,i),e.startDate=a,e.endDate=n.calculateEndDate({startDate:a,durationHours:t.durationHours,task:t})}function $d(t,e){if(!t||!e)return new Date;let{constraintType:n,constraintDate:i}=t;if(!n||!i)return e;switch(n){case D.MSO:case D.MFO:return new Date(i);case D.SNET:case D.FNET:return i>e?new Date(i):e;case D.SNLT:case D.FNLT:return i<e?new Date(i):e;default:return e}}function BI(t,e){return e.length?e.some(n=>String(n)===String(t)):!1}function qd(t,e,n){return Ns(t.id,e,n)?{startDate:t.startDate,endDate:t.endDate}:{startDate:t.startDate,endDate:t.endDate}}function Ns(t,e,n){return e.dragWithMultiple&&BI(t,n)}async function zd(t,e,n,i,r,a){let o=new Map;for(let u of e){let p=String(u.target);o.has(p)||o.set(p,[]),o.get(p).push(u)}let s=u=>{let p=a.get(u);if(p?.startDate&&p.endDate)return{startDate:p.startDate,endDate:p.endDate};let f=n.getActivity(u);return f?{startDate:f.startDate,endDate:f.endDate}:{startDate:new Date,endDate:new Date}},l=n.getFlags(),c=i.draggedIds??[],d=performance.now();for(let u of t){let p=await da(d,r);if(p.aborted)return a;d=p.newSliceStart;let f=n.getActivity(u);if(!f||!f.autoScheduling||f.progress===100||jI(f,n))continue;let y=o.get(String(u))??[],m=null,h=null,A=!1;for(let w of y){let R=n.getActivity(w.source);if(!R)continue;let L=s(w.source),P=L.startDate.getTime()!==R.startDate.getTime()||L.endDate.getTime()!==R.endDate.getTime(),O={...R,startDate:L.startDate,endDate:L.endDate},M=qd(O,l,c),j={...O,startDate:M.startDate,endDate:M.endDate},z=Ns(w.source,l,c)?{...w,lag:0}:w,ft=Ia(j,f,z,n);(!m||ft.successorStart>m)&&(m=ft.successorStart,h=String(w.id),A=w._summaryTargetId!==void 0&&!P&&(w._targetLag===0||i.preventSummaryTargetPullback===!0))}m!==null&&A&&m<f.startDate&&(m=new Date(f.startDate));let b=a.get(u),S=b?{...b}:{activityId:u,startDate:f.startDate,endDate:f.endDate,drivingLinkId:null,kind:D.ASAP,conflict:!1},g=S.earliestStart||S.latestStart||S.earliestEnd||S.latestEnd;if(!(!m&&!g)){if(m){let w=m;f.type===k.MILESTONE&&(w=$d(f,m)),S.drivingLinkId=h,S.startDate=w,S.endDate=n.calculateEndDate({startDate:w,durationHours:f.durationHours,task:f}),S.earliestSchedulingStart=w,S.earliestSchedulingEnd=S.endDate}else f.constraintType===D.MSO?S.earliestStart&&(S.startDate=S.earliestStart,S.endDate=S.earliestEnd??n.calculateEndDate({startDate:S.earliestStart,durationHours:f.durationHours,task:f})):f.constraintType===D.MFO&&S.latestStart&&(S.startDate=S.latestStart,S.endDate=S.latestEnd??n.calculateEndDate({startDate:S.latestStart,durationHours:f.durationHours,task:f}));ui(f,S,n),a.set(u,S)}}return a}function jI(t,e){return ue(t.type,e.getChildren(t.id).length>0)}async function Jd(t,e,n,i,r,a){let o=new Map(n),s=i.getAllActivities(),l=s.length,c=[];for(let h of s)h.constraintType===D.ALAP&&c.push(h.id);if(c.length===0)return o;let d=new Map,u=new Map;for(let h of e){let A=String(h.source);d.has(A)||d.set(A,[]),d.get(A).push(h);let T=String(h.target);u.has(T)||u.set(T,[]),u.get(T).push(h)}let p=h=>{let A=o.get(h);if(A)return{startDate:A.startDate,endDate:A.endDate};let T=i.getActivity(h);return T?{startDate:T.startDate,endDate:T.endDate}:{startDate:new Date,endDate:new Date}},f=h=>!h.parentId||V(h.parentId)?i.getProjectEnd():p(h.parentId).endDate,y=(h,A)=>{let T=h,b=0;for(;T&&!V(T)&&b++<l+1;){if(String(T)===String(A))return!0;let S=i.getActivity(T);if(!S||!S.parentId)break;T=S.parentId}return!1},m=performance.now();for(let h of t){let A=await da(m,a);if(A.aborted)return o;m=A.newSliceStart;let T=i.getActivity(h);if(!T||T.constraintType!==D.ALAP||!T.autoScheduling||T.progress===100||ue(T.type,i.getChildren(h).length>0))continue;let b=f(T),S=b,g=null,w=null,R=!1,L=d.get(String(h))??[];for(let It of L){if((It.lag??0)<0)continue;let Ye=i.getActivity(It.target);if(!Ye||Ye.autoScheduling===!1)continue;let Vr=p(It.target),Kr={...Ye,startDate:Vr.startDate,endDate:Vr.endDate},Yr=Sa(Kr,T,It,i);(S===null||Yr<S)&&(S=Yr),(g===null||Yr<g)&&(g=Yr,w=It.type,R=T.parentId&&!V(T.parentId)?y(It.target,T.parentId):!1)}if(g!==null)if(R||b===null)S=g;else{let It=p(h).endDate,Ye=It.getTime()>b.getTime()?It:b;S=g<Ye?g:Ye}else{if(b===null||S===null)continue;S>b&&(S=b)}if(S===null)continue;let O=(u.get(String(h))??[]).some(It=>It.type===H.FINISH_TO_START||It.type===H.FINISH_TO_FINISH),M=new Date(Date.UTC(S.getUTCFullYear(),S.getUTCMonth(),S.getUTCDate())),j=()=>i.getClosestWorkTime({date:M,dir:"past",task:T}),z=i.getClosestWorkTime({date:S,dir:"future",task:T}).getTime()===S.getTime(),ft;T.durationHours===0&&g===null?ft=O&&z?j():i.getClosestWorkTime({date:S,dir:"past",task:T}):T.durationHours===0?g!==null&&w===H.FINISH_TO_START&&S.getTime()===g.getTime()?ft=S:O?ft=j():ft=i.getClosestWorkTime({date:S,dir:"future",task:T}):ft=i.getClosestWorkTime({date:S,dir:"future",task:T});let st=i.calculateEndDate({startDate:ft,durationHours:-T.durationHours,task:T}),Nt=o.get(h),kt=Nt?{...Nt}:{activityId:h,startDate:st,endDate:ft,drivingLinkId:null,kind:D.ALAP,conflict:!1};kt.startDate=st,kt.endDate=ft,kt.drivingLinkId=null,kt.kind=D.ALAP;let Ce=kt.earliestSchedulingStart??null;kt.earliestSchedulingStart=null,kt.earliestSchedulingEnd=null;let Le=Ce!==null&&Ce.getTime()>st.getTime()?Ce:st;kt.latestSchedulingStart=Le,kt.latestSchedulingEnd=Le===st?ft:i.calculateEndDate({startDate:Le,durationHours:T.durationHours,task:T}),ui(T,kt,i),o.set(h,kt)}return o}var pi={warn(){},error(){}};var WI=864e5;function Te(t){if(t.type===k.MILESTONE)return 0;let e=t.startDate?.getTime(),n=t.endDate?.getTime();return e==null||n==null||Number.isNaN(e)||Number.isNaN(n)?null:Math.floor((n-e)/WI)+1}function rr(t,e){e.cancelled||e.updatedIds.length===0||t.batchUpdate(()=>{for(let n of e.updatedIds){let i=e.plans.get(n);if(!i)continue;let r=t.getLiveActivity(n);r&&(r.startDate=i.startDate,r.endDate=i.endDate,r.calendarDuration=Te(r),t.updateActivity(n))}})}function Fs(t,e){let n=String(e.source),i=String(e.target);if(n===i)return!0;let r=new Map;for(let a of t){let o=String(a.source),s=String(a.target),l=r.get(o)??[];l.push(s),r.set(o,l)}return VI(r,i,n)}function ar(t){let e=new Map,n=new Map;for(let a of t){let o=String(a.source),s=String(a.target),l=e.get(o)??[];l.push(s),e.set(o,l),n.set(o,n.get(o)??0),n.set(s,(n.get(s)??0)+1)}let i=new Xt;for(let[a,o]of n)o===0&&i.enqueue(a);let r=0;for(;!i.isEmpty();){let a=i.dequeue();r+=1;for(let o of e.get(a)??[]){let s=n.get(o)-1;n.set(o,s),s===0&&i.enqueue(o)}}return r!==n.size}function VI(t,e,n){if(e===n)return!0;let i=new Set([e]),r=new Xt;for(r.enqueue(e);!r.isEmpty();){let a=r.dequeue(),o=t.get(a)??[];for(let s of o){if(s===n)return!0;i.has(s)||(i.add(s),r.enqueue(s))}}return!1}function va(t){let e=KI(t);for(let n of e.adjacency.keys())e.records.has(n)||YI(n,e);return e.components}function KI(t){let e=new Map,n=new Set;for(let i of t){let r=String(i.source),a=String(i.target),o=Xd(e,r);if(Xd(e,a),r===a){n.add(r);continue}o.push(a)}return{adjacency:e,selfLooped:n,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Xd(t,e){let n=t.get(e);if(n)return n;let i=[];return t.set(e,i),i}function YI(t,e){let n=[];for(n.push({node:t,record:Zd(t,e),neighborCursor:0});n.length>0;){let i=n[n.length-1];if(i===void 0)break;let r=e.adjacency.get(i.node)??[];if(i.neighborCursor<r.length){let s=r[i.neighborCursor];if(i.neighborCursor+=1,s===void 0)continue;GI(i,s,n,e);continue}n.pop();let a=n[n.length-1];a&&i.record.lowLink<a.record.lowLink&&(a.record.lowLink=i.record.lowLink),i.record.lowLink===i.record.visitIndex&&$I(i.node,e)}}function GI(t,e,n,i){let r=i.records.get(e);if(!r){n.push({node:e,record:Zd(e,i),neighborCursor:0});return}r.onStack&&r.visitIndex<t.record.lowLink&&(t.record.lowLink=r.visitIndex)}function Zd(t,e){let n={visitIndex:e.nextIndex,lowLink:e.nextIndex,onStack:!0};return e.nextIndex+=1,e.records.set(t,n),e.componentStack.push({node:t,record:n}),n}function $I(t,e){let n=[];for(;;){let o=e.componentStack.pop();if(o===void 0||(o.record.onStack=!1,n.push(o.node),o.node===t))break}let i=n[0],r=n.length===1&&i!==void 0&&e.selfLooped.has(i);(n.length>1||r)&&e.components.push(n)}function or(t,e,n){let i=n?new ws(t,n):t;return ma([...e],i)}var ws=class{constructor(e,n){this.base=e;e.isWorkTime!==void 0&&(this.isWorkTime=e.isWorkTime.bind(e));for(let[i,r]of n.reparented){let a=String(i),o=r===null||V(r)?null:r,s=e.getActivity(i)?.parentId??null,l=s===null||V(s)?null:String(s),c=o===null?null:String(o);if(l!==c){if(this.reparented.set(a,o),l!==null){let d=this.movedOutByParent.get(l)??new Set;d.add(a),this.movedOutByParent.set(l,d)}if(c!==null){let d=this.movedInByParent.get(c)??[];d.push(i),this.movedInByParent.set(c,d)}}}}base;isWorkTime;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(e){if(!e)return null;let n=this.reparented.get(String(e.id));return n===void 0?e:{...e,parentId:n}}getActivity(e){return this.withOverride(this.base.getActivity(e))}getLiveActivity(e){return this.withOverride(this.base.getLiveActivity(e))}getAllActivities(){return this.base.getAllActivities().map(e=>this.withOverride(e)??e)}getChildren(e){let n=String(e),i=this.movedOutByParent.get(n),r=this.base.getChildren(e),a=i?r.filter(s=>!i.has(String(s))):[...r],o=this.movedInByParent.get(n);return o&&a.push(...o),a}getParent(e){let n=this.reparented.get(String(e));return n===void 0?this.base.getParent(e):n===null?null:this.getActivity(n)}isChildOf(e,n){let i=String(n),r=new Set,a=this.getActivity(e);for(;a;){let o=a.parentId;if(o===null||V(o))return!1;let s=String(o);if(s===i)return!0;if(r.has(s))return!1;r.add(s),a=this.getActivity(o)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(e){return this.base.getLink(e)}activityExists(e){return this.base.activityExists(e)}getOutgoingLinkIds(e){return this.base.getOutgoingLinkIds(e)}getIncomingLinkIds(e){return this.base.getIncomingLinkIds(e)}getClosestWorkTime(e){return this.base.getClosestWorkTime(e)}calculateEndDate(e){return this.base.calculateEndDate(e)}calculateDuration(e){return this.base.calculateDuration(e)}batchUpdate(e){this.base.batchUpdate(e)}updateActivity(e){this.base.updateActivity(e)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function tn(t){let{port:e,proposedPort:n,currentLinks:i,proposedLinks:r,proposal:a}=t,o=or(n??e,r,a);if(!ar(o))return{ok:!0};let s=or(e,i),l=Qd(s),d=[...Qd(o)].filter(u=>!l.has(u));return d.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:d}}function Qd(t){let e=new Set;for(let n of va(t))for(let i of n)e.add(i);return e}function Da(t,e,n){return n.getChildren(t).length>0||n.getChildren(e).length>0}function en(t,e){switch(t.kind){case Et.CREATE:return qI(t,e);case Et.UPDATE:return zI(t,e.port,e.rejectParentLinkMutations??!1);case Et.DELETE:return JI(t,e)}}function _a(t,e){if(t.length===0)return{applied:!0};let n=e.port.getAllLinks(),i=new Map,r=[];for(let c of n){let d=Ta(c);i.has(d)||i.set(d,c.id),r.push({source:c.source,target:c.target})}let a=ar(r),o=null;for(let{operation:c,linkId:d}of t){if(String(c.source)===String(c.target)){o={applied:!1,rejected:yt.SELF_LINK};break}if(!e.port.getActivity(c.source)||!e.port.getActivity(c.target)){o={applied:!1,rejected:yt.ACTIVITY_MISSING};break}if(e.rejectParentLinkMutations&&Da(c.source,c.target,e.port)){o={applied:!1,rejected:yt.HIERARCHY_LINK};break}if(ha(c.source,c.target,e.port)){o={applied:!1,rejected:yt.HIERARCHY_LINK};break}let u=Ta(c),p=i.get(u);if(p!==void 0){o={applied:!1,rejected:yt.DUPLICATE,linkId:p};break}if(i.set(u,d),a&&Fs(r,{source:c.source,target:c.target}))return{applied:!1,rejected:yt.CYCLE};r.push({source:c.source,target:c.target})}if(!a&&ar(r))return{applied:!1,rejected:yt.CYCLE};if(o)return o;let s=[...n,...t.map(({operation:c,linkId:d})=>({id:d,source:c.source,target:c.target,type:c.type,lag:c.lag,freeSlackHours:null,isCritical:!1}))];if(!tn({port:e.port,currentLinks:n,proposedLinks:s}).ok)return{applied:!1,rejected:yt.CYCLE};for(let{operation:c,linkId:d}of t){let u=e.preserved?.get(d);e.port.addLink({id:d,source:c.source,target:c.target,type:c.type,lag:c.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 Ta(t){return JSON.stringify([String(t.source),String(t.target),t.type])}function qI(t,e){let{port:n}=e;if(String(t.source)===String(t.target))return{applied:!1,rejected:yt.SELF_LINK};let i=n.getActivity(t.source),r=n.getActivity(t.target);if(!i||!r)return{applied:!1,rejected:yt.ACTIVITY_MISSING};if(e.rejectParentLinkMutations&&Da(t.source,t.target,n))return{applied:!1,rejected:yt.HIERARCHY_LINK};if(ha(t.source,t.target,n))return{applied:!1,rejected:yt.HIERARCHY_LINK};let a=n.getAllLinks();for(let d of a)if(String(d.source)===String(t.source)&&String(d.target)===String(t.target)&&d.type===t.type)return{applied:!1,rejected:yt.DUPLICATE,linkId:d.id};let o=a.map(d=>({source:d.source,target:d.target}));if(Fs(o,{source:t.source,target:t.target}))return{applied:!1,rejected:yt.CYCLE};let s=(e.newLinkId??XI)(),l={id:s,source:t.source,target:t.target,type:t.type,lag:t.lag,freeSlackHours:null,isCritical:!1};return tn({port:n,currentLinks:a,proposedLinks:[...a,l]}).ok?(n.addLink(l),{applied:!0,linkId:s}):{applied:!1,rejected:yt.CYCLE}}function zI(t,e,n){let i=e.getLink(t.linkId);if(!i)return{applied:!1,rejected:yt.LINK_MISSING};let r={...i,source:t.source??i.source,target:t.target??i.target,type:t.type??i.type,lag:t.lag??i.lag};if(String(r.source)===String(r.target))return{applied:!1,rejected:yt.SELF_LINK};if(!e.getActivity(r.source)||!e.getActivity(r.target))return{applied:!1,rejected:yt.ACTIVITY_MISSING};if(n&&(Da(i.source,i.target,e)||Da(r.source,r.target,e)))return{applied:!1,rejected:yt.HIERARCHY_LINK};if(ha(r.source,r.target,e))return{applied:!1,rejected:yt.HIERARCHY_LINK};let a=e.getAllLinks(),o=a.find(c=>String(c.id)!==String(t.linkId)&&Ta(c)===Ta(r));if(o)return{applied:!1,rejected:yt.DUPLICATE,linkId:o.id};let s=a.map(c=>String(c.id)===String(t.linkId)?r:c);return tn({port:e,currentLinks:a,proposedLinks:s}).ok?((String(i.source)!==String(r.source)||String(i.target)!==String(r.target))&&e.setLinkEndpoints(t.linkId,r.source,r.target),t.lag!==void 0&&e.setLinkField(t.linkId,"lag",t.lag),t.type!==void 0&&e.setLinkField(t.linkId,"type",t.type),{applied:!0,linkId:t.linkId}):{applied:!1,rejected:yt.CYCLE}}function JI(t,e){let{port:n}=e;return n.getLink(t.linkId)?(n.removeLink(t.linkId),{applied:!0,linkId:t.linkId}):{applied:!1,rejected:yt.LINK_MISSING}}var Ca=null;function XI(){return Ca===null&&(Ca=Date.now()),Ca+=1,String(Ca)}var Ft={FINISH_TO_START:"fs",START_TO_START:"ss",FINISH_TO_FINISH:"ff",START_TO_FINISH:"sf"},Ea={[H.FINISH_TO_START]:Ft.FINISH_TO_START,[H.START_TO_START]:Ft.START_TO_START,[H.FINISH_TO_FINISH]:Ft.FINISH_TO_FINISH,[H.START_TO_FINISH]:Ft.START_TO_FINISH},Fn={[Ft.FINISH_TO_START]:H.FINISH_TO_START,[Ft.START_TO_START]:H.START_TO_START,[Ft.FINISH_TO_FINISH]:H.FINISH_TO_FINISH,[Ft.START_TO_FINISH]:H.START_TO_FINISH},tu=Ft.FINISH_TO_START;function eu(t){if(t in Fn)return Fn[t]}var nu=";",nn={DAY:"d",WEEK:"w",WEEK_DHTMLX:"wk",MONTH:"m",MONTH_DHTMLX:"mon",YEAR:"y"},iu=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)(weeks?|wk|w|months?|mon|m|days?|d|years?|y)?)?$/i;var ZI=5,Pa=30,xs=365,QI={[nn.DAY]:1,day:1,days:1,[nn.MONTH]:Pa,[nn.MONTH_DHTMLX]:Pa,month:Pa,months:Pa,[nn.YEAR]:xs,year:xs,years:xs},tS=new Set([nn.WEEK,nn.WEEK_DHTMLX,"week","weeks"]);function Ra(t,e={}){let n=[],i=[],r=e.daysPerWeek!==void 0&&Number.isFinite(e.daysPerWeek)&&e.daysPerWeek>0?e.daysPerWeek:ZI,a=t.replace(/\s+/g,"");if(a.length===0)return{specs:n,errors:i};for(let o of a.split(nu)){if(o.length===0)continue;let s=eS(o,r);s?n.push(s):i.push(o)}return{specs:n,errors:i}}function eS(t,e){let n=t.toLowerCase(),i=iu.exec(n);if(!i)return null;let[,r,a,o,s,l]=i,c=a?Fn[a]:Fn[tu],d=0;if(s!==void 0){let u=Number(s);if(Number.isNaN(u))return null;let p=l!==void 0&&tS.has(l)?e:QI[l??nn.DAY],f=u*p;d=o==="-"?-f:f}return{correlativeId:r,type:c,lag:d}}function La(t){let{targetActivityId:e,currentLinks:n,desiredSpecs:i}=t,r=[],a=new Map;for(let c of i){let d=t.resolveActivityByCorrelative(c.correlativeId);if(d==null){r.push(c);continue}let u=ka(d,c.type);a.has(u)||a.set(u,{source:d,type:c.type,lag:c.lag})}let o=new Map;for(let c of n)String(c.target)===String(e)&&o.set(ka(c.source,c.type),c);let s=[],l=ru(o,a,c=>c.source);for(let[c,d]of a){if(o.has(c))continue;let u=l.get(String(d.source))?.pop();if(!u)continue;let[p,f]=u;s.push({kind:Et.UPDATE,linkId:f.id,type:d.type,lag:d.lag}),o.delete(p),a.delete(c)}for(let[c,d]of o)a.has(c)||s.push({kind:Et.DELETE,linkId:d.id});for(let[c,d]of a){let u=o.get(c);u&&u.lag!==d.lag&&s.push({kind:Et.UPDATE,linkId:u.id,lag:d.lag})}for(let[c,d]of a)o.has(c)||s.push({kind:Et.CREATE,source:d.source,target:e,type:d.type,lag:d.lag});return{operations:s,unresolved:r}}function ka(t,e){return`${String(t)}::${e}`}function ru(t,e,n){let i=new Map;for(let r of t){if(e.has(r[0]))continue;let a=String(n(r[1])),o=i.get(a)??[];o.push(r),i.set(a,o)}return i}function Oa(t){let{sourceActivityId:e,currentLinks:n,desiredSpecs:i}=t,r=[],a=new Map;for(let c of i){let d=t.resolveActivityByCorrelative(c.correlativeId);if(d==null){r.push(c);continue}let u=ka(d,c.type);a.has(u)||a.set(u,{target:d,type:c.type,lag:c.lag})}let o=new Map;for(let c of n)String(c.source)===String(e)&&o.set(ka(c.target,c.type),c);let s=[],l=ru(o,a,c=>c.target);for(let[c,d]of a){if(o.has(c))continue;let u=l.get(String(d.target))?.pop();if(!u)continue;let[p,f]=u;s.push({kind:Et.UPDATE,linkId:f.id,type:d.type,lag:d.lag}),o.delete(p),a.delete(c)}for(let[c,d]of o)a.has(c)||s.push({kind:Et.DELETE,linkId:d.id});for(let[c,d]of a){let u=o.get(c);u&&u.lag!==d.lag&&s.push({kind:Et.UPDATE,linkId:u.id,lag:d.lag})}for(let[c,d]of a)o.has(c)||s.push({kind:Et.CREATE,source:e,target:d.target,type:d.type,lag:d.lag});return{operations:s,unresolved:r}}function ba(t){let e=Math.sign(t)*Math.round(Math.abs(t));return Object.is(e,-0)?0:e}function ne(t,e){return Math.sign(t)*Math.round(Math.abs(t)*e)}var au={rawInputToConstraintDate(t,e){let n=new Date(t);return n.setUTCHours(0,0,0,0),n.getTime()===t.getTime()?e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:dt.HOUR}):e.isWorkTime(t,dt.HOUR)?t:n},computeLagBetweenTasks(t,e,n){return n.calculateDuration(t,e)}};function Ms(t,e,n){switch(n){case H.FINISH_TO_START:return{sourceDate:t.endDate,targetDate:e.startDate};case H.START_TO_START:return{sourceDate:t.startDate,targetDate:e.startDate};case H.FINISH_TO_FINISH:return{sourceDate:t.endDate,targetDate:e.endDate};case H.START_TO_FINISH:return{sourceDate:t.startDate,targetDate:e.endDate}}}var Us=au;var fi=class{adapter;reporter;currentCalculationId=0;topoCache=new ua;expandedLinksCache=new ga;constructor(e,n=pi){this.adapter=e,this.reporter=n}getCurrentCalculationId(){return this.currentCalculationId}invalidateTopoCache(){this.topoCache.invalidate()}invalidateExpandedLinksCache(){this.expandedLinksCache.invalidate()}invalidateAllCaches(){this.topoCache.invalidate(),this.expandedLinksCache.invalidate()}async schedule(e={}){let n=++this.currentCalculationId,i=wd(n,()=>this.currentCalculationId),r={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{rS(this.adapter);let a=rn("schedule.total"),o=rn("schedule.expandParentLinks"),s=this.adapter.getAllLinks(),l=this.expandedLinksCache.get(s,this.adapter);Fe(o);let c=l;if((await ci(i)).aborted)return{...r,cancelled:!0};let d=rn("schedule.scoping"),u=this.adapter.getAllIds(),p=aS(e,c,this.adapter),f=p.links,y=p.idSet;Fe(d);let m=rn("schedule.topologicalSort"),h=sS(this.topoCache,u,c,y);if(Fe(m),h.hasCycles)return Fe(a),{...r,cycles:[h.cycleNodes]};if((await ci(i)).aborted)return{...r,cancelled:!0};let A=rn("schedule.processConstraints"),T=new Map;if(Gd(h.ordered,this.adapter,T),Fe(A),(await ci(i)).aborted)return{...r,cancelled:!0};let b=rn("schedule.asapPass"),S=await zd(h.ordered,f,this.adapter,e,i,T);if(Fe(b),(await ci(i)).aborted)return{...r,cancelled:!0};let g=rn("schedule.alapPass"),w=await Jd(h.reversed,f,S,this.adapter,e,i);if(Fe(g),(await ci(i)).aborted)return{...r,cancelled:!0};let R=rn("schedule.diff"),L=[];for(let[P,O]of w){let M=this.adapter.getActivity(P);if(!M)continue;let j=M.startDate.getTime()!==O.startDate.getTime(),z=M.endDate.getTime()!==O.endDate.getTime();(j||z)&&L.push(P)}return Fe(R),Fe(a),{plans:w,updatedIds:L,cycles:[],cancelled:!1}}catch(a){throw this.reporter.error("[AutoScheduler] Error during scheduling",a),a}}},nS=!1;function iS(){let t=globalThis.__SCHEDULER_PHASE_LOG__;return typeof t=="boolean"?t:nS}function rn(t){return{name:t,startedAt:performance.now()}}function rS(t){let e=t;typeof e.clearCalendarCache=="function"&&e.clearCalendarCache()}function Fe(t){if(!iS())return;let e=performance.now()-t.startedAt;console.log(`[scheduler] ${t.name} ${e.toFixed(1)}ms`)}function aS(t,e,n){let i=t.triggerId;if(i==null)return{idSet:null,links:e};let r=Bd(i,e);return oS(r,e,n)}function oS(t,e,n){let i=new Set(t.activityIds),r=new Set;for(let o of n.getAllActivities()){let s=String(o.id);o.constraintType===D.ALAP&&!i.has(s)&&(r.add(s),i.add(s))}if(r.size===0)return{idSet:i,links:t.links};let a=[...t.links];for(let o of e)(r.has(String(o.source))||r.has(String(o.target)))&&a.push(o);return{idSet:i,links:a}}function sS(t,e,n,i){let r=t.get(e,n);if(r.hasCycles){let o=i?Array.from(i):e;return De(o,n)}if(!i)return r;let a=xd(r.ordered,i);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function ou(t,e,n){let i=e.getActivity(t);if(!i)return;let r=n?{...i,endDate:n.endDate}:i,a=e.calendarReader.getCalendar(String(i.calendarId));for(let o of e.getIncomingLinkIds(t)){let s=e.getLink(o);if(!s)continue;let l=e.getActivity(s.source);if(!l||l.constraintType===D.ALAP||Ne(i.type)&&(s.type===H.START_TO_FINISH||s.type===H.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=Ms(l,r,s.type),p=Us.computeLagBetweenTasks(d,u,a);p!==s.lag&&e.setLinkField(s.id,Gt.LAG,p)}}function su(t,e){let n=e.getActivity(t);n&&Ne(n.type)&&(n.durationHours=0)}function Na(t){let e=0,n=!1;for(let i of t)i.ponderator>0&&(e+=i.ponderator/100*i.progress,n=!0);return n?e:null}function lu(t){return Number(t.toFixed(2))}function sr(t){for(let e of lS(t))du(e,t)}function cu(t,e){for(let n of t)du(n,e)}function lS(t){let e=new Set;t.forEachActivity((i,r)=>{t.getChildren(r).length>0&&e.add(r)});let n=new Map;for(let i of e)n.set(i,cS(i,t));return[...e].sort((i,r)=>(n.get(r)??0)-(n.get(i)??0))}function cS(t,e){let n=0,i=t;for(;i&&i!=="0"&&e.getActivity(i);)n+=1,i=e.getParentId(i);return n}function du(t,e){let n=e.getChildren(t);if(n.length===0)return;let i=[];for(let r of n){let a=e.getActivity(r);a&&i.push({progress:Number(a.progress??0),ponderator:Number(a.ponderator??0)})}Hs(t,i,e)}function Hs(t,e,n){let i=n.getActivity(t);if(!i)return;let r=Na(e);if(r===null){let a=n.getProgressFallback(t);a!==null&&n.setActivityField(t,E.PROGRESS,a);return}n.getProgressFallback(t)===null&&n.setProgressFallback(t,Number(i.progress??0)),n.setActivityField(t,E.PROGRESS,lu(r))}function uu(t,e,n){let i=[t];for(;i.length>0;){let r=i.pop();if(r===void 0)continue;let a=n.getChildren(r);a.length!==0&&(n.setProgressFallback(r,e),i.push(...a))}}function $t(t,e){return(Number(t)||0)*(Number(e)||0)/100}var lr={SKIP:"skip",FREEZE_WITHOUT_CONTRIBUTION:"freeze-when-no-contribution"};async function we(t,e,n=!0,i={}){let r=e?cr(t,e):hS(t),a=n?i.progressMode??lr.FREEZE_WITHOUT_CONTRIBUTION:lr.SKIP;await dS(r,t,a,{recomputeRealWork:i.recomputeRealWork??!1})}function Fa(t,e){pu(t,e,lr.SKIP)}async function dS(t,e,n,i={recomputeRealWork:!1}){let a=0;for(let o of t)pu(o,e,n,i.recomputeRealWork),a+=1,a%200===0&&await mt()}function cr(t,e){let n=new Set,i=new Map;for(let o of e)uS(o,t,n,i);if(n.size===0)return[];let r=Array.from(n),a=pS(r,i);return fu(r,a)}function uS(t,e,n,i){let r=e.getParentId(t);for(;r&&!V(r);){if(n.has(r))return;n.add(r);let a=e.getParentId(r);i.set(r,a),r=a}}function pS(t,e){let n=new Map;for(let i of t){if(n.has(i))continue;let r=[],a=new Set,o=i;for(;o&&!V(o)&&!n.has(o)&&!a.has(o);)r.push(o),a.add(o),o=e.get(o)??null;let s=o?n.get(o)??0:0;for(let l=r.length-1;l>=0;l-=1)s+=1,n.set(r[l],s)}return n}function fS(t,e,n){let i=null,r=null,a=0,o=[];for(let s of t){let l=e.getActivity(s);if(!l)continue;let c=l.startDate.getTime(),d=l.endDate.getTime();(i===null||c<i)&&(i=c),(r===null||d>r)&&(r=d),n&&(a+=yS(l,e.getChildren(s).length>0)),o.push({progress:Number(l.progress??0),ponderator:Number(l.ponderator??0)})}return{minStart:i,maxEnd:r,realWorkSum:a,weightedChildren:o}}function pu(t,e,n=lr.FREEZE_WITHOUT_CONTRIBUTION,i=!1){let r=e.getActivity(t);if(!r)return;let a=e.getChildren(t);if(a.length===0)return;let o=fS(a,e,i);if(o.minStart===null||o.maxEnd===null)return;let s=String(r.calendarId??""),l=e.calendarReader.getCalendar(s),c=new Date(o.minStart),d=new Date(o.maxEnd),u=l.calculateDuration(c,d);e.setActivityField(t,"startDate",c),e.setActivityField(t,"endDate",d),e.setActivityField(t,"durationHours",u),n!==lr.SKIP&&Hs(t,o.weightedChildren,e),i&&e.setActivityField(t,"realWorkHours",o.realWorkSum)}function yS(t,e){return e?Number(t.realWorkHours)||0:$t(t.workHours,t.progress)}function hS(t){let e=mS(t),n=gS(e,t);return fu(e,n)}function mS(t){let e=new Set;return t.forEachActivity(n=>{n.parentId!==null&&e.add(n.parentId)}),Array.from(e)}function gS(t,e){let n=new Map;for(let i of t)n.set(i,AS(i,e));return n}function AS(t,e){let n=0,i=t;for(;i&&!V(i)&&e.getActivity(i);)n+=1,i=e.getParentId(i);return n}function fu(t,e){return[...t].sort((n,i)=>(e.get(i)??0)-(e.get(n)??0))}var yu={updateActivityDuration:su,updateTaskTiming:SS("updateTaskTiming"),adjustLinkLagOnTaskMove:ou,recordLastStartDate:IS};function IS(t,e){let n=e.getActivity(t);n&&e.setLastStartDate(t,n.startDate)}function an(t,e,n,i){for(let r of e){let a=r in yu?yu[r]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${r} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(t,n,i??null)}}function SS(t){return()=>{console.debug(`[replay post-processors] ${t}: not yet ported to adapter \u2014 no-op.`)}}function K(t,e){return e!==void 0?{ok:!0,value:t,raw:e}:{ok:!0,value:t}}function Z(t){return{ok:!1,reason:t}}function tt(){return{valid:!0}}function gt(t,e){return e!==void 0?{valid:!1,reason:t,notification:e}:{valid:!1,reason:t}}function X(){return{allowed:!0}}function at(t,e){return e!==void 0?{allowed:!1,reason:t,alertKey:e}:{allowed:!1,reason:t}}function it(t,e={}){return{patch:t,needsAutoSchedule:e.autoSchedule??!1,postProcessors:e.postProcessors??[],...e.cascadeMutations!==void 0?{cascadeMutations:e.cascadeMutations}:{},...e.trackingEvents!==void 0?{trackingEvents:e.trackingEvents}:{}}}var Ct={PROGRESS_ENTRY:"activity_progress_entry",PROGRESS_UPDATE_RADIO_BUTTON:"activity_progress_update_radio_button",DURATION_ENTRY:"activity_duration_entry",START_DATE_ENTRY:"activity_start_date_entry",END_DATE_ENTRY:"activity_end_date_entry",NAME_ENTRY:"activity_name_entry",DESCRIPTION_ENTRY:"activity_description_entry",CALENDAR_ASSIGNMENT:"activity_calendar_assignment",COST_BUDGETED_ENTRY:"activity_cost_budgeted_entry",COST_SPENT_ENTRY:"activity_cost_spent_entry",LABOR_HOURS_BUDGETED_ENTRY:"activity_labor_hours_budgeted_entry"};var hu={targetField:"name",canEdit(){return X()},parseInput(t){return typeof t!="string"?Z("not_a_string"):K(t)},validate(){return tt()},transform(t,e){return it({name:e},{autoSchedule:!1,postProcessors:[]})},trackEvent:Ct.NAME_ENTRY};var mu={targetField:"description",canEdit(){return X()},parseInput(t){return typeof t!="string"?Z("not_a_string"):K(t.trim())},validate(){return tt()},transform(t,e){return it({description:e},{autoSchedule:!1,postProcessors:[]})},trackEvent:Ct.DESCRIPTION_ENTRY};function pe(t){return t.constraintType??D.ASAP}var wa=100;function on(t){return t.progress>=wa}function St(t,e){return ue(t.type,e.hasChildren(t.id))}function gu(t){return t.progress>0}function Au(t){return t.hasLookaheadTasks}function wn(t,e){return Math.round(Math.ceil(t*e*60)/60)}var yi=t=>({endDate:t});var xa="UTC";function sn(t,e){if(e){let n=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),i=r=>Number(n.find(a=>a.type===r)?.value);return new Date(Date.UTC(i("year"),i("month")-1,i("day")))}return new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate()))}function Ma(t,e){if(!e||e===xa){let p=new Date(t);return p.setUTCHours(23,59,0,0),p}let n=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(t),i=p=>Number(n.find(f=>f.type===p)?.value),r=i("year"),a=i("month"),o=i("day"),s=Date.UTC(r,a-1,o,23,59,0,0),l=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(s)),c=p=>Number(l.find(f=>f.type===p)?.value),u=Date.UTC(c("year"),c("month")-1,c("day"),c("hour")===24?0:c("hour"),c("minute"),c("second"))-s;return new Date(s-u)}function vS(t,e){let n=sn(e,xa);for(;!t.isWorkTime(n,dt.DAY);)n=new Date(n),n.setUTCDate(n.getUTCDate()+1),n=sn(n,xa);return n}function ur(t,e){return t.getClosestWorkTime({direction:q.FUTURE,date:e,unit:dt.HOUR})}function Bs(t,e){let n=vS(t,e),i=new Date(n);return i.setUTCDate(i.getUTCDate()+1),i.setUTCHours(0,0,0,0),t.getClosestWorkTime({direction:q.PAST,date:i,unit:dt.HOUR})}function Iu(t,e){return e.isWorkTime(t,dt.HOUR)?new Date(t):e.getClosestWorkTime({direction:q.FUTURE,date:t,unit:dt.HOUR})}function Su(t,e){if(e.isWorkTime(t,dt.HOUR))return new Date(t);let n=js(t)?CS(t):t;return e.getClosestWorkTime({direction:q.PAST,date:n,unit:dt.HOUR})}function js(t){return t.getUTCHours()===0&&t.getUTCMinutes()===0&&t.getUTCSeconds()===0&&t.getUTCMilliseconds()===0}function CS(t){let e=new Date(t);return e.setUTCDate(e.getUTCDate()+1),e}var dr=new Set([D.SNET,D.SNLT,D.MSO]),Ws=new Set([D.FNET,D.FNLT,D.MFO]),ln=new Set([D.ASAP,D.ALAP]),Ua=D.SNET;function fe(t,e,n){let i=sn(t,xa);return!dr.has(n)&&!Ws.has(n)?i:dr.has(n)?vu(i,e):Cu(i,e)}function vu(t,e){return _u(t,ur(e,t))}function Cu(t,e){return _u(t,Bs(e,t))}function Du(t,e){return js(t)?vu(t,e):new Date(t)}function Tu(t,e){return js(t)?Cu(t,e):new Date(t)}function _u(t,e){let n=new Date(t);return n.setUTCHours(e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds()),n}var cn=()=>({constraintType:Ua});var xn=t=>({constraintDate:t}),Eu=t=>({constraintDate:t});var Pu={UPDATE_ACTIVITY_DURATION:"updateActivityDuration",UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ha={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"},ye={COMPLETED:"completed",SUMMARY:"summary",HAS_PROGRESS:"has_progress",HAS_LOOKAHEAD_TASKS:"has_lookahead_tasks",SIR_START_AFTER_PROGRESS:"sir_start_after_progress",DATA_DATE_UNAVAILABLE:"data_date_unavailable",DATA_DATE_ACTUAL_START_LOCKED:"data_date_actual_start_locked",DATA_DATE_ACTIVITY_COMPLETED:"data_date_activity_completed",DATA_DATE_UNITS_PERCENT_READ_ONLY:"data_date_units_percent_read_only",SECONDARY_CONSTRAINT_TYPE_REQUIRED:"secondary_constraint_type_required"},Ba={CANT_EDIT_COMPLETED:"cant_edit_completed_activity",SUMMARY_COLUMN_VALUE:"summary_column_value",CANT_EDIT_WITH_PROGRESS:"cant_edit_activity_with_progress",SIR_CANT_MOVE_START_AFTER_PROGRESS:"sir_cant_move_start_after_progress",CANT_EDIT_WITH_TASK:"cant_edit_actvity_with_task",DATA_DATE_EDIT_REJECTED:"data_date_edit_rejected",DATA_DATE_UNITS_PERCENT_READ_ONLY:"data_date_units_percent_read_only"};function hi(t,e,n){return qr(t,e,n)}function mi(t,e,n){return zr(t,e,n)}var ku={targetField:"durationHours",canEdit(t,e){return on(t)?at("completed","cant_edit_completed_activity"):St(t,e)?at("summary","summary_column_value"):X()},parseInput(t,e,n){let i=parseFloat(String(t));return Number.isFinite(i)?K(wn(i,n.hoursPerDay)):Z("not_a_number")},validate(t,e,n){return Ru(n)?gt(Ha.NEGATIVE_DURATION):DS(e,n)?gt("unchanged"):tt()},transform(t,e,n){if(Ru(e))return it({},{autoSchedule:!1,postProcessors:[]});let i=TS(t,e,n),r=_S(t,e,n,i.violated);return{...it(r,{autoSchedule:!0,postProcessors:[Pu.RECORD_LAST_START_DATE]}),...i.violated?{constraintWarning:mi(i.constraintType,i.constraintDate,Lu(t,e,n)??void 0)}:{}}},trackEvent:Ct.DURATION_ENTRY};function Ru(t){return Math.sign(t)===-1}function DS(t,e){return t===e}function TS(t,e,n){let i=n.calendars.getCalendar(t.calendarId);if(!i)return{violated:!1};let r=t.constraintType;if(r!==D.FNET&&r!==D.FNLT&&r!==D.MFO)return{violated:!1};let a=i.calculateEndDate(t.startDate,e);return hi(r,t.constraintDate,a)}function _S(t,e,n,i=!1){let r={};i&&Object.assign(r,cn(),xn(t.startDate));let a=nr(t.durationHours,e);a&&(r.type=a),r.durationHours=e;let o=Lu(t,e,n);return o&&Object.assign(r,yi(o)),r}function Lu(t,e,n){let i=n.calendars.getCalendar(t.calendarId);return i?i.calculateEndDate(t.startDate,e):null}var gi=t=>({realWorkHours:t});var ES=0,PS=wa,Ai={targetField:"progress",canEdit(t,e){return St(t,e)?at("summary","summary_column_value"):Au(t)?at("has_lookahead_tasks","cant_edit_actvity_with_task"):X()},parseInput(t){let e=parseFloat(String(t));return Number.isNaN(e)?Z("not_a_number"):K(e)},validate(t,e,n){return RS(n)?gt("out_of_range"):tt()},transform(t,e,n){let i=Nn(e),r=t.progress!==e&&i,a=kS(e),o=bS(t,e,n.hierarchy),s={progress:e,autoScheduling:i,...gi(o.get(t.id)??0)},l=a?LS(t,e,i,n.hierarchy,o):[],c=a?FS(t,e,n.hierarchy):[],d=l.length+c.length>0?[...l,...c]:void 0,u=[],p=a?xS(t,e):void 0;return it(s,{autoSchedule:r,postProcessors:u,cascadeMutations:d,trackingEvents:p})},trackEvent:Ct.PROGRESS_ENTRY};function RS(t){return t<ES||t>PS}function kS(t){return t===wa||Nn(t)}function LS(t,e,n,i,r){return i.getDescendantIds(t.id).map(o=>({activityId:o,fields:OS(e,n,r.get(o)??0)}))}function OS(t,e,n){return{progress:t,autoScheduling:e,...gi(n)}}function bS(t,e,n){let i=new Map,r=o=>{let s=0;for(let l of n.getChildHhInfo(o)){let c=n.hasChildren(l.id)?r(l.id):$t(l.workHours,e);i.set(l.id,c),s+=c}return s},a=n.hasChildren(t.id)?r(t.id):$t(t.workHours,e);return i.set(t.id,a),i}function NS(t,e){let n=[t.id,...e.getDescendantIds(t.id)],i=a=>e.getChildProgressInfo(a).some(o=>e.hasChildren(o.id)),r=a=>e.getAncestorIds(a).length;return n.filter(a=>i(String(a))).map(String).sort((a,o)=>r(o)-r(a))}function FS(t,e,n){let i=new Map;i.set(t.id,e);for(let o of n.getDescendantIds(t.id))i.set(o,e);let r=[...NS(t,n),...n.getAncestorIds(t.id)],a=[];for(let o of r){let s=wS(o,i,n);s!==null&&(i.set(o,s),a.push({activityId:o,fields:{progress:s}}))}return a}function wS(t,e,n){let i=n.getChildProgressInfo(t).map(a=>({progress:e.has(a.id)?e.get(a.id):a.progress,ponderator:a.ponderator??0})),r=Na(i);return r===null?null:Number(r.toFixed(2))}function xS(t,e){return[{name:Ct.PROGRESS_UPDATE_RADIO_BUTTON,properties:{activity_id:t.id,activity_name:t.name,progress_updated:e}}]}var Ou={targetField:"cost",canEdit(t,e){return St(t,e)?at("summary","summary_column_value"):X()},parseInput(t){if(String(t).trim()==="")return K(0);let e=parseFloat(String(t));return Number.isNaN(e)?Z("not_a_number"):K(e)},validate(){return tt()},transform(t,e,n){let i=MS(t,e,n.hierarchy);return it({cost:e},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:Ct.COST_BUDGETED_ENTRY};function MS(t,e,n){let i=new Map;i.set(t.id,e);let r=[];for(let a of n.getAncestorIds(t.id)){let o=0;for(let s of n.getChildCostInfo(a))o+=i.has(s.id)?i.get(s.id):s.cost;i.set(a,o),r.push({activityId:a,fields:{cost:o}})}return r}var bu={targetField:"usedCost",canEdit(t,e){return St(t,e)?at("summary","summary_column_value"):X()},parseInput(t){if(String(t).trim()==="")return K(0);let e=parseFloat(String(t));return Number.isNaN(e)?Z("not_a_number"):K(e)},validate(){return tt()},transform(t,e,n){let i=US(t,e,n.hierarchy);return it({usedCost:e},{autoSchedule:!1,postProcessors:[],cascadeMutations:i})},trackEvent:Ct.COST_SPENT_ENTRY};function US(t,e,n){let i=new Map;i.set(t.id,e);let r=[];for(let a of n.getAncestorIds(t.id)){let o=0;for(let s of n.getChildUsedCostInfo(a))o+=i.has(s.id)?i.get(s.id):s.usedCost;i.set(a,o),r.push({activityId:a,fields:{usedCost:o}})}return r}var Nu={targetField:"workHours",canEdit(t,e){return St(t,e)?at("summary","summary_column_value"):X()},parseInput(t){if(String(t).trim()==="")return K(0,t);let e=parseFloat(String(t));return Number.isNaN(e)?Z("not_a_number"):K(e)},validate(){return tt()},transform(t,e,n,i){let r=Fu(e,t.progress),a=String(i).trim()===""?[]:HS(t,e,r,n.hierarchy);return it({workHours:e,...gi(r)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:Ct.LABOR_HOURS_BUDGETED_ENTRY};function Fu(t,e){return $t(t,e)}function HS(t,e,n,i){let r=new Map,a=new Map;r.set(t.id,e),a.set(t.id,n);let o=[];for(let s of i.getAncestorIds(t.id)){let l=0,c=0;for(let d of i.getChildHhInfo(s)){let u=r.has(d.id)?r.get(d.id):d.workHours,p=a.has(d.id)?a.get(d.id):d.realWorkHours??Fu(d.workHours,d.progress);l+=u,c+=p}r.set(s,l),a.set(s,c),o.push({activityId:s,fields:{workHours:l,...gi(c)}})}return o}function Ii(t,e){return t.getUTCFullYear()===e.getUTCFullYear()&&t.getUTCMonth()===e.getUTCMonth()&&t.getUTCDate()===e.getUTCDate()}function Vs(t,e){return t.getTime()<e.getTime()}function dn(t){return t instanceof Date&&!Number.isNaN(t.getTime())}var ja=t=>({durationHours:t});var BS="sir-apply",wu={targetField:"startDate",canEdit(t,e,n){return St(t,e)?at("summary","summary_column_value"):gu(t)?n?.eventSource!==BS?at("has_progress","cant_edit_activity_with_progress"):dn(n.newValue)?Ii(t.startDate,n.newValue)?X():on(t)?at("completed","cant_edit_completed_activity"):X():X():X()},parseInput(t,e,n){return dn(t)?K(sn(t,"UTC")):Z("invalid_date")},validate(t,e,n,i){if(Ii(e,n))return gt("unchanged");let r=jS(t,n,i);return r||tt()},transform(t,e,n){let i=n.calendars.getCalendar(t.calendarId);if(!i)throw new Error("startDatePipeline: no calendar resolved (integrity)");let r=ur(i,e),a=t.type===k.MILESTONE,o=a?r:i.calculateEndDate(r,t.durationHours),s=r;return{...it({startDate:r,...yi(o),...a?ja(0):{},...cn(),...xn(s)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:WS(t,r,i)}},trackEvent:Ct.START_DATE_ENTRY};function jS(t,e,n){let i=n.hierarchy.getParentStartDateIfHasPredecessors(t.id);if(!i)return null;let r=sn(i,"UTC");return e.getTime()<r.getTime()?gt("before_parent_start"):null}function WS(t,e,n){let i=n.calculateEndDate(e,t.durationHours),r=En(pe(t),e,i),a=hi(pe(t),t.constraintDate,r);if(a.violated)return mi(a.constraintType,a.constraintDate,r)}var VS=99.999,KS="sir-apply",Mu={targetField:"endDate",canEdit(t,e,n){return St(t,e)?at("summary","summary_column_value"):GS(t)&&!YS(t.endDate,n)?at("completed","cant_edit_completed_activity"):X()},parseInput(t,e,n){if(!dn(t))return Z("invalid_date");let i=sn(t,"UTC"),r=n.calendars.getCalendar(e.calendarId);return r?r.isWorkTime(i,dt.DAY)?K(Bs(r,i)):K(r.getClosestWorkTime({direction:"past",date:i,unit:dt.HOUR})):K(i)},validate(t,e,n,i){if(Ii(t.endDate,n))return gt("unchanged");if($S(n,t))return gt("before_date_origin");if(qS(n,t))return gt("before_start_date");let r=zS(n,t,i);return r||tt()},transform(t,e,n){let i=JS(t,e),r=XS(t,e,n,!!i);return{...it(r,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...i?{constraintWarning:i}:{}}},trackEvent:Ct.END_DATE_ENTRY};function YS(t,e){return e?.eventSource===KS&&dn(e.newValue)&&Ii(t,e.newValue)}function GS(t){return t.progress>=VS}function $S(t,e){return e.dateOrigin?Vs(t,e.dateOrigin):!1}function qS(t,e){return Vs(t,e.startDate)}function zS(t,e,n){let i=n.calendars.getCalendar(e.calendarId);return i?i.isWorkTime(t,dt.DAY)?null:gt("not_working_day"):null}function JS(t,e){if(pe(t)===D.MSO)return;let i=En(pe(t),t.startDate,e),r=hi(pe(t),t.constraintDate,i);if(r.violated)return mi(r.constraintType,r.constraintDate,i)}function XS(t,e,n,i=!1){let r={};Ne(t.type)&&!i&&xu(t)?Object.assign(r,xn(t.startDate)):(i||xu(t))&&Object.assign(r,cn(),xn(t.startDate));let s=ZS(t,e,n),l=nr(t.durationHours,s);return l&&(r.type=l),Object.assign(r,ja(s)),r.endDate=e,r}function xu(t){return ln.has(pe(t))}function ZS(t,e,n){let i=n.calendars.getCalendar(t.calendarId);return i?i.calculateDuration(t.startDate,e):t.durationHours}var QS=new Set(Object.values(D)),Uu={targetField:"constraintType",canEdit(t,e){return on(t)?at("completed","cant_edit_completed_activity"):St(t,e)?at("summary","summary_column_value"):X()},parseInput(t){let e=String(t).toLowerCase();return tv(e)?K(e):Z("invalid_constraint_type")},validate(){return tt()},transform(t,e,n){let i=ev(t,e,n);return it(i,{autoSchedule:!0})}};function tv(t){return QS.has(t)}function ev(t,e,n){let i=iv(t,e);return{constraintType:e,...Eu(nv(t,e,i,n))}}function nv(t,e,n,i){if(t.type!==k.MILESTONE||!n||dr.has(e))return n;let r=i.calendars.getCalendar(String(t.calendarId));return r?fe(n,r,e):n}function iv(t,e){return ln.has(e)?null:dr.has(e)?t.startDate:Ws.has(e)?t.endDate:t.constraintDate}var Hu={targetField:"constraintDate",canEdit(t,e){return on(t)?at("completed","cant_edit_completed_activity"):St(t,e)?at("summary","summary_column_value"):X()},parseInput(t){return dn(t)?K(t):Z("invalid_date")},validate(){return tt()},transform(t,e,n){let i=Bu(t)?Ua:pe(t),r=n.calendars.getCalendar(t.calendarId);if(!r)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=fe(e,r,i),o=rv(t,a);return it(o,{autoSchedule:!0})}};function rv(t,e){return{constraintDate:e,...Bu(t)?cn():{}}}function Bu(t){return ln.has(pe(t))||!t.constraintType}var ju={targetField:"calendarId",canEdit(){return X()},parseInput(t){let e=String(t).trim();return av(e)?Z("empty_calendar"):K(e)},validate(t,e,n,i){return ov(t.calendarId,n)?gt("unchanged"):i.calendars.getCalendar(n)?tt():gt("unknown_calendar")},transform(t,e,n){return it(sv(t,e,n),{autoSchedule:!0,postProcessors:[]})},trackEvent:Ct.CALENDAR_ASSIGNMENT};function av(t){return t===""}function ov(t,e){return t===e}function sv(t,e,n){let i={calendarId:e,assignedDefaultCalendar:!1},r=n.calendars.getCalendar(e);if(r){let a=r.isWorkTime(t.startDate,"hour"),o=r.getClosestWorkTime({date:a?Wu(t.startDate):t.startDate,direction:"future",unit:"hour"});i.startDate=o;let s=lv(t,r);if(s&&(i.constraintDate=s),!t.autoScheduling)return i;Object.assign(i,yi(r.calculateEndDate(o,t.durationHours)))}return i}function lv(t,e){return!t.constraintDate||!t.constraintType?null:Zi({...t,constraintDate:Wu(t.constraintDate)},{getClosestWorkTime:({date:n,dir:i})=>e.getClosestWorkTime({date:n,direction:i,unit:dt.HOUR})})}function Wu(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}var Vu={targetField:"customId",canEdit(t,e){return St(t,e)?at("summary","summary_column_value"):X()},parseInput(t){if(t==null)return Z("empty_custom_id");if(typeof t!="string")return Z("not_a_string");let e=t.trim();return e.length===0?Z("empty_custom_id"):e.length>20?Z("exceeds_max_length"):K(e)},validate(){return tt()},transform(t,e){return it({customId:e},{autoSchedule:!1,postProcessors:[]})}};var Ku={targetField:"subcontractId",canEdit(){return X()},parseInput(t){if(t==null)return K(null);if(typeof t=="string"){let e=t.trim();if(e.length===0)return K(null);let n=Number(e);return!Number.isFinite(n)||!Number.isInteger(n)?Z("not_an_integer"):K(n)}return typeof t=="number"?!Number.isFinite(t)||!Number.isInteger(t)?Z("not_an_integer"):K(t):Z("not_an_integer")},validate(){return tt()},transform(t,e){return it({subcontractId:e},{autoSchedule:!1,postProcessors:[]})}};function pr(t){if(t==null)return null;if(typeof t=="object"){if(!("id"in t))return null;let e=t.id;return e==null?null:String(e)}return String(t)}function Wa(t){return t.some(e=>pr(e)===null)}var Yu={targetField:"responsableIds",canEdit(){return X()},parseInput(t){return t==null?K([]):Array.isArray(t)?K(t):Z("not_an_array")},validate(t,e,n){return Wa(n)?gt("missing_id"):tt()},transform(t,e){let n=e.map(pr).filter(i=>i!==null);return it({responsableIds:n},{autoSchedule:!1,postProcessors:[]})}};var Gu={targetField:"tagIds",canEdit(){return X()},parseInput(t){return t==null?K([]):Array.isArray(t)?K(t):Z("not_an_array")},validate(t,e,n){return Wa(n)?gt("missing_id"):tt()},transform(t,e){let n=e.map(pr).filter(i=>i!==null);return it({tagIds:n},{autoSchedule:!1,postProcessors:[]})}};var fr={TOTAL_FLOAT:"total_float",LONGEST_PATH:"longest_path"},ht={DURATION:"duration",UNITS:"units",PHYSICAL:"physical"},ie={TASK:"task",LEVEL_OF_EFFORT:"level_of_effort",START_MILESTONE:"start_milestone",FINISH_MILESTONE:"finish_milestone",WBS_SUMMARY:"wbs_summary",RESOURCE_DEPENDENT:"resource_dependent"},et={NOT_STARTED:"not_started",IN_PROGRESS:"in_progress",COMPLETED:"completed"},re={FIXED_DURATION_AND_UNITS:"fixed_duration_and_units",FIXED_DURATION_AND_UNITS_PER_TIME:"fixed_duration_and_units_per_time"};function Va(t){return t==="start_on"||t==="mandatory_start"?"mso":t==="finish_on"||t==="mandatory_finish"?"mfo":t}function un(t){return t.remainingDurationHours!==null}var wt={UNSTART:"unstart",UNCOMPLETE:"uncomplete",START_ON_PROGRESS:"start_on_progress",COMPLETE_ON_PROGRESS:"complete_on_progress",KEEP_IN_PROGRESS:"keep_in_progress",CLEAR_SECONDARY_CONSTRAINT:"clear_secondary_constraint"};function yr(t,e){return e?.includes(t)??!1}var cv={asap:[],alap:["fnlt","snlt"],snet:["fnlt","snlt"],fnet:["fnlt","snlt"],snlt:["fnet","snet"],fnlt:["fnet","snet"],mso:[],mfo:[]};function Ks(t){return t===null?[]:cv[t]}function Si(t,e){return e===null||Ks(t).includes(e)}var qt=(t,e)=>({...it({}),dataDatePatch:{[t]:e}}),Ka=t=>({...it({}),dataDatePatch:t}),hr=(t,e)=>({...Ka(t),confirmation:e}),mr=t=>t.p6===void 0?at("data_date_unavailable"):X(),pn=t=>({targetField:t,canEdit:mr,parseInput(e){return e===null?K(null):!(e instanceof Date)||!Number.isFinite(e.getTime())?Z("invalid_date"):K(e)},validate(){return tt()},transform(e,n){return qt(t,n)}}),zu=(t,e=Number.POSITIVE_INFINITY)=>({targetField:t,canEdit:mr,parseInput(n){let i=typeof n=="number"||typeof n=="string"&&n.trim()!==""?Number(n):Number.NaN;return Number.isFinite(i)?K(i):Z("not_a_number")},validate(n,i,r){return r<0||r>e?gt("out_of_range"):tt()},transform(n,i){return qt(t,i)}}),Ju=(t,e)=>({targetField:t,canEdit:mr,parseInput(n){return typeof n=="string"&&e.has(n)?K(n):Z("not_a_string")},validate(){return tt()},transform(n,i){return qt(t,i)}}),dv=new Set(["not_started","in_progress","completed"]),uv=new Set(["duration","units","physical"]),pv=new Set(["snet","snlt","fnet","fnlt"]),fv=(t,e)=>{let n=t.p6?.executionStatus;return n===e||n===void 0?qt("executionStatus",e):n===et.NOT_STARTED?Ka(e===et.IN_PROGRESS?{actualStart:t.startDate}:{actualStart:t.startDate,actualFinish:t.endDate}):n===et.IN_PROGRESS?e===et.COMPLETED?qt("actualFinish",t.endDate):hr({actualStart:null},wt.UNSTART):e===et.IN_PROGRESS?hr({actualFinish:null},wt.UNCOMPLETE):hr({actualStart:null,actualFinish:null},wt.UNSTART)},$u=(t,e)=>{if(e!==null||t.p6?.actualStart==null)return qt("actualStart",e);let i=t.p6?.actualFinish!=null;return hr(i?{actualStart:null,actualFinish:null}:{actualStart:null},wt.UNSTART)},qu=(t,e)=>e!==null||t.p6?.actualFinish==null?qt("actualFinish",e):hr({actualFinish:null},wt.UNCOMPLETE),gr=(t,e)=>{let n=e.calendars.getCalendar(t.calendarId);if(!n)throw new Error("dataDatePipelines: no calendar resolved (integrity)");return n},Xu={...pn("actualStart"),transform(t,e,n){if(e===null)return $u(t,null);let i=gr(t,n);return $u(t,Du(e,i))}},Zu={...pn("actualFinish"),transform(t,e,n){if(e===null)return qu(t,null);let i=gr(t,n);return qu(t,Tu(e,i))}},Qu={...pn("plannedStart"),transform(t,e,n){if(e===null)return qt("plannedStart",null);let i=gr(t,n);return qt("plannedStart",Iu(e,i))}},tp={...pn("plannedFinish"),transform(t,e,n){if(e===null)return qt("plannedFinish",null);let i=gr(t,n);return qt("plannedFinish",Su(e,i))}},ep=zu("remainingDurationHours"),np={...Ju("executionStatus",dv),transform(t,e){return fv(t,e)}},ip=pn("expectedFinish"),rp=pn("suspendDate"),ap=pn("resumeDate"),op={targetField:"secondaryConstraintType",canEdit:mr,parseInput(t){return t===null||t===""?K(null):typeof t=="string"&&pv.has(t)?K(t):Z("not_a_string")},validate(t,e,n){return Si(t.constraintType,n)?tt():gt("constraint_violation")},transform(t,e){return e===null?Ka({secondaryConstraintType:null,secondaryConstraintDate:null}):t.p6?.secondaryConstraintType!=null?qt("secondaryConstraintType",e):Ka({secondaryConstraintType:e,secondaryConstraintDate:e.startsWith("s")?t.startDate:t.endDate})}},sp={...pn("secondaryConstraintDate"),canEdit(t,e){let n=mr(t,e);return n.allowed?t.p6?.secondaryConstraintType==null?at("secondary_constraint_type_required"):X():n},transform(t,e,n){let i=t.p6?.secondaryConstraintType??null;if(e===null||i===null)return qt("secondaryConstraintDate",e);let r=gr(t,n);return qt("secondaryConstraintDate",fe(e,r,i))}},lp=Ju("percentCompleteType",uv),cp=zu("physicalPercentComplete",100);var yv=new Map([[E.TEXT,hu],[E.DESCRIPTION,mu],[E.DURATION,ku],[E.PROGRESS,Ai],[E.COST,Ou],[E.USED_COST,bu],[E.HH_WORK_TIME,Nu],[E.START_DATE,wu],[E.END_DATE,Mu],[E.CONSTRAINT_TYPE,Uu],[E.CONSTRAINT_DATE,Hu],[E.CALENDAR_ID,ju],[E.CUSTOM_ID,Vu],[E.SUBCONTRACT_ID,Ku],[E.RESPONSABLES,Yu],[E.TAGS,Gu],[E.ACTUAL_START,Xu],[E.ACTUAL_FINISH,Zu],[E.PLANNED_START,Qu],[E.PLANNED_FINISH,tp],[E.REMAINING_DURATION_HOURS,ep],[E.EXECUTION_STATUS,np],[E.EXPECTED_FINISH,ip],[E.SUSPEND_DATE,rp],[E.RESUME_DATE,ap],[E.SECONDARY_CONSTRAINT_TYPE,op],[E.SECONDARY_CONSTRAINT_DATE,sp],[E.PERCENT_COMPLETE_TYPE,lp],[E.PHYSICAL_PERCENT_COMPLETE,cp]]);function _e(t){return yv.get(t)}var Dt={APPEND:"append",REPLACE:"replace"},Ya={ACTION_BUTTON:"action-button"},Ga={SIR_AUTO_REJECT:"sir-auto-reject"},$a={DATE_CHANGED:"date_changed",ACTIVITY_DELETED:"activity_deleted"},Un={VIOLATION:"constraint_violation"},Ht={DISPATCH_MANY:"dispatch-many",INIT:"init",UNDO:"undo",REDO:"redo",P6_SETTINGS_UPDATE:"p6-settings-update",P6_ACTIVITY_UPDATE:"p6-activity-update",P6_SCHEDULE:"p6-schedule"};function Hn(t,e){if(!e||e.type!==Gr.CONSTRAINT)return null;let n=e.data;return!n?.constraintType||!n.constraintDate?null:{kind:Un.VIOLATION,activityId:t,constraintType:n.constraintType,constraintDate:n.constraintDate,projectedDate:n.projectedDate??n.constraintDate,messageKey:e.messageKey}}var dp=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],up=new Set(dp),y0=new Set([...dp,...Object.values(Qn)]),pp=new Set(Object.values(Qn));function ae(t,e,n,i){t.setActivityFieldDynamic(e,n,i)}function fp(t,e,n,i){t.setLinkFieldDynamic(e,n,i)}function xe(t){return{...t,startDate:new Date(t.startDate),endDate:new Date(t.endDate),constraintDate:Ee(t.constraintDate),dateOrigin:Ee(t.dateOrigin),newActivityIds:[...t.newActivityIds],pendingRequestIds:[...t.pendingRequestIds],responsableIds:[...t.responsableIds],tagIds:[...t.tagIds],baselinePoints:t.baselinePoints.map(e=>({...e,startDate:Ee(e.startDate),endDate:Ee(e.endDate)})),baselineSnapshot:hv(t.baselineSnapshot),criticalPath:mv(t.criticalPath),...t.p6===void 0?{}:{p6:v(t.p6)}}}function Ee(t){return t===null?null:new Date(t)}function hv(t){return t===null?null:{...t,startDate:Ee(t.startDate),endDate:Ee(t.endDate)}}function mv(t){return t===null?null:{...t,earlyStart:Ee(t.earlyStart),earlyFinish:Ee(t.earlyFinish),lateStart:Ee(t.lateStart),lateFinish:Ee(t.lateFinish)}}var mp=200;function fn(t,e){let n=new Set([String(t)]);for(let i of e.cascadeMutations??[])n.add(String(i.activityId));return n}async function ot(t,e){let n=new Map,i=0;for(let r of e){i+=1,i%mp===0&&await mt();let a=t.getActivity(r);a&&n.set(r,rt(a))}return n}function rt(t){return xe(t)}function qa(t,e){let n=t.getActivity(e);return n?xe(n):null}function yn(t,e,n){yp(t,e,n.patch),n.dataDateState!==void 0&&t.setActivityField(e,"p6",n.dataDateState);for(let i of n.cascadeMutations??[])yp(t,i.activityId,i.fields)}function yp(t,e,n){for(let[i,r]of Object.entries(n)){if(!up.has(i))throw new Error(`applyFieldChanges: column write to non-writable field "${i}"`);ae(t,e,i,r)}}async function za(t,e,n,i){let r=[],a=0;for(let o of n){a+=1,a%mp===0&&await mt();let s=gv(t,e,o,i);s&&r.push(s)}return r}function gv(t,e,n,i){let r=t.getActivity(n);if(!r)return{id:n,kind:x.DELETED,after:null};let a=e.get(n);if(!a&&i?.has(n))return Av(n,i.get(n),r);let o=Gs(a,r);return Iv(o,i,n,r),a&&Object.keys(o).length===0?null:{id:n,kind:a?x.UPDATED:x.CREATED,fields:o,after:rt(r)}}function Av(t,e,n){return e===n.correlativeId?null:{id:t,kind:x.UPDATED,fields:{correlativeId:{before:e,after:n.correlativeId}},after:rt(n)}}function Iv(t,e,n,i){if(!e?.has(n)||Object.hasOwn(t,"correlativeId"))return;let r=e.get(n);r!==i.correlativeId&&(t.correlativeId={before:r,after:i.correlativeId})}var Sv=[U.CALENDAR_DURATION,U.BASELINE_VARIANCE_DAYS];function Gs(t,e){let n={},i=t??{},r=e,a=new Set([...Object.keys(i),...Object.keys(r)]);for(let o of Sv)a.delete(o);for(let o of a)(Object.hasOwn(i,o)!==Object.hasOwn(r,o)||!Ys(i[o],r[o]))&&(n[o]={before:hp(i[o]),after:hp(r[o])});return n}function hp(t){return t===null||typeof t!="object"?t:v(t)}function Ys(t,e){if(Object.is(t,e))return!0;if(t instanceof Date&&e instanceof Date)return t.getTime()===e.getTime();if(t==null||e==null)return!1;if(Array.isArray(t)||Array.isArray(e))return!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length?!1:t.every((o,s)=>Ys(o,e[s]));if(typeof t!="object"||typeof e!="object")return!1;let n=t,i=e,r=Object.keys(n),a=Object.keys(i);return r.length!==a.length?!1:r.every(o=>Object.hasOwn(i,o)&&Ys(n[o],i[o]))}function Ja(t,e,n){let i=new Set;i.add(t);for(let r of e)i.add(r);for(let r of n)i.add(r);return i}function $s(t,e){let n=new Set;for(let i of t)n.add(String(i));for(let i of e)n.add(i);return n}function vi(t,e,n,i,r){for(let a of e){if(n.has(a.activityId)||(r.add(a.activityId),i.has(a.activityId)))continue;let o=t.getActivity(a.activityId);if(!o)continue;let s=rt(o);a.before!==void 0&&(s.correlativeId=a.before),i.set(a.activityId,s)}}var vv=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Me(t){if(t==null||t==="")throw new Error(`[parseFromBackend] expected a date string, got "${t}"`);if(t.includes("T")||t.endsWith("Z")){let s=new Date(t);if(Number.isNaN(s.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${t}"`);return s}let e=t.match(vv);if(!e)throw new Error(`[parseFromBackend] unsupported date format "${t}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,n,i,r,a,o]=e;return new Date(Date.UTC(Number(n),Number(i)-1,Number(r),Number(a),Number(o)))}function Ci(t,e,n,i){if(t.getTime()>n.getTime())return 0;if(e.getTime()<n.getTime()||t.getTime()===e.getTime())return 100;let r=i.calculateDuration(t,n),a=i.calculateDuration(t,e);return a===0?0:r*100/a}var Cv=t=>t.type===k.PROJECT,Dv=(t,e,n)=>{let i=t.calendarId,r=i!=null?n.calendarReader.getCalendar(String(i)):null;if(!r)return 0;let a=o=>o instanceof Date?o:Me(String(o));return Ci(a(t.startDate),a(t.endDate),e,r)};function Tv(t,e,n){let i=[],r=(o,s)=>{let l=n.getActivity(o);l&&l.expectedProgress!==s&&(n.setActivityField(o,"expectedProgress",s),i.push(String(o)))},a=o=>{let s=n.getActivity(o);if(!s)return 0;if(!Cv(s)){let d=Dv(s,e,n);return r(o,d),d}let l=0;for(let d of n.getChildren(o)){let u=a(d),p=n.getActivity(d),f=typeof p?.ponderator=="number"?p.ponderator:0;l+=u*f}let c=l/100;return r(o,c),c};for(let o of t)a(o);return i}function Bn(t,e){let n=[];t.forEachActivity((i,r)=>{i.parentId===null&&n.push(r)}),Tv(n,e,t)}var _v=t=>t.type===k.PROJECT,Ev=t=>Lt(t),Pv=(t,e,n,i)=>{let r=Ev(t);if(!r)return 0;let a=(r.baseCalendarId!=null?n.getBaseCalendar(`${r.baseCalendarId}-base`):null)??(i?n.getBaseCalendar(i):null);return!a||!r.startDate||!r.endDate?0:Ci(r.startDate,r.endDate,e,a)};function qs(t,e,n,i=null){let r=[],a=(s,l)=>{let c=n.getActivity(s);c&&c.expectedProgressBaseline!==l&&(n.setActivityField(s,"expectedProgressBaseline",l),r.push(s))},o=s=>{let l=n.getActivity(s);if(!l)return 0;if(!_v(l)){let u=Pv(l,e,n,i);return a(s,u),u}let c=0;for(let u of n.getChildrenIds(s)){let p=o(u),f=n.getActivity(u),y=typeof f?.ponderator=="number"?f.ponderator:0;c+=p*y}let d=c/100;return a(s,d),d};for(let s of t)o(s);return r}function Di(t,e,n=null){let i={getChildrenIds:a=>t.getChildren(String(a)).map(o=>String(o)),getActivity:a=>t.getActivity(a),setActivityField:(a,o,s)=>ae(t,a,o,s),getBaseCalendar:a=>t.calendarReader.getCalendar(a)},r=[];return t.forEachActivity((a,o)=>{a.parentId===null&&r.push(o)}),qs(r,e,i,n)}var zs=Ge.BASELINE;function Xa(t){return t===Ge.ACTUAL?Ge.ACTUAL:zs}var gp=t=>Math.round(t*100)/100;function Rv(t,e){return(e===Ge.BASELINE?t.expectedProgressBaseline:t.expectedProgress)??void 0}function kv(t,e){let n=gp(t),i=gp(e);return n>99.99?Mt.DONE:i>n?Mt.OVERDUE:t>0&&n>i?Mt.ADVANCEMENT:t===0&&e===0?Mt.WAITING:t>0&&n<i?Mt.DOING:Mt.WAITING}function Ue(t,e){let n=[];return t.forEachActivity((i,r)=>{let a=typeof i.progress=="number"?i.progress:0,o=kv(a,Rv(i,e));i.status!==o&&(ae(t,r,E.STATUS,o),n.push(r))}),n}function Ap(t){let e=t?.baselinePoints;return!Array.isArray(e)||e.length===0?null:e.find(n=>n.isVisibleVersion)??null}var Ip=100,Lv=t=>Math.round(t*Ip)/Ip;function Ov(t,e,n){if(n<=0)return null;let i=Ap(t)?.endDate,r=t.endDate;if(!i||!r)return null;let a=r.getTime()>i.getTime(),o=i.getTime()>r.getTime();if(!a&&!o)return 0;let s=e.calculateDuration({startDate:a?i:r,endDate:a?r:i,task:t}),l=Lv(s/n);return a?l:-l}function jn(t,e){let n=[];return t.forEachActivity((i,r)=>{let a=Ov(i,t,e);i.baselineVarianceDays!==a&&(i.baselineVarianceDays=a,n.push(String(r)))}),n}function Js(t){let e=t instanceof Date?new Date(t.getTime()):t&&typeof t=="object"&&typeof t.valueOf=="function"?new Date(t.valueOf()):new Date(t),n=(r,a)=>o=>o===void 0?e[r]():(e[a](o),i),i={__isMomentShim:!0,clone:()=>Js(e),hours:n("getUTCHours","setUTCHours"),minutes:n("getUTCMinutes","setUTCMinutes"),seconds:n("getUTCSeconds","setUTCSeconds"),milliseconds:n("getUTCMilliseconds","setUTCMilliseconds"),valueOf:()=>e.getTime(),toDate:()=>new Date(e.getTime()),getTime:()=>e.getTime()};return i}Js.isMoment=t=>!!t&&typeof t=="object"&&t.__isMomentShim===!0;var oe=Js;function bv(t){return t&&t.constructor===Date?!!(t.getFullYear&&t.getMonth&&t.getDate):!1}function Za(t){return bv(t)&&!isNaN(t.getTime())}function N(t,e,n,i){if(!Za(new Date(e)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${e}, Activity: ${JSON.stringify(i)}`);let r=e;return t.calculateEndDate({start_date:new Date(r),duration:n,unit:"hour",task:i})}function Qt(t){if(!Za(new Date(t.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:e,activityCalendar:n,direction:i,activity:r}=t;return n.$gantt.getClosestWorkTime({date:new Date(e),dir:i,unit:"hour",task:r})}var C=D;var Y=Object.freeze({FS:Ft.FINISH_TO_START,SS:Ft.START_TO_START,FF:Ft.FINISH_TO_FINISH,SF:Ft.START_TO_FINISH});function Wn(t){return Ea[String(Number(t))]??Ft.START_TO_FINISH}var Q=Object.freeze({FORWARD:"forward",BACKWARD:"backward"}),Vn=Object.freeze({GREATER:"greater",LESS:"less"}),he=Object.freeze({SOURCE:"$source"});var Nv=t=>t?t.$level===1:!1,Fv=t=>t.type===k.PROJECT,wv=t=>t.$level!==0,xv=t=>t.type===k.TASK,Mv=t=>t.type===k.TASK||t.type===k.MILESTONE,Vt={byFirstLevel:Nv,filterByParentType:Fv,avoidSubproject:wv,byTaskType:xv,byTaskTypeAndMilestone:Mv};function Sp(t){let{gantt:e,pendingParentsWithNoLinks:n,calculations:i,linkProperty:r}=t;try{let a=Uv({gantt:e,pendingParentsWithNoLinks:n});if(a.length===0)return new Set;let o=Hv({gantt:e,subprojectsWithNoLinks:a}),s=Bv({gantt:e,childrenIds:o,linkProperty:r,getArrayOfLinkedActivities:jv,calculations:i});return new Set(s.map(l=>l.id))}catch(a){throw a}}function Uv(t){let{gantt:e,pendingParentsWithNoLinks:n}=t;return e.getTaskByTime().filter(Vt.filterByParentType).filter(i=>n.has(i.id)).map(i=>i.id)}function Hv(t){let{gantt:e,subprojectsWithNoLinks:n}=t,i=new Set;for(let r of n)e.getChildren(r).filter(s=>{let l=e.getTask(s),c=Vt.byTaskTypeAndMilestone(l),d=Number(l.progress)<100;return c&&d}).forEach(s=>i.add(s));return[...i]}function Bv(t){let{gantt:e,childrenIds:n,linkProperty:i,getArrayOfLinkedActivities:r,calculations:a}=t,o=[];for(let s of n){let l=e.getTask(s),c=l[i]||[];r({gantt:e,links:c,linkDirection:i===he.SOURCE?"target":"source"}).every(p=>a.has(p))&&o.push(l)}return o}function jv(t){let{gantt:e,links:n,linkDirection:i}=t,r=[];for(let a of n){let o=e.getLink(a);if(!o){`${a}`;continue}let s=Number(o[i]);r.push(s)}return r}function vp({gantt:t,linkProperty:e,direction:n}){try{let i=Wv(t,e);if(n===Q.FORWARD)return{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:null};if(n===Q.BACKWARD)return Vv(i,t,e)}catch(i){throw console.log("Critical Path",i),i}}function Wv(t,e){return t.getTaskByTime().filter(Vt.avoidSubproject).filter(Vt.byTaskTypeAndMilestone).filter(n=>!n[e].length)}function Vv(t,e,n){let i=[],r=new Set;return t.forEach(a=>{let o=Number(a.parent),s=e.getTask(o);s&&(s[n].length>0?r.add(a.id):s.constraint_type!==C.FNLT&&i.push(a))}),{chainStartActivities:i,activitiesStartChainButChildrenOfLinkedParents:r}}function Cp({gantt:t,direction:e,linkProperty:n}){try{let i=Kv(t),r=new Set,a=new Set,o=new Set;e===Q.BACKWARD&&$v(i).forEach(d=>{r.add(d.id)});let s=Yv(i,e,n),l=Gv(i,s);return s.forEach(c=>{a.add(c.id)}),l.forEach(c=>{o.add(c.id)}),{parentsWithFullProgress:r,pendingParentsWithNoLinks:a,pendingParentsWithLinks:o}}catch(i){throw i}}function Kv(t){return t.getTaskByTime().filter(Vt.filterByParentType).filter(Vt.avoidSubproject)}function Yv(t,e,n){return t.filter(i=>{let r=i[n];if(!Array.isArray(r))return!1;let a=r.length>0,o=i.constraint_type||"",s=o!==C.FNLT;if(e===Q.FORWARD){let l=o!==C.SNET;return!a&&s&&l}else return!a&&s})}function Gv(t,e){let n=new Set(e.map(i=>i.id));return t.filter(i=>!n.has(i.id))}function $v(t){return t.filter(e=>{let n=Number(e.progress);return Number.isNaN(n)?!1:n===100})}function Dp({pendingParentsWithLinks:t,gantt:e,direction:n}){try{let i=new Set;return t.forEach(r=>{let a=e.getTask(r),o=qv(n),s=zv(n),l=a[o];if(!Array.isArray(l))return;Jv(e,l,s).forEach(d=>{i.add(d)})}),i}catch(i){throw i}}function qv(t){return t===Q.FORWARD?he.SOURCE:"$target"}function zv(t){return t===Q.FORWARD?"target":"source"}function Jv(t,e,n){return e.map(i=>{let a=t.getLink(i)[n];return Number(a)})}var Ar={identifySecondLevelActivities:Sp,identifyInitialActivities:vp,identifyParentsWithAndWithoutLinks:Cp,identifyForbiddenActivities:Dp};function Qa(t){return t.length?t.reduce((e,n)=>n.ef>e.ef?n:e):!1}function Xs({linkType:t,lag:e,predecessorTime:n,activityCalendar:i,activity:r}){return t===Y.FS&&e===0?Qt({predecessorTime:n,activityCalendar:i,direction:"future",activity:r}):Ir(n,t,i,r)}function Tp({duration:t,constraintDate:e,activityCalendar:n,activity:i}){let r=new Date(e);return{es:N(n,r,t,i),ef:r}}function _p({duration:t,constraintDate:e,activityCalendar:n,activity:i}){let r=new Date(e),a=N(n,r,t,i);return{es:r,ef:a}}function Ir(t,e,n,i){if(![Y.FS,Y.SS,Y.FF].includes(e))return t;let a=[Y.FS,Y.SS].includes(e)?"future":"past";return Qt({dateBaseToCalculate:t,activityCalendar:n,direction:a,activity:i})}var Zs=class{constructor(e,n,i,r){if(this.linkedActivitiesData=e,this.activity=n,this.gantt=i,this.linkCandidates=r,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 e=this.calculateLinks(),n=Qa(e),i=this.activity.constraint_type;return i===C.SNET?this.handleSNETConstraint(n):i===C.FNLT?this.handleFNLTConstraint(n):n}calculateLinks(){let e=[];for(let n of this.linkedActivitiesData){let i=n.linkType,r=Wn(i),a=n.linkLag,o=n.es,s=n.ef,l=null;if(r===Y.SS)l=this.calculateSSLink({lag:a,predecessorEs:o});else if(r===Y.FF)l=this.calculateFFLink({lag:a,predecessorEf:s});else if(r===Y.FS)l=this.calculateFSLink({lag:a,predecessorEf:s});else if(r===Y.SF)l=this.calculateSFLink({lag:a,predecessorEs:o,predecessorEf:s});else continue;l&&(this.linkCandidates?.set(n.linkId,{targetId:String(this.activity.id),...l}),e.push(l))}return e}handleSNETConstraint(e){let n=_p({duration:this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return e&&e.ef>n.ef?e:n}handleFNLTConstraint(e){let n=Tp({duration:-this.activity.duration,constraintDate:this.activity.constraint_date,activityCalendar:this.activityCalendar,activity:this.activity});return e?e.ef>n.ef?n:e:n}calculateSSLink({lag:e,predecessorEs:n}){let i=Xs({linkType:Y.SS,lag:e,predecessorTime:n,activityCalendar:this.activityCalendar,activity:this.activity}),r=N(this.activityCalendar,i,e,this.activity);e>0&&(r=Ir(r,Y.SS,this.activityCalendar,this.activity));let a=N(this.activityCalendar,r,this.activity.duration,this.activity);return{es:r,ef:a}}calculateFFLink({lag:e,predecessorEf:n}){let i=Xs({linkType:Y.FF,lag:e,predecessorTime:n,activityCalendar:this.activityCalendar,activity:this.activity}),r=N(this.activityCalendar,i,e,this.activity),a=N(this.activityCalendar,r,-this.activity.duration,this.activity);return e>0&&(a=Ir(a,Y.FF,this.activityCalendar,this.activity)),{es:a,ef:r}}calculateFSLink({lag:e,predecessorEf:n}){let i=n;e===0&&(i=Qt({dateBaseToCalculate:n,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let r=N(this.activityCalendar,i,e,this.activity),a=N(this.activityCalendar,r,this.activity.duration,this.activity);return{es:r,ef:a}}calculateSFLink({lag:e,predecessorEs:n}){let i=N(this.activityCalendar,n,e,this.activity),r=N(this.activityCalendar,i,-this.activity.duration,this.activity);return e>0&&(r=Ir(r,Y.SF,this.activityCalendar,this.activity)),{es:r,ef:i}}},Ep=Zs;var Qs=class{constructor(e){this.linkedActivitiesData=e.linksWithActivityData,this.activity=e.activity,this.gantt=e.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 e=[];for(let n of this.linkedActivitiesData){let i=Wn(n.linkType);if(n.type===k.TASK&&Number(n.progress)>0||n.type===k.PROJECT&&Number(n.progress)===100)continue;let r=n.linkLag,a=n.ls,o=n.lf;if(i===Y.SS){let s={lag:r,workTime:a,lsDataCalculation:-r,lfDataCalculation:this.activity.duration},{ls:l,lf:c}=this.calculateSSLink(s);e.push({ls:l,lf:c})}if(i===Y.FF){let s={lag:r,workTime:o,lsDataCalculation:-this.activity.duration,lfDataCalculation:-r},{ls:l,lf:c}=this.calculateFFLink(s);e.push({ls:l,lf:c})}if(i===Y.FS){let s={lag:r,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-r},{ls:l,lf:c}=this.calculateFsLink(s);e.push({ls:l,lf:c})}if(i===Y.SF){let s={lag:r,workTime:o,lsDataCalculation:-r,lfDataCalculation:this.activity.duration},{ls:l,lf:c}=this.calculateSFLink(s);e.push({ls:l,lf:c})}}if(this.activity.constraint_type===C.FNLT){let n=this.getMinLfFromLinks(e),i=this.calculateSfRestrictionDates();return n?this.getMinLfFromLinks([i,n]):i}else{let n=this.getMinLfFromLinks(e);if(n===!1){let i=this.gantt.getSubtaskDates();return{ls:N(this.activityCalendar,i.end_date,-this.activity.duration,this.activity),lf:i.end_date}}return n}}calculateFFLink({lag:e,workTime:n,lsDataCalculation:i,lfDataCalculation:r}){let a=null,o=null;if(e===0)return a=N(this.activityCalendar,n,r,this.activity),o=N(this.activityCalendar,a,i,this.activity),{ls:o,lf:a};let s=n;return e>0&&(s=this.getLastWorkingHour(s,this.activityCalendar,q.PAST)),a=N(this.activityCalendar,s,r,this.activity),o=N(this.activityCalendar,a,i,this.activity),{ls:o,lf:a}}calculateFsLink({lag:e,workTime:n,lsDataCalculation:i,lfDataCalculation:r,isMilestone:a=!1}){let o=null,s=null;if(e===0){let c=this.getLastWorkingHour(n,this.activityCalendar,q.PAST);return o=N(this.activityCalendar,c,r,this.activity),o=this.getLastWorkingHour(o,this.activityCalendar,q.PAST),s=N(this.activityCalendar,o,i,this.activity),{ls:s,lf:o}}let l=n;return a||(l=this.getLastWorkingHour(n,this.activityCalendar)),o=N(this.activityCalendar,l,r,this.activity),s=N(this.activityCalendar,o,i,this.activity),a||(o=this.getLastWorkingHour(o,this.activityCalendar,q.PAST)),{ls:s,lf:o}}calculateSFLink({lag:e,workTime:n,lsDataCalculation:i,lfDataCalculation:r}){let a=null,o=null,s=n;return o=N(this.activityCalendar,s,i,this.activity),a=N(this.activityCalendar,o,r,this.activity),{ls:o,lf:a}}calculateSSLink({lag:e,workTime:n,lsDataCalculation:i,lfDataCalculation:r,isMilestone:a=!1}){let o=null,s=null;if(e===0)return s=N(this.activityCalendar,n,i,this.activity),o=N(this.activityCalendar,s,r,this.activity),{ls:s,lf:o};let l=n;return e<0&&!a&&(l=this.getLastWorkingHour(l,this.activityCalendar,"future")),s=N(this.activityCalendar,l,i,this.activity),o=N(this.activityCalendar,s,r,this.activity),{ls:s,lf:o}}getMinLfFromLinks(e=[]){return e.length?e.reduce((n,i)=>i.lf<n.lf?i:n):!1}calculateSfRestrictionDates(){let e=this.activity.constraint_date,n=this.activity.duration;return{ls:N(this.activityCalendar,e,-n,this.activity),lf:e}}getLastWorkingHour(e,n,i=q.PAST){let r=e instanceof Date?e:new Date(e),a=oe(r).clone();return this.isActivityInInitHour(n,r)&&i===q.PAST&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),Qt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:n,activity:this.activity})}isActivityInInitHour(e,n){let i=n instanceof Date?n:new Date(n),a=e.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),oe.isMoment(n)?n.hours()===o:i.getUTCHours()===o)}},Pp=Qs;function Rp(t){let{parent:e,linkProperty:n,linkDirection:i,calculations:r,gantt:a,direction:o,linkCandidates:s}=t,l=e[n],c=Xv(e),d=null;if(o===Q.FORWARD){let u=Zv(l,i,r,a);d=new Ep(u,e,a,s),d=d.calculate()}else{let u=Qv(l,i,r,a);d=new Pp({linksWithActivityData:u,activity:e,parentData:c,gantt:a}).calculate()}return d}function Xv(t){return{duration:t.duration,calendarId:t.calendar_id}}function Zv(t,e,n,i){return t.length===0?[]:t.map(r=>{let a=i.getLink(r);if(!a)return console.warn(`Link not found: ${r}`),null;let o=Number(a[e]),s=n.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 Qv(t,e,n,i){return t.length===0?[]:t.map(r=>{let a=i.getLink(r);if(!a)return console.warn(`Link not found: ${r}`),null;let o=Number(a[e]),s=n.get(o);if(!s)return null;let l=i.getTask(o);return l?{ls:s.ls,lf:s.lf,linkLag:a.lag||0,linkType:a.type,progress:l.progress,type:l.type}:null}).filter(Boolean)}function Op(t){let{activityData:e,calculations:n,singleParents:i,direction:r}=t;if(tC(e.id,n))return null;let a=eC(e.id,i),o=nC(a,n);return o.length===0?null:iC(o,r)}function tC(t,e){return e.has(t)}function eC(t,e){let n=e.get(t);return n?n.childrens:[]}function nC(t,e){return t.filter(n=>e.has(n)).map(n=>e.get(n))}function iC(t,e){if(e===Q.FORWARD){let n=kp(t,"es"),i=Lp(t,"ef");return{es:n,ef:i}}else{let n=kp(t,"ls"),i=Lp(t,"lf");return{ls:n,lf:i}}}function kp(t,e){return t.reduce((n,i)=>i[e]<n[e]?i:n)[e]}function Lp(t,e){return t.reduce((n,i)=>i[e]>n[e]?i:n)[e]}var tl={parentWithLinks:Rp,parentWithNoLinks:Op};var el=class{constructor(e){this.activity=e.activity,this.direction=e.direction,this.linkProperty=e.direction===Q.FORWARD?"$target":he.SOURCE,this.linkDirection=e.direction===Q.FORWARD?"source":"target",this.calculationsOfParentThatImpactChildrens=e.calculationsOfParentThatImpactChildrens,this.calculations=e.calculations,this.calculationOfParentsFromLinks=e.calculationOfParentsFromLinks,this.singleParents=e.singleParents,this.parentCalculationFromChildren=e.parentCalculationFromChildren,this.linkCandidates=e.linkCandidates,this.gantt=e.gantt}handleParentWithLinks(){try{let e=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction===Q.BACKWARD){let i=[C.FNLT];if(this.shouldCalculateParentWithLinksBackward(i)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(i)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(e)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction===Q.FORWARD&&this.setDatesToParentsWithLinks(),this.direction===Q.BACKWARD&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(e){throw e}}shouldCalculateParentWithLinksBackward(e){let n=e.includes(this.activity.constraint_type),i=!this.calculationOfParentsFromLinks.has(this.activity.id);return n&&i}calculateAndStoreParentWithLinks(e){let n=tl.parentWithLinks({parent:e,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});this.calculationsOfParentThatImpactChildrens.set(e.id,n),this.calculationOfParentsFromLinks.add(e.id)}areAllLinksCalculated(e){return e.every(n=>this.calculations.has(n))}shouldSetDatesToParentsWithLinks(e){let n=e.includes(this.activity.constraint_type),i=this.calculationOfParentsFromLinks.has(this.activity.id);return n&&i}handleParentWithNoLinks(){let e=tl.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});e&&this.calculations.set(this.activity.id,e)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let e=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(o=>e.includes(o[0])).map(o=>o[1]),{minEs:r,maxEf:a}=i.reduce((o,{es:s,ef:l})=>({minEs:new Date(Math.min(o.minEs.getTime(),new Date(s).getTime())),maxEf:new Date(Math.max(o.maxEf.getTime(),new Date(l).getTime()))}),{minEs:new Date(i[0].es),maxEf:new Date(i[0].ef)});this.calculations.set(this.activity.id,{es:r,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 e=this.singleParents.get(this.activity.id)?.childrens,i=Array.from(this.calculations).filter(o=>e.includes(o[0])).map(o=>o[1]),{minLs:r,maxLf:a}=i.reduce((o,{ls:s,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(s).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(this.activity.id,{ls:r,lf:a})}getArrayOfIdOfLinkedActivities(e,n=!1){return e.map(i=>{let a=this.gantt.getLink(i)[n||this.linkDirection];return Number(a)})}},bp=el;var nl=class{constructor({gantt:e,linkProperty:n}){this.gantt=e,this.linkProperty=n,this.structureOfParents=new Map,this.singleParents=new Map}identifyThirdLevelActivities(){try{let e=this.getFirstLevelParents();for(let n of e){let i=this.processEachActivity(n),{activitiesByLevel:r}=i,a=this.getAllLevels(r),o=this.getDeepestLevel(a),s=this.createResult(n,i,o,a);this.structureOfParents.set(n.id,s)}return{structureOfParents:this.structureOfParents,singleParents:this.singleParents}}catch(e){throw e}}getFirstLevelParents(){return this.gantt.getTaskByTime().filter(Vt.byFirstLevel).filter(Vt.filterByParentType)}processEachActivity(e){let n=new Set,i=new Set,r=new Map;return this.initializeParent(e),this.gantt.eachTask(a=>{this.processActivity(a,n,i,r)},e.id),{parentsIds:n,allTasks:i,activitiesByLevel:r}}initializeParent(e){let n=Number(e.id),i=!!e[this.linkProperty]?.length,r=e.$level;this.singleParents.set(n,{level:r,hasLink:i,childrens:[]})}processActivity(e,n,i,r){let a=Number(e.id),o=Number(e.parent);i.add(a),this.isProjectActivity(e)&&this.addParentInfo(e,n);let l=this.doesParentExist(o);o!=null&&l&&this.addChildToParent(o,a),this.addActivityToLevel(e,r)}isProjectActivity(e){return e.type===k.PROJECT}hasLink(e){return!!e[this.linkProperty]?.length}addParentInfo(e,n){let i=Number(e.id),r=e.$level,a=this.hasLink(e),o={level:r,hasLink:a,childrens:[]};n.add(i),this.singleParents.set(i,o)}doesParentExist(e){return this.singleParents.has(e)}addChildToParent(e,n){this.singleParents.get(e).childrens.push(n)}addActivityToLevel(e,n){let i=e.$level,r=Number(e.parent);n.has(i)||n.set(i,new Map);let a=n.get(i);a.has(r)||a.set(r,[]),a.get(r).push({id:Number(e.id),isParent:this.isProjectActivity(e),calculated:!1})}getAllLevels(e){return new Set(e.keys())}getDeepestLevel(e){return e.size===0?0:Math.max(...e)}createResult(e,n,i,r){let{activitiesByLevel:a,parentsIds:o,allTasks:s}=n;return{parent:e.id,isALinkedParent:this.hasLink(e),levels:r,allParentChildrens:o,allChildrens:s,childrensByLevel:a,currentResolutionLevel:i,canBeCalculated:!1}}},Np=nl;var il=class{constructor(e,n){this.direction=n,this.gantt=e,this.linkProperty=this.direction===Q.FORWARD?"$target":he.SOURCE,this.linkDirection=this.direction===Q.FORWARD?"source":"target",this.projectDates=e.getSubtaskDates()}tryToCalculateLastLevelChildrens(){this.structureOfParents.forEach(e=>{let{currentResolutionLevel:n,childrensByLevel:i,isALinkedParent:r}=e;if(r)return;let a=i.get(n);for(let[o,s]of a)if(s.filter(c=>!this.calculations.has(c.id)).length===0){let c=this.gantt.getTask(o);this.calculateParentWithNoLinks(c,s);return}})}initActivitiesWaitingForCalculation(){try{this.gantt.getTaskByTime().filter(Vt.avoidSubproject).forEach(e=>{this.activitiesWaitingForCalculation.add(e.id)})}catch(e){throw e}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:e,pendingParentsWithNoLinks:n,pendingParentsWithLinks:i}=Ar.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=e,this.pendingParentsWithNoLinks=n,this.pendingParentsWithLinks=i}catch(e){throw e}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Ar.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(e){throw e}}getArrayOfIdOfLinkedActivities(e,n=!1){return e.map(i=>{let a=this.gantt.getLink(i)[n||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:e,singleParents:n}=new Np({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=e,this.singleParents=n}catch(e){throw e}}processEachActivity(e){let n=new Set,i=new Set,r=new Map,a=new Map;return this.singleParents.set(Number(e.id),{level:e.$level,hasLink:!!e[this.linkProperty].length,childrens:[]}),new Promise((o,s)=>{this.gantt.eachTask(function(l){let c=Number(l.parent);if(i.add(l.id),l.type===k.PROJECT){let u={level:l.$level,hasLink:!!l[this.linkProperty].length,childrens:[]};n.add(l.id),this.singleParents.set(Number(l.id),u)}c&&this.singleParents.has(c)&&this.singleParents.get(c).childrens.push(l.id),r.has(l.$level)||r.set(l.$level,new Map);let d=r.get(l.$level);d.has(Number(l.parent))||d.set(Number(l.parent),[]),d.get(Number(l.parent)).push({id:l.id,isParent:l.type===k.PROJECT,calculated:!1})}.bind(this),e.id),o({parentsIds:n,allTasks:i,activitiesByLevel:r,singleParents:a})})}identifySecondLevelActivities(){try{let e=Ar.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...e])}catch(e){throw e}}identifyInitialActivities(){try{let{chainStartActivities:e,activitiesStartChainButChildrenOfLinkedParents:n}=Ar.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=e,n&&(this.activitiesStartChainButChildrenOfLinkedParents=n)}catch(e){throw new Error("Error in identifyInitialActivities",{cause:e})}}calculateSecondLevelActivities(){try{this.direction===Q.FORWARD?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(e){throw e}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(e=>{if(!e||e.progress>100||e.type===k.PROJECT)return;let n=this.calculateStartAndFinishOfChainOrigin(e,this.direction);if(this.direction===Q.FORWARD){let{es:i,ef:r}=n;this.calculations.set(e.id,{es:i,ef:r,text:e.text}),this.activitiesWaitingForCalculation.delete(e.id)}else{let{ls:i,lf:r}=n;this.calculations.set(e.id,{ls:i,lf:r,text:e.text}),this.activitiesWaitingForCalculation.delete(e.id)}})}catch(e){throw e}}buildDependencyGraph(e){let n=new Map,i=new Set(this.calculations.keys()),r=new Map;return e.forEach(a=>{a&&r.set(a.id,a)}),r.forEach((a,o)=>{if(i.has(o))return;let s=[];(a[this.linkDirection]||[]).forEach(c=>{let d=this.gantt.getLink(c);if(d){let u=Number(d[this.linkProperty]);s.push(u)}}),s=s.filter(c=>r.has(c)||i.has(c)),n.set(o,s)}),{graph:n,activityMap:r,calculatedActivities:i}}topologicalSort(e,n){let i=new Set,r=new Set,a=[],o=s=>{if(r.has(s))throw new Error("Cyclical dependency detected",{cause:{nodeId:s}});if(!i.has(s)&&!n.has(s)){r.add(s);let l=e.get(s)||[];for(let c of l)o(c);r.delete(s),i.add(s),a.push(s)}};for(let s of e.keys())!i.has(s)&&!n.has(s)&&o(s);return a.reverse()}calculateStartAndFinishOfChainOrigin(e=null,n=null){try{let i=e,r=Number(i.progress);r==="0.00"&&(r=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((n||this.direction)===Q.FORWARD){let s=i.start_date,l=i.end_date;return{es:s,ef:l}}else{if(r>=100)return{ls:oe(i.start_date).clone(),lf:oe(i.end_date).clone()};if(r===0)return this.calculateBackwardWhenZeroProgress(i,a);if(r<100&&r>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(i,a)}}catch(i){throw i}}calculateBackwardWhenZeroProgress(e,n){let i=oe(e.start_date).clone(),r=oe(e.end_date).clone(),a=e.duration,o=[C.ASAP,C.ALAP,C.SNET,C.FNET],s=e.constraint_type||C.ASAP;if(o.includes(s))r=this.projectDates.end_date,i=N(n,r,-a,e);else{let l=[C.SNLT,C.MSO],c=[C.FNLT,C.MFO];l.includes(s)&&(i=e.constraint_date,r=N(n,i,a,e)),c.includes(s)&&(r=e.constraint_date,i=N(n,r,-a,e))}return{ls:i,lf:r}}calculateWhenProgressIsBetweenZeroAndOneHundred(e){let n=e.start_date,i=null,r=e.constraint_type||C.ASAP,a=this.projectDates.end_date,o=[C.ASAP,C.ALAP,C.SNET,C.FNET],s=[C.SNLT,C.FNLT];if(o.includes(r))i=Math.max(e.end_date,a);else if(r===C.MSO)i=e.end_date;else if(r===C.MFO||s.includes(r)){let l=Math.min(a,e.constraint_date);i=Math.max(l,e.end_date)}return{ls:n,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 r=i.type===k.PROJECT;this.setDatesForActivityWithFullProgress(i),this.activitiesWaitingForCalculation.delete(i.id),r&&this.pendingParentsWithLinks.has(i.id)&&(this.parentCalculationFromChildren.add(i.id),this.calculationsOfParentThatImpactChildrens.set(i.id,{[this.direction===Q.FORWARD?"es":"ls"]:i.start_date,[this.direction===Q.FORWARD?"ef":"lf"]:i.end_date}),this.calculationOfParentsFromLinks.add(i.id))})}catch(e){throw e}}doCalculationForParentType(e){let n=new bp({activity:e,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(e.id)?n.handleParentWithLinks():n.handleParentWithNoLinks()}},hn=il;function rC(t,e,n){let i={es:null,ef:null};if(!t)return i;if([C.SNET,C.SNLT].includes(e)){let r=new Date(t.constraint_date);i.es=r,i.ef=N(n,r,t.duration,t)}else if([C.FNLT,C.FNET].includes(e)){let r=new Date(t.constraint_date);i.es=N(n,r,-t.duration,t),i.ef=r}else if(e===C.MSO){let r=new Date(t.constraint_date);i.es=r,i.ef=N(n,r,t.duration,t)}else if(e===C.MFO){let r=new Date(t.constraint_date);i.es=N(n,r,-t.duration,t),i.ef=r}return i}var to=rC;var rl=class{constructor(e){this.referenceActivity=e.activity,this.activityToCalculate=null,this.links=e.links,this.calculatedActivities=e.calculatedActivitiesMap,this.alapMap=e.calculatedAlapsMap,this.parentsWithLinks=e.parentsWithLinks,this.parentsCalculations=e.parentsCalculations,this.gantt=e.ganttInstance,this.linkCandidates=e.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(e){return this.alapMap.has(e)?this.alapMap.get(Number(e)):this.calculatedActivities.get(Number(e))}calculateSucessorTimes(e,n,i=0,r,a=Y.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=e,l=null,c=null,d=this.referenceActivity.type===k.MILESTONE;return d||(a===Y.FS&&r===0?s=Qt({dateBaseToCalculate:s,activityCalendar:o,direction:"future",activity:this.referenceActivity}):s=this.mutateTheDateToFutureOrPastInBaseRestriction(e,a,o)),[Y.FF,Y.SF].includes(a)?(c=N(o,s,i,this.referenceActivity),l=N(o,c,n,this.referenceActivity),!d&&r>0&&(l=this.mutateTheDateToFutureOrPastInBaseRestriction(l,a,o))):(l=N(o,s,n,this.referenceActivity),!d&&r>0&&(l=this.mutateTheDateToFutureOrPastInBaseRestriction(l,a,o)),c=N(o,l,i,this.referenceActivity)),{es:l,ef:c}}calculateSS(e){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(e.source)),i=e.lag||0,a=this.referenceActivity.duration,o=e.lag||0;return this.calculateSucessorTimes(n.es,i,a,o,Y.SS)}calculateFF(e){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(e.source)),r=-this.referenceActivity.duration,a=e.lag||0,o=e.lag||0;return this.calculateSucessorTimes(n.ef,r,a,o,Y.FF)}calculateFS(e){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(e.source)),i=e.lag||0,a=this.referenceActivity.duration,o=e.lag||0;return this.calculateSucessorTimes(n.ef,i,a,o,Y.FS)}calculateSF(e){let n=this.getEsAndEfFromPreviousCalculatedActivities(Number(e.source)),r=-this.referenceActivity.duration,a=e.lag||0,o=e.lag||0;return this.calculateSucessorTimes(n.es,r,a,o,Y.SF)}mutateTheDateToFutureOrPastInBaseRestriction(e,n,i){if(![Y.FS,Y.SS,Y.FF].includes(n))return e;let a=[Y.FS,Y.SS].includes(n)?"future":q.PAST;return Qt({dateBaseToCalculate:e,activityCalendar:i,direction:a,activity:this.referenceActivity})}},Fp=rl;var Sr=class extends Fp{constructor(e){super(e)}calculate(){if(this.links.length===0)return new hn(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let e=this.links.map(i=>{let r=this.gantt.getLink(i);if(!r)throw new Error("Link data not found",{cause:{linkId:i}});let a=this.calculateLink(r);return this.linkCandidates?.set(String(r.id),{targetId:String(this.referenceActivity.id),...a}),a}),n=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(n)){let i=this.gantt.getCalendar(this.referenceActivity.calendar_id),r=this.parentsCalculations.get(n).es,a=N(i,r,this.referenceActivity.duration,this.referenceActivity);e.push({es:r,ef:a})}return Qa(e)}calculateLink(e){return{0:()=>this.calculateFS(e),1:()=>this.calculateSS(e),2:()=>this.calculateFF(e),3:()=>this.calculateSF(e)}[e.type]()}};var al=class{constructor(e){this.gantt=e.gantt,this.direction=e.direction,this.pendingParentsWithNoLinks=e.pendingParentsWithNoLinks,this.pendingParentsWithLinks=e.pendingParentsWithLinks,this.calculationOfParentsFromLinks=e.calculationOfParentsFromLinks,this.singleParents=e.singleParents,this.calculations=e.calculations,this.activitiesStartChainButChildrenOfLinkedParents=e.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=e.linkProperty,this.linkDirection=e.linkDirection}checkActivitiesThatNowCanBeCalculated(e){let n=new Set,i=new Set(e);for(let r of e){let a=this.gantt.getTask(r);a.type===k.PROJECT?this.handleProjectActivity(r,a,n,i):this.handleNonProjectActivity(r,a,n,i)}return{activitiesThatCanBeCalculated:n,pendingActivities:i}}handleProjectActivity(e,n,i,r){let a=this.pendingParentsWithNoLinks.has(e),o=this.pendingParentsWithLinks.has(e),s=this.calculationOfParentsFromLinks.has(e);if(a){let l=this.singleParents.get(e)?.childrens;if(!l)return;l.every(d=>this.calculations.has(d))&&(i.add(e),r.delete(e));return}if(o&&s){let l=this.singleParents.get(e)?.childrens;if(!l)return;l.every(d=>this.calculations.has(d))&&(i.add(e),r.delete(e));return}o&&!s&&this.canCalculateParentActivity(n)&&(i.add(e),r.delete(e))}canCalculateParentActivity(e){let n=(e[this.linkProperty]||[]).length===0,i=e.constraint_type;return(this.direction===Q.FORWARD?i===C.FNLT||i===C.SNLT:i===C.FNLT)&&n?!0:this.getArrayOfLinkedActivities(e[this.linkProperty]).every(o=>this.calculations.has(o))}handleNonProjectActivity(e,n,i,r){let a=Number(n.parent),o=this.pendingParentsWithLinks.has(a),s=this.calculationOfParentsFromLinks.has(a);if(o&&!s||this.direction===Q.BACKWARD&&this.activitiesStartChainButChildrenOfLinkedParents.has(e)&&!s)return;if(n.$target.length===0&&n[he.SOURCE].length===0){i.add(e),r.delete(e);return}let l=this.getLinkedActivities(n[this.linkProperty]),c=l.every(d=>this.calculations.has(d.id));if(this.direction===Q.BACKWARD&&(l.length===0||c)&&s){i.add(e),r.delete(e);return}c&&(i.add(e),r.delete(e))}getLinkedActivities(e){if(!Array.isArray(e))return[];let n=[];for(let i of e){let r=this.gantt.getLink(i);if(!r)continue;let a=r[this.linkDirection],o=this.gantt.getTask(a);o&&n.push(o)}return n}getArrayOfLinkedActivities(e){if(!Array.isArray(e))return[];let n=[];for(let i of e){let r=this.gantt.getLink(i);r&&n.push(Number(r[this.linkDirection]))}return n}},eo=al;var ol=(t,e)=>()=>e()===t;var sl=t=>!t?.fullyParsed;var aC=16,Kn=async t=>performance.now()-t>aC?(await mt(),performance.now()):t;var vr=async({pending:t,activityCalculator:e,calculateFn:n,shouldKeepPending:i,isCalculated:r,onActivityProcessed:a,isCurrent:o})=>{let s=new Set(t),l=performance.now();for(;s.size>0;){if(!o())return;l=await Kn(l);let{activitiesThatCanBeCalculated:c,pendingActivities:d}=e.checkActivitiesThatNowCanBeCalculated(s);if(c.size===0)break;for(let u of c){if(!o())return;l=await Kn(l),n([u])}for(let u of c){if(!o())return;i(u)&&d.add(u),a(u),r(u)&&d.delete(u)}s=d}};var ll=class extends hn{constructor(e){super(e,Q.FORWARD),this.gantt=e,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(e){this.identifyParentsWithAndWithoutLinks(),e()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),e()&&(this.initializeActivitiesWithFullProgress(),e()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),e()&&(this.identifySecondLevelActivities(),e()&&(this.identifyThirdLevelActivities(),e()&&await this.iterativeCalculateEfAndEs(e))))))}async iterativeCalculateEfAndEs(e){let n=new eo({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 vr({pending:this.activitiesWaitingForCalculation,activityCalculator:n,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:e})}calculateStartAndFinishTimes(e){e.forEach(n=>{let i=this.gantt.getTask(n);if(i.type===k.PROJECT)return this.doCalculationForParentType(i);if(!i)throw new Error("Error trying to get activity",{cause:{activityId:n}});let r=i.$target,a=i.constraint_type||C.ASAP,o=[C.SNET,C.SNLT,C.FNLT,C.FNET],s=[C.ASAP,C.ALAP,C.SNET,C.FNET,C.SNLT,C.FNLT],l=this.gantt.getCalendar(i.calendar_id);if(!l)throw new Error(`Error trying to get calendar with id: ${i.calendar_id}`);let c=Number(i.progress),d=null,u=null,p=null;if(c===100){this.setDatesForActivityWithFullProgress(i);return}c>0&&s.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(i),p=new Sr({links:r,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===C.ASAP&&this.totalFloatForAsap.set(n,{es:p.es,ef:p.ef,text:i.text})):{es:d,ef:u}=new Sr({links:r,activity:i,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===C.ALAP&&this.alapMap.set(n,{es:i.start_date,ef:i.end_date,text:i.text});let f=to(i,a,l);if(o.includes(a)&&(this.constraintsMap.set(n,f),this.totalFloatSnltFnlt.set(n,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,f,{es:d,ef:u})),[C.MSO,C.MFO].includes(a))if(this.totalFloatForMsoMfo.set(n,{es:d,ef:u}),this.constraintsMap.set(n,f),i.progress===0)d=f.es,u=f.ef;else{let y=i.end_date;a===C.MFO&&(y=Math.max(f.ef,i.end_date)),d=i.start_date,u=y}this.calculations.set(n,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(n)})}getTheGreatesDateBetweenRestrictionAndEsEf(e,n,i=Vn.GREATER){if(i===Vn.GREATER)return n.ef>e.ef?n:e;if(i===Vn.LESS)return n.ef<e.ef?n:e}setDatesForActivityWithFullProgress(e){this.calculations.set(e.id,{es:e.start_date,ef:e.end_date})}getDatesForActivityWithZeroProgress(e){return{es:e.start_date,ef:e.end_date}}recalculateInBaseConstraint(e,n,i){let r=[C.SNET,C.FNET].includes(e)?Vn.GREATER:Vn.LESS,{es:a,ef:o}=this.getTheGreatesDateBetweenRestrictionAndEsEf(n,i,r);return{es:a,ef:o}}cleanAllActivityParentsFromLinks(e){return e.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Error trying to get link",{cause:{linkId:n}});let r=i.source,a=i.target;if(!(!this.gantt.getTask(r)||this.gantt.getTask(r)?.type===k.PROJECT)&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type===k.PROJECT))return n}).filter(Boolean)}},wp=ll;var cl=class{constructor(e){this.activity=e.activity,this.links=e.links,this.calculatedActivities=e.calculatedActivitiesMap,this.forwardPathCalculations=e.calculatedForwardActivitiesMap,this.gantt=e.ganttInstance}getForwardOrBackwardCalculations(e,n=null){return n===C.ALAP?this.forwardPathCalculations.get(e):this.calculatedActivities.get(e)}calculateSuccessorTimes(e,n,i=0,r,a=Y.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=e,l=this.activity.type===k.MILESTONE;if(l&&r===0){let d=N(o,s,n,this.activity),u=N(o,d,i,this.activity);return{ls:d,lf:u}}let c={lag:r,workTime:s,activityCalendar:o,lsDataCalculation:n,lfDataCalculation:i,isMilestone:l};if(a===Y.FS){let{ls:d,lf:u}=this.calculateFsLink(c);return{ls:d,lf:u}}if(a===Y.FF){let{ls:d,lf:u}=this.calculateFFLink(c);return{ls:d,lf:u}}if(a===Y.SS){let{ls:d,lf:u}=this.calculateSSlink(c);return{ls:d,lf:u}}if(a===Y.SF){let{ls:d,lf:u}=this.calculateSFLink(c);return{ls:d,lf:u}}}calculateSS(e,n=!1){let i=this.getValueForSS(e,n),r=-e.lag||0,a=this.activity.duration,o=e.lag;return this.calculateSuccessorTimes(i,r,a,o,Y.SS)}calculateFF(e,n){let i=this.getForwardOrBackwardCalculations(Number(e.target)),r=n===C.ALAP?"ef":"lf",a=i[r],o=-this.activity.duration,s=-e.lag||0,l=e.lag;return this.calculateSuccessorTimes(a,o,s,l,Y.FF)}calculateFS(e,n){let i="ls";i=n===C.ALAP?"es":"ls";let r=this.getForwardOrBackwardCalculations(Number(e.target),n),a=-this.activity.duration,o=e.lag||0,s=-e.lag||0;return this.calculateSuccessorTimes(r[i],a,s,o,Y.FS)}calculateSF(e,n=!1){let i=n?this.getEarlyStartFromForwardPath(Number(e.target)).ef:this.getForwardOrBackwardCalculations(Number(e.target)).lf,r=-e.lag||0,a=this.activity.duration,o=e.lag;return this.calculateSuccessorTimes(i,r,a,o,Y.SF)}getEarlyStartFromForwardPath(e){return this.forwardPathCalculations.get(e)}getValueForSS(e,n){return n?this.getEarlyStartFromForwardPath(Number(e.target)).es:this.getForwardOrBackwardCalculations(Number(e.target))["ls"]}calculateDate(e,n,i){let r=oe(n).clone();return N(e,new Date(r),i,this.activity)}getLastWorkingHour(e,n,i=q.PAST){let r=e instanceof Date?e:new Date(e),a=oe(r).clone();return this.isActivityInInitHour(n,r)&&i===q.PAST&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),Qt({dateBaseToCalculate:new Date(a),direction:i,activityCalendar:n,activity:this.activity})}isActivityInInitHour(e,n){let i=n instanceof Date?n:new Date(n),a=e.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),oe.isMoment(n)?n.hours()===o:i.getUTCHours()===o)}calculateFsLink({lag:e,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:a,isMilestone:o=!1}){let s=null,l=null;if(e===0){let d=this.getLastWorkingHour(n,i,q.PAST);return s=N(i,d,a,this.activity),s=this.getLastWorkingHour(s,i,q.PAST),l=N(i,s,r,this.activity),{ls:l,lf:s}}let c=n;return o||(c=this.getLastWorkingHour(n,i)),s=N(i,c,a,this.activity),l=N(i,s,r,this.activity),o||(s=this.getLastWorkingHour(s,i,q.PAST,!0)),{ls:l,lf:s}}calculateFFLink({lag:e,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:a}){let o=null,s=null;if(e===0)return o=N(i,n,a,this.activity),s=N(i,o,r,this.activity),{ls:s,lf:o};let l=n;return e>0&&(l=this.getLastWorkingHour(l,i,q.PAST)),o=N(i,l,a,this.activity),s=N(i,o,r,this.activity),{ls:s,lf:o}}calculateSSlink({lag:e,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:a,isMilestone:o=!1}){let s=null,l=null;if(e===0)return l=N(i,n,r,this.activity),s=N(i,l,a,this.activity),{ls:l,lf:s};let c=n;return e<0&&!o&&(c=this.getLastWorkingHour(c,i,"future")),l=N(i,c,r,this.activity),s=N(i,l,a,this.activity),{ls:l,lf:s}}calculateSFLink({lag:e,workTime:n,activityCalendar:i,lsDataCalculation:r,lfDataCalculation:a}){let o=null,s=null;return e===0?(s=N(i,n,r),o=N(i,s,a,this.activity),{ls:s,lf:o}):(s=N(i,n,r,this.activity),o=N(i,s,a,this.activity),{ls:s,lf:o})}},xp=cl;var dl=class extends xp{constructor(e){super(e),this.constraint=e.constraint||C.ASAP,this.parentsWithFullProgress=e.parentsWithFullProgress,this.parentsThatImpactChildrens=e.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new hn(this.gantt,Q.BACKWARD).calculateStartAndFinishOfChainOrigin(this.activity);let e=this.activity.progress>0&&this.activity.progress<100,n=this.gantt.getTask(this.activity.parent),i=!1;n&&(i=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let r=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(r.length!==0){let o=this.getMinLfFromLinks(r);if(r.push(this.calculateTheLsAndLfForTheActivity()),i){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));r.push(this.calculateTheLsAndLfForTheActivity(d))}let s=this.getMinDateFromLinks(r),l=s.ls,c=s.lf;return e&&(l=this.activity.start_date,c=this.getMinCalculationLogic(s)),{ls:l,lf:c,minFromLinks:o}}if(i){r.push(this.calculateTheLsAndLfForTheActivity());let s=this.parentsThatImpactChildrens.get(Number(this.activity.parent)).lf,l=N(this.gantt.getCalendar(this.activity.calendar_id),s,-this.activity.duration,this.activity);r.push({ls:l,lf:s});let c=this.getMinDateFromLinks(r);return{ls:c.ls,lf:c.lf,minFromLinks:c}}let a=this.calculateTheLsAndLfForTheActivity();return{ls:a.ls,lf:a.lf,minFromLinks:a}}calculateTheLsAndLfForTheActivity(e=null){try{let n=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 r=e?e.lf:this.projectDates.end_date;if(!r)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:N(i,r,-n,this.activity),lf:r}}catch(n){throw Error(n.message)}}SnetSnltMsoMinDate(e){let n=Math.min(e.lf,this.projectDates.end_date);return new Date(Math.max(n,this.activity.end_date))}calculateLink(e){let n=this.gantt.getTask(e.target);if(!n||n.progress>0&&n.type!==k.PROJECT)return;let i=this.getSpecialCalculationParamForConstraintLink(),r=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(e,i),1:()=>this.calculateSS(e),2:()=>this.calculateFF(e,a),3:()=>this.calculateSF(e,r)}[e.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===C.ALAP)return C.ALAP;if(this.constraint===C.FNET||this.constraint===C.SNET)return"snet-fnet";if(this.constraint===C.FNLT)return C.FNLT}getSpecialParamForSf(){return!![C.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![C.MFO,C.MSO].includes(this.constraint)}getMinCalculationLogic(e){if(this.constraint===C.ALAP)return this.getMinDateBasedOnConstraint(e);if(this.constraint===C.FNET)return this.getMinDateBasedOnConstraint(e);if(this.constraint===C.FNLT)return this.getMinDateBasedOnConstraint(e);if(this.constraint===C.MFO)return this.getMinDateBasedOnConstraint(e);if(this.constraint===C.SNET||this.constraint===C.SNLT||this.constraint===C.MSO)return this.SnetSnltMsoMinDate(e);if(this.constraint===C.ASAP)return this.getMinDateBasedOnConstraint(e)}getMinDateFromLinks(e){try{return this.constraint===C.ALAP||this.constraint===C.ASAP?e.reduce((i,r)=>r.lf<i.lf?r:i):e.reduce((n,i)=>i.ls<n.ls?i:n)}catch(n){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${n.message}`)}}getMinLfFromLinks(e){return e.reduce((n,i)=>i.lf<n.lf?i:n)}getMinDateBasedOnConstraint(e,n=this.constraint){let i=Math.min(e.lf,this.projectDates.end_date),r=this.activity.end_date,a=this.activity.constraint_date;if(n===C.ASAP)return new Date(Math.max(i,r));if(n===C.FNET||n===C.FNLT){let o=Math.min(i,a);return new Date(Math.max(i,o))}if(n===C.ALAP)return new Date(Math.min(i,r))}},Mp=dl;function oC(t,e,n){let i={ls:null,lf:null};return n===C.MSO&&(i.ls=e.constraint_date,i.lf=N(t,i.ls,e.duration,e)),n===C.MFO&&(i.lf=e.constraint_date,i.ls=N(t,i.lf,-e.duration,e)),i}var Up=oC;var ul=class extends hn{constructor(e,n,i){super(e,Q.BACKWARD),this.gantt=e,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=n,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(e){this.identifyParentsWithAndWithoutLinks(),e()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),e()&&(this.initializeActivitiesWithFullProgress(),e()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),e()&&(this.identifySecondLevelActivities(),e()&&(this.identifyThirdLevelActivities(),e()&&await this.iterativeCalculateLfAndLs(e))))))}async iterativeCalculateLfAndLs(e){let n=new eo({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 vr({pending:this.activitiesWaitingForCalculation,activityCalculator:n,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:e})}setDatesToParentsWithLinks(e){if(!e)throw new Error("Error trying to get parent",{cause:{receivedParentData:e}});let n=this.singleParents.get(e.id).childrens,r=Array.from(this.calculations).filter(s=>n.includes(s[0])).map(s=>s[1]),{minLs:a,maxLf:o}=r.reduce((s,{ls:l,lf:c})=>({minLs:new Date(Math.min(s.minLs.getTime(),new Date(l).getTime())),maxLf:new Date(Math.max(s.maxLf.getTime(),new Date(c).getTime()))}),{minLs:new Date(r[0].ls),maxLf:new Date(r[0].lf)});this.calculations.set(e.id,{ls:a,lf:o})}calculateStartAndFinishTimes(e){e.forEach(n=>{let i=this.gantt.getTask(n);if(!i)throw new Error("Activity not found",{cause:{activityId:n}});let r=i.$source,a=i.constraint_type||C.ASAP,o=Number(i.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(n)){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===k.PROJECT)return this.doCalculationForParentType(i);if(o===100){this.setDatesForActivityWithFullProgress(i);return}if(this.allLinkedActivitiesHasProgress(r,i)){this.setWhenAllLinkedActivitiesHasProgress(i);return}if(o>0&&o<100&&(a===C.MSO||a===C.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(i,a);return}if(a===C.MSO||a===C.MFO){this.recalculateInBaseRestriction(i,a);return}let{ls:s,lf:l,minFromLinks:c}=this.calculateLfandLsFromLinks(r,i,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===C.SNLT||a===C.FNLT)&&({ls:s,lf:l}=this.getTheLessLateInBasEsEfConstraint(i.id,{ls:s,lf:l},a)),this.setCalculations(i,s,l),this.minFromLinks.set(i.id,{ls:c.ls,lf:c.lf})})}getTheLessLateInBasEsEfConstraint(e,n,i){let r=this.forwardConstraintsMap.get(e);if(!r){let a=this.gantt.getTask(e),o=this.gantt.getCalendar(a.calendar_id);r=to(a,i,o)}return n.lf<r.ef?n:{ls:r.es,lf:r.ef}}allLinkedActivitiesHasProgress(e){try{let n=!0;for(let i of e){let r=this.gantt.getLink(i);if(!r)continue;let a=this.gantt.getTask(r.target);a&&(a.type===k.PROJECT&&(n=!1),a.progress===0&&(n=!1))}return n}catch(n){throw new Error(n.message)}}setDatesForActivityWithFullProgress(e){this.setCalculations(e,e.start_date,e.end_date)}setWhenAllLinkedActivitiesHasProgress(e){let n=Number(e.parent),{ls:i,lf:r}=this.calculateStartAndFinishOfChainOrigin(e,Q.BACKWARD);if(this.calculationsOfParentThatImpactChildrens.has(n)){i=e.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(n);a&&typeof a=="object"&&a.lf!=null&&(r=new Date(Math.min(r,a.lf)))}this.setCalculations(e,i,r)}setWhenActivitiesHasProgressButLessThanOneHundred(e,n){if(n===C.MSO){this.setCalculations(e,e.start_date,e.end_date);return}if(n===C.MFO){let i=Math.min(e.constraint_date,this.projectDates.end_date),r=new Date(Math.max(i,e.end_date));this.setCalculations(e,e.start_date,r);return}}setCalculations(e,n,i){this.calculations.set(e.id,{ls:n,lf:i,text:e.text})}calculateLfandLsFromLinks(e,n,i,r,a){return new Mp({links:e,activity:n,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:i,parentsWithFullProgress:r,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(e,n){try{let i=this.gantt.getCalendar(e.calendar_id);if(!i)throw new Error(`Error trying to get calendar with id: ${e.calendar_id}`);let r=Up(i,e,n);this.constraintMap.set(e,r),this.setCalculations(e,r.ls,r.lf)}catch(i){throw new Error(i.message)}}cleanAllActivityParentsFromLinks(e){return e.map(n=>{let i=this.gantt.getLink(n).source,r=this.gantt.getLink(n).target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type===k.PROJECT)&&!(!this.gantt.getTask(r)||this.gantt.getTask(r)?.type===k.PROJECT))return n}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(e){let n=Number(e.parent),i=this.calculationsOfParentThatImpactChildrens.get(n),r=0,a=0;if([C.ASAP,C.ALAP,C.SNET,C.FNET].includes(e.constraint_type))if(Number(e.progress)>0){let c=this.projectDates.end_date;a=new Date(Math.min(c,i.lf)),r=e.start_date}else a=i.lf,r=N(this.gantt.getCalendar(e.calendar_id),a,-e.duration,e);if([C.SNLT].includes(e.constraint_type)){let c=this.calculationsOfParentThatImpactChildrens.get(n),d=N(this.gantt.getCalendar(e.calendar_id),c.lf,-e.duration,e),u=e.constraint_date??d;r=new Date(Math.min(u.getTime(),d.getTime())),a=N(this.gantt.getCalendar(e.calendar_id),r,e.duration,e)}if([C.FNLT].includes(e.constraint_type)){let c=this.calculationsOfParentThatImpactChildrens.get(n),d=e.constraint_date??c.lf;r=new Date(Math.min(d.getTime(),c.lf.getTime())),a=N(this.gantt.getCalendar(e.calendar_id),r,e.duration,e)}[C.MSO].includes(e.constraint_type)&&(r=e.constraint_date,a=N(this.gantt.getCalendar(e.calendar_id),r,e.duration,e)),[C.MFO].includes(e.constraint_type)&&(a=e.constraint_date,r=N(this.gantt.getCalendar(e.calendar_id),a,-e.duration,e));let o=this.projectDates.end_date,s=[{ls:r,lf:a}];s.push({ls:N(this.gantt.getCalendar(e.calendar_id),o,-e.duration,e),lf:o});let l=this.getMinLfFromLinks(s);this.calculations.set(e.id,{ls:l.ls,lf:l.lf,text:e.text})}getMinLfFromLinks(e=[]){return e.length?e.reduce((n,i)=>i.lf<n.lf?i:n):!1}},Hp=ul;function Bp(){return null}var jp=({forward:t,backward:e,id:n,activity:i,gantt:r,projectDates:a})=>({totalFloat:{es:t.calculations.get(n)?.es||0,ef:t.calculations.get(n)?.ef||0,ls:e.calculations.get(n)?.ls||0,lf:e.calculations.get(n)?.lf||0,constraintsMap:t.constraintsMap.get(n),totalFloatSnltFnlt:t.totalFloatSnltFnlt.get(n),totalFloatForMsoMfo:t.totalFloatForMsoMfo.get(n),minFromLinks:e.minFromLinks.get(n),activity:i,gantt:r},freeFloat:{forwardMap:t.calculations||new Map,backwardMap:e.calculations||new Map,activity:i,projectDates:a,gantt:r}});var pl=class{constructor(e){this.gantt=e.gantt,this.activity=e.activity,this.es=e.es,this.ef=e.ef,this.ls=e.ls,this.lf=e.lf,this.constrainstMap=e.constraintsMap,this.totalFloatSnltFnlt=e.totalFloatSnltFnlt,this.totalFloatForMsoMfo=e.totalFloatForMsoMfo,this.minFromLinks=e.minFromLinks}getTotalFloat(){let{constraint_type:e}=this.activity,n=Number(this.activity.progress);if(n===100)return 0;if(e||(e=C.ASAP),e===C.ASAP||!e)return n===0?this.calculateAsap():this.calculateAsapWithProgress();if(e===C.ALAP)return n===0?this.calculateAlap():this.calculateAlapWithProgress();if(e===C.SNET||e===C.FNET)return n===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(e===C.SNLT)return n===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(e===C.FNLT)return n===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(e===C.MSO||e===C.MFO)return n===0?this.calculateMsoMfo():this.calculateMsoMfoWithProgress()}calculateAsap(){let e=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(e,n)/this.gantt.config.hoursPerDay}calculateAsapWithProgress(){let e=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(e,n)/this.gantt.config.hoursPerDay}return e/this.gantt.config.hoursPerDay}calculateAlap(){let e=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(e,n),r=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(i,r)/this.gantt.config.hoursPerDay}calculateAlapWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFnetSnltWithProgress(){let e=this.calculationWithCalendar(this.lf,this.ef);if(this.minFromLinks){let n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(e,n)/this.gantt.config.hoursPerDay}return e/this.gantt.config.hoursPerDay}calculateFnltWithProgress(){let e=this.calculationWithCalendar(this.lf,this.ef),n=this.calculationWithCalendar(this.activity.constraint_date,this.ef);if(this.minFromLinks){let i=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(e,n,i)/this.gantt.config.hoursPerDay}return this.getMinValue(e,n)/this.gantt.config.hoursPerDay}calculateMsoMfoWithProgress(){return this.calculationWithCalendar(this.lf,this.ef)/this.gantt.config.hoursPerDay}calculateSnetFet(){let e=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef);return this.getMinValue(e,n)/this.gantt.config.hoursPerDay}calculateSnltFnlt(){let e=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(e,n);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(e,n)/this.gantt.config.hoursPerDay;let r=0;return this.activity.constraint_type===C.SNLT?r=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):r=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(r,i)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let e=this.calculationWithCalendar(this.ls,this.es),n=this.calculationWithCalendar(this.lf,this.ef),i=this.getMinValue(e,n);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(e,n)/this.gantt.config.hoursPerDay;let r=0;return this.activity.constraint_type===C.MSO?r=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):r=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(r,i)/this.gantt.config.hoursPerDay}getMinValue(...e){return Math.min(...e)}calculationWithCalendar(e,n){return this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(n),end_date:new Date(e)})}},Wp=pl;var fl=class{constructor(e){this.gantt=e.gantt,this.activity=e.activity,this.forwardMap=e.forwardMap,this.backwardMap=e.backwardMap,this.projectDates=e.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let e=Number(this.activity.progress),n=this.getConstraintType();return this.calculateFreeFloatOfLink(n),{activityFreeFloat:e===100?0:this.getFreeFloatBaseConstraint(n),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(e){return e===C.MSO||e===C.MFO?this.calculateMsoMfo(e):this.calculateGeneral(e)}calculateFreeFloatOfLink(e=C.ASAP){let n=this.activity.$source.map(i=>{let{LINK:r,LINK_TYPE:a}=this.getLinkData(i),o=this.gantt.getTask(r.target);if(!o)return{linkId:r.id,freeFloat:null,hasProgress:!1};let s=Number(o.progress)>0,{sucessorDateToCalculate:l,predecessorDateToCalculate:c}=this.getDatesFromSucessorAndPredecessor(a,e,o),d=this.calculationWithCalendar(l,c),u=this.parseHoursToDays(d)-this.parseHoursToDays(r.lag),p=Math.max(0,u);return this.linksFreeFloatObject[r.id]=p,{linkId:r.id,freeFloat:p,hasProgress:s}}).filter(i=>i.freeFloat!==null&&i.freeFloat!==void 0);return this.linksFreeFloatArray=n,n}calculateGeneral(e=C.ASAP){let n=this.getMinFloat(this.linksFreeFloatArray),i=this.calculateFreeFloatForEndOfProject(e),r=[C.SNLT,C.FNLT].includes(e)&&n===null?this.doCalculationForSnltFnlt(e,i,n):this.doGeneralCalculation(i,n);return Math.max(0,r)}getConstraintType(){let{constraint_type:e}=this.activity;return e||(e=C.ASAP),e}getDatesFromSucessorAndPredecessor(e,n,i){let r=i.constraint_type===C.ALAP,a=this.getSucessorAndPredecessorDates({constraint:n,isSuscessorAlap:r,sucessorId:i.id,predecessorId:this.activity.id}),o=new Date,s=new Date;return o=a[e].sucessor,s=a[e].predecessor,{sucessorDateToCalculate:o,predecessorDateToCalculate:s}}doGeneralCalculation(e,n){return n===null?e:this.getMinValue(n,e)}doCalculationForSnltFnlt(e,n,i){let r=this.calculateFreeFloatOfRestriction(e);return this.getMinValue(i,n,r)}calculateFreeFloatForEndOfProject(e){let n=e===C.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,e===C.ALAP?n?.lf:n?.ef))}calculateFreeFloatOfRestriction(e){let n=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,e===C.FNLT?n?.ef:n?.es))}getLinkData(e){let n=this.gantt.getLink(e)||{},i=Wn(n.type);return{LINK:n,LINK_TYPE:i}}getSucessorAndPredecessorDates({constraint:e,isSuscessorAlap:n,sucessorId:i,predecessorId:r}){let a=(n?this.backwardMap:this.forwardMap).get(i),o=(e===C.ALAP?this.backwardMap:this.forwardMap).get(r),s=e===C.ALAP?o?.ls:o?.es,l=e===C.ALAP?o?.lf:o?.ef;return{fs:{sucessor:a?.ls??a?.es,predecessor:l},ss:{sucessor:a?.ls??a?.es,predecessor:s},ff:{sucessor:a?.lf??a?.ef,predecessor:l},sf:{sucessor:a?.lf??a?.ef,predecessor:s}}}calculateMsoMfo(e){let n=this.activity.constraint_date||new Date,i=this.forwardMap.get(this.activity.id),r=e===C.MSO?i?.es:i?.ef,a=this.calculationWithCalendar(n,r);return Math.max(0,this.parseHoursToDays(a))}getMinValue(...e){let n=e.filter(i=>i!=null);return n.length?Math.min(...n):0}calculationWithCalendar(e,n){if(!(e instanceof Date)||!(n instanceof Date)||!Number.isFinite(e.getTime())||!Number.isFinite(n.getTime()))return Number.NaN;let i=`${n.getTime()}_${e.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(n),end_date:new Date(e)});return this.durationCache.set(i,a),a}parseHoursToDays(e){return e==null?0:e/this.gantt.config.hoursPerDay}getMinFloat(e){if(!e?.length)return null;let n=e.filter(i=>!i.hasProgress).map(i=>i.freeFloat);return n.length===0?null:Math.min(...n)}},Vp=fl;var Kp=t=>({totalFloat:new Wp(t.totalFloat).getTotalFloat(),freeFloat:new Vp(t.freeFloat).getFreeFloat()});var yl=async({activityIds:t,forward:e,backward:n,gantt:i,projectDates:r,isCurrent:a})=>{let o=performance.now(),s=new Map,l=new Map;for(let c of t){if(a&&!a())return{totalFloatMap:s,freeFloatMap:l};let d=i.getTask(c);if(!d)continue;let u=jp({forward:e,backward:n,id:c,activity:d,gantt:i,projectDates:r}),{totalFloat:p,freeFloat:f}=Kp(u);s.set(c,p),l.set(c,f),o=await Kn(o)}return{totalFloatMap:s,freeFloatMap:l}};var hl=class{constructor(e){this.gantt=e,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(e,n=()=>!0){let i=++this.currentCalculationId,r=ol(i,this.getCurrentCalculationId),a=()=>r()&&n();try{let o=e||this.gantt;if(this.gantt=o||Bp(),sl(this.gantt))return!1;let s=new wp(this.gantt);if(await s.calculateAsync(a),!a())return!1;let l=s.calculations,c=s.constraintsMap,d=new Hp(this.gantt,l,c);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=l,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(s.linkCandidates,l,a);if(!u||!a())return!1;this.linkResidualHours=u;let{totalFloatMap:p,freeFloatMap:f}=await this.calculateFloatsAsync(s,d,a);return a()?(this.totalFloat=p,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(o){throw this.forwardPathCalculations?.size,o}}async calculateLinkResidualHours(e,n,i=()=>!0){let r=new Map,a=performance.now();for(let[o,s]of e){if(a=await Kn(a),!i())return null;let l=Number(s.targetId),c=this.gantt.getTask(l),d=n.get(l),u=s.ef,p=d?.ef,f=c&&this.gantt.getCalendar(c.calendar_id);if(!f||!(u instanceof Date)||!(p instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(p.getTime())){r.set(o,null);continue}let y=u.getTime(),h=p.getTime()>=y?f.calculateDuration({start_date:u,end_date:p}):-f.calculateDuration({start_date:p,end_date:u});r.set(o,Number.isFinite(h)?Object.is(h,-0)?0:h:null)}return r}async calculateFloatsAsync(e,n,i){try{let r=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await yl({activityIds:a,forward:e,backward:n,gantt:this.gantt,projectDates:r,isCurrent:i})}catch(r){throw this.forwardPathCalculations?.size,r}}},Yp=hl;var sC=t=>t===D.FNET||t===D.FNLT||t===D.MFO,lC=t=>new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));function cC(t,e){let n=t.constraintDate;if(!n||!sC(t.constraintType))return n;let i=lC(n);if(n.getTime()!==i.getTime())return n;let r=e.getClosestWorkTime({date:i,dir:"future",task:t});return r.getUTCFullYear()===n.getUTCFullYear()&&r.getUTCMonth()===n.getUTCMonth()&&r.getUTCDate()===n.getUTCDate()?Zi(t,e):n}function dC(t){let e=new Map,n=new Map,i=new Map;return{calculateEndDate:({start_date:r,duration:a})=>{let o=`${r.getTime()}|${a}`,s=e.get(o);if(s!==void 0)return new Date(s);let l=t.calculateEndDate(r,a);return e.set(o,l.getTime()),l},calculateDuration:({start_date:r,end_date:a})=>{let o=`${r.getTime()}|${a.getTime()}`,s=n.get(o);if(s!==void 0)return s;let l=t.calculateDuration(r,a);return n.set(o,l),l},getWorkHours:r=>t.getWorkHours(r),$gantt:{getClosestWorkTime:({date:r,dir:a,unit:o})=>{let s=o??"hour",l=`${r.getTime()}|${a}|${s}`,c=i.get(l);if(c!==void 0)return new Date(c);let d=t.getClosestWorkTime({date:r,direction:a,unit:s});return i.set(l,d.getTime()),d}}}}function uC(t){let e=new Map;t.forEachActivity((r,a)=>e.set(String(a),r));let n=new Map,i=(r,a)=>{let o=n.get(r);if(o!=null)return o;let l=e.get(r)?.parentId??null,c=0;return l!==null&&!a.has(r)&&(a.add(r),c=i(String(l),a)+1),n.set(r,c),c};for(let r of e.keys())i(r,new Set);return n}function pC(t){let e=new Set;t.forEachActivity((s,l)=>{e.add(String(l)),s.parentId!==null&&e.add(String(s.parentId))});let n=new Map;for(let s of e){let l=Number(s);Number.isSafeInteger(l)&&l!==0&&n.set(l,(n.get(l)??0)+1)}let i=new Map,r=new Map;for(let s of e){let l=Number(s);Number.isSafeInteger(l)&&l!==0&&n.get(l)===1&&(i.set(s,l),r.set(l,s))}let a=1,o=s=>{let l=String(s),c=i.get(l);if(c!==void 0)return c;for(;r.has(a);)a+=1;return i.set(l,a),r.set(a,l),a++};for(let s of e)o(s);return{toLegacy:o,toCanonical:s=>typeof s=="number"?r.get(s)??null:i.has(String(s))?String(s):null}}function fC(t,e){let n=uC(t),i=new Map;return t.forEachActivity((r,a)=>{let o=String(a);i.set(o,{id:e.toLegacy(o),parent:r.parentId===null?0:e.toLegacy(r.parentId),$level:n.get(o)??0,$source:t.getOutgoingLinkIds(o),$target:t.getIncomingLinkIds(o),start_date:r.startDate,end_date:r.endDate,duration:r.durationHours,progress:r.progress,type:r.type,calendar_id:r.calendarId,constraint_type:r.constraintType,constraint_date:cC(r,t)})}),i}function yC(t){let e=new Map;for(let o of t.values()){let s=e.get(o.parent);s?s.push(o):e.set(o.parent,[o])}let n=[],i=new Set,r=[],a=o=>{if(o)for(let s=o.length-1;s>=0;s-=1)r.push(o[s])};for(a(e.get(0));r.length>0;){let o=r.pop();i.has(o)||(i.add(o),n.push(o),a(e.get(o.id)))}if(n.length<t.size)for(let o of t.values())i.has(o)||n.push(o);return n}function hC(t){let e=null,n=null;return t.forEachActivity(i=>{if(i.startDate){let r=i.startDate.getTime();e=e==null?r:Math.min(e,r)}if(i.endDate){let r=i.endDate.getTime();n=n==null?r:Math.max(n,r)}}),{start_date:new Date(e??0),end_date:new Date(n??0)}}async function Gp(t,e){let n=new Map,i=c=>{let d=c==null?"__default__":String(c),u=n.get(d);if(u)return u;let p=t.calendarReader.getCalendar(String(c)),f=dC(p);return n.set(d,f),f},r=hC(t);await mt();let a=pC(t),o=fC(t,a);await mt();let s=[...o.values()].sort((c,d)=>(c.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await mt();let l=yC(o);return{fullyParsed:!0,config:{hoursPerDay:e},getTask:c=>{let d=a.toCanonical(c);return d===null?null:o.get(d)??null},getLink:c=>{let d=t.getLink(c);return d?{...d,source:a.toLegacy(d.source),target:a.toLegacy(d.target),lag:d.lag}:null},getCalendar:i,getChildren:c=>{let d=a.toCanonical(c);return d===null?[]:t.getChildren(d).map(a.toLegacy)},eachTask:c=>{for(let d of l)c(d)},getTaskByTime:()=>s,getSubtaskDates:()=>r,getCanonicalActivityId:a.toCanonical,refreshData:()=>{}}}var gl=1e3,mC=t=>typeof t!="number"||!Number.isFinite(t)?null:Object.is(t,-0)?0:t,gC=(t,e)=>typeof t!="number"||t<0?null:ml(t,e);function AC(t){let e=gC(t.freeFloatDays,t.hoursPerDay),n=mC(t.residualHours);return{freeSlackHours:e,isCritical:n!==null&&n<=0&&t.sourceIsCritical&&t.targetIsCritical&&t.targetProgress===0}}async function IC(t,e){let n=new Map,i=0;for(let r of t.values())for(let a in r.linksFreeFloat)if(Object.hasOwn(r.linksFreeFloat,a)){if(++i>=gl&&(i=0,await mt(),!e()))return null;n.set(String(a),r.linksFreeFloat[a])}return e()?n:null}async function SC(t,e,n,i,r){let a=new Map,o=0;for(let s of e.forward?.keys()??[]){if(++o>=gl&&(o=0,await mt(),!r()))return null;let l=i(s);if(l===null)continue;let c=t.getActivity(l);c&&a.set(String(l),CC(s,Number(c.progress??0),e,n))}return r()?a:null}async function vC(t,e,n,i,r,a){let o=new Map,s=0;for(let l of t.getAllLinks()){if(++s>=gl&&(s=0,await mt(),!a()))return null;o.set(String(l.id),AC({freeFloatDays:e.get(String(l.id)),residualHours:n.get(String(l.id)),hoursPerDay:r,sourceIsCritical:i.get(l.source)?.isCritical===!0,targetIsCritical:i.get(l.target)?.isCritical===!0,targetProgress:t.getActivity(l.target)?.progress}))}return a()?o:null}var ml=(t,e)=>{if(typeof t!="number"||!Number.isFinite(t)||!Number.isFinite(e)||e<=0)return null;let n=t*e;return Number.isFinite(n)?Object.is(n,-0)?0:n:null};function CC(t,e,n,i){let r=l=>{if(l==null)return null;let c=new Date(l);return Number.isFinite(c.getTime())?c:null},a=n.forward?.get(t),o=n.backward?.get(t),s=ml(n.totalFloat.get(t),i);return{criticalPath:{earlyStart:r(a?.es),earlyFinish:r(a?.ef),lateStart:r(o?.ls),lateFinish:r(o?.lf),totalSlackHours:s},isCritical:e<100&&s!==null&&s<=0,freeSlackHours:ml(n.freeFloat.get(t)?.activityFreeFloat,i)}}var no=(t,e)=>t===e||t!==null&&e!==null&&t.getTime()===e.getTime();function Al(t,e,n){let i=t.getActivity(e),r=i?.criticalPath,a=n.criticalPath;i&&r&&no(r.earlyStart,a.earlyStart)&&no(r.earlyFinish,a.earlyFinish)&&no(r.lateStart,a.lateStart)&&no(r.lateFinish,a.lateFinish)&&Object.is(r.totalSlackHours,a.totalSlackHours)&&Object.is(i.isCritical,n.isCritical)&&Object.is(i.freeSlackHours,n.freeSlackHours)||t.setActivityFields(e,n)}function Il(t,e,n){let i=t.getLink(e);!i||Object.is(i.freeSlackHours,n.freeSlackHours)&&Object.is(i.isCritical,n.isCritical)||(t.setLinkField(e,"freeSlackHours",n.freeSlackHours),t.setLinkField(e,"isCritical",n.isCritical))}async function Sl(t,e,n=()=>!0){if(!n())return null;let i=await Gp(t,e);if(!n())return null;let r=new Yp(i);if(!await r.calculate(i,n)){if(!n())return null;throw new Error("critical path calculation aborted")}if(!n())return null;let o={forward:r.forwardPathCalculations,backward:r.backwardPathCalculations,totalFloat:r.totalFloat,freeFloat:r.freeFloat},s=await SC(t,o,e,i.getCanonicalActivityId,n);if(!s)return null;let l=await IC(o.freeFloat,n);if(!l)return null;let c=await vC(t,l,r.linkResidualHours,s,e,n);return c?{activities:s,links:c}:null}async function $p(t,e,n=()=>!0){let i=await Sl(t,e,n);if(!i||!n())return!1;for(let[r,a]of i.activities){if(!n())return!1;Al(t,r,a)}for(let[r,a]of i.links){if(!n())return!1;Il(t,r,a)}return!0}function Ti(t){let e=[],n=[];t.forEachActivity((r,a)=>{r.parentId===null&&e.push(String(a))});let i=r=>{let a=t.getActivity(String(r));if(!a)return 0;let o=[...t.getChildren(String(r))],s;if(o.length===0){let l=Lt(a),c=l&&Number(l.cost)||0;s=(Number(a.progress)||0)/100*c}else{let l=0;for(let c of o)l+=i(String(c));s=l}return t.setActivityField(String(r),U.REAL_COST,s),n.push(String(r)),s};for(let r of e)i(r);return n}var qp=new Set;var zp=new Set(["activity-outdent","activity-indent"]);var Cr=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),DC=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.VIEW_ATTRIBUTES_SET,I.GROUP_SET,I.WBS_DEPTH_SET,I.SIR_SYNC,I.ACTIVITY_LOOKAHEAD_SYNC,I.PERSISTENCE_ACKNOWLEDGE,I.BASELINE_APPLY,I.PONDERATOR_CRITERION_SET,I.STATUS_CRITERIA_SET]),TC=new Set([I.ACTIVITY_CLIPBOARD_CLEAR,I.ACTIVITY_COPY,I.SELECTION_TOGGLE,I.SELECTION_REPLACE,I.VISIBILITY_SET,I.FILTER_SET,I.SORT_SET,I.VIEW_ATTRIBUTES_SET,I.GROUP_SET,I.WBS_DEPTH_SET]),Jp=new Set(Object.values(Qn));function Zp(t){return!TC.has(t.kind)}var _C=new Set;function EC(t){return t.kind===I.INLINE_EDIT?Cr.has(t.column):t.kind===I.BULK_EDIT?t.edits.every(e=>Cr.has(e.column)):!1}function vl(t){return t.kind===I.INLINE_EDIT?Jp.has(t.column):t.kind===I.BULK_EDIT&&t.edits.every(e=>Jp.has(e.column))}function Cl(t,e){return!(DC.has(t.kind)||e.has(t.kind)||EC(t))}function Dr(t){return t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?t.persistedProgress!==void 0:Cl(t,_C)}function Yn(t){return vl(t)?!1:t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?t.persistedProgress!==void 0:Cl(t,qp)}function Qp(t){return vl(t)?!1:Cl(t,zp)}function Dl(t){return t.kind===I.ACTIVITY_SET_PROGRESS?!0:t.kind===I.INLINE_EDIT?t.column===E.PROGRESS:t.kind===I.BULK_EDIT?t.edits.some(e=>e.column===E.PROGRESS):!1}function PC(t){return Qp(t)&&Dl(t)}var Xp=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function RC(t){return t.kind===I.ACTIVITY_SET_PROGRESS?!0:t.kind===I.INLINE_EDIT?Xp.has(t.column):t.kind===I.BULK_EDIT?t.edits.some(e=>Xp.has(e.column)):!1}var bt={AUTOSCHEDULE:"autoschedule",PARENT_BOUNDS:"parent-bounds",PARENT_PROGRESS:"parent-progress",REAL_WORK:"real-work",EXPECTED_PROGRESS:"expected-progress",REAL_COST:"real-cost",BASELINE_VARIANCE:"baseline-variance",CRITICAL_PATH:"critical-path"};function tf(t,e,n){let i=new Set;if(e.ran&&i.add(bt.AUTOSCHEDULE),i.add(bt.PARENT_BOUNDS),vl(t))return i;RC(t)&&i.add(bt.PARENT_PROGRESS),Dl(t)&&i.add(bt.REAL_WORK);let r=!n.skipAutoSchedule;return r&&Qp(t)&&i.add(bt.EXPECTED_PROGRESS),r&&PC(t)&&i.add(bt.REAL_COST),Dr(t)&&i.add(bt.BASELINE_VARIANCE),r&&Yn(t)&&!n.skipCriticalPath&&i.add(bt.CRITICAL_PATH),i}function lt(t){return t?.dataDate!=null}var ef=(t,e)=>{if(!(t instanceof Date)||!Number.isFinite(t.getTime()))throw new TypeError(`Outbuild P6 ${e} must be a valid Date`);return new Date(t.getTime())};function kC(t){if(t.type==="project")return;if(!Number.isFinite(t.durationHours)||t.durationHours<0)throw new TypeError("Outbuild P6 durationHours must be a non-negative finite number");let e=ef(t.startDate,"plannedStart"),n=ef(t.endDate,"plannedFinish"),i=t.durationHours;return{activityType:"task",actualStart:null,actualFinish:null,plannedStart:e,plannedFinish:n,remainingDurationHours:i,executionStatus:"not_started",expectedFinish:null,suspendDate:null,resumeDate:null,secondaryConstraintType:null,secondaryConstraintDate:null,percentCompleteType:ht.PHYSICAL,physicalPercentComplete:0,actualDurationHours:0,atCompletionDurationHours:i,durationPercentComplete:0,unitsPercentComplete:0,schedulePercentComplete:0,remainingFloatHours:null,remainingEarlyStart:null,remainingEarlyFinish:null,remainingLateStart:null,remainingLateFinish:null,earlyStart:null,earlyFinish:null,lateStart:null,lateFinish:null,floatPath:null,floatPathOrder:null,longestPath:!1,originalDurationHours:i,actualLaborUnits:0,remainingLaborUnits:0,actualNonlaborUnits:0,remainingNonlaborUnits:0,primaryBaselineStart:null,primaryBaselineFinish:null,freeFloatHours:null}}function _i(t){let e=kC(t);if(e!==void 0)return{...e,remainingDurationHours:Tl(t)}}function Tl(t){return t.progress===0?t.durationHours:Aa(t.progress)?0:null}function nf(t,e){if(!(e===void 0||lt(e.settings)))for(let n of t.getAllActivities()){if(Object.hasOwn(e.activities,n.id))continue;let i=_i(n);i!==void 0&&t.setActivityField(n.id,"p6",i)}}function rf(t){if(t.dataDateSettings()===null||lt(t.dataDateSettings()))return;let e=t.peekWriteCapture();if(e!==null)for(let[n,i]of e.before){let r=t.getActivity(n);if(r?.p6===void 0||i.p6===void 0)continue;let a=LC(i,r);Object.keys(a).length!==0&&t.setActivityField(r.id,"p6",{...r.p6,...a})}}function LC(t,e){let n=t.durationHours!==e.durationHours;return{...t.startDate.getTime()!==e.startDate.getTime()?{plannedStart:new Date(e.startDate)}:{},...t.endDate.getTime()!==e.endDate.getTime()?{plannedFinish:new Date(e.endDate)}:{},...n?{originalDurationHours:e.durationHours}:{},...n||t.progress!==e.progress?OC(t,e):{}}}function OC(t,e){let n=e.p6;if(n.actualStart!==null||n.remainingDurationHours!==t.p6.remainingDurationHours)return{};let i=Tl(e);return{remainingDurationHours:i,...i!==null?{atCompletionDurationHours:i}:{}}}var Rt={INSERT:"insert",REMOVE:"remove",LINK_ADD:"link-add",LINK_REMOVE:"link-remove",LINK_FIELD:"link-field"},io=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(e,n){let i=this._journal;i&&(i.before.has(e)||i.before.set(e,xe(n)),i.dirty.add(e))}noteInsert(e){this._journal?.ops.push({kind:Rt.INSERT,activityId:e})}noteRemove(e,n){this._journal?.ops.push({kind:Rt.REMOVE,activityId:e,before:xe(n)})}noteLinkAdd(e){this._journal?.ops.push({kind:Rt.LINK_ADD,linkId:e})}noteLinkRemove(e,n){this._journal?.ops.push({kind:Rt.LINK_REMOVE,linkId:e,before:af(n)})}noteCorrelativeBefore(e,n){let i=this._journal;if(!i||i.correlativeBefore.has(e))return;let r=i.before.get(e)?.correlativeId;i.correlativeBefore.set(e,typeof r=="number"?r:n)}noteScheduledBefore(e,n){let i=this._journal;if(!i)return;let r=xe(n);i.scheduledBefore.has(e)||i.scheduledBefore.set(e,r),i.before.has(e)||i.before.set(e,r),i.dirty.add(e)}noteLinkField(e,n){let i=this._journal;!i||i.linkFieldCaptured.has(e)||(i.linkFieldCaptured.add(e),i.ops.push({kind:Rt.LINK_FIELD,linkId:e,before:af(n)}))}noteProgressFallback(e,n){let i=this._journal;!i||i.progressFallbackBefore.has(e)||i.progressFallbackBefore.set(e,n)}};function af(t){return{...t}}function _l(t,e,n){let i=[];for(let r of n){let a=t.get(r);if(!a)continue;let o=a.pendingRequestIds??[];if(ei({pendingRequestIds:o})&&e.getActivity(r)==null)for(let s of o)i.push({kind:Ga.SIR_AUTO_REJECT,activityId:r,sirId:s,reason:$a.ACTIVITY_DELETED})}return i}function zt(t){let e={id:String(t.id),source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag),freeSlackHours:typeof t.freeSlackHours=="number"&&Number.isFinite(t.freeSlackHours)?t.freeSlackHours:null,isCritical:t.isCritical===!0};return t.proplannerId!=null&&(e.proplannerId=Number(t.proplannerId)),t.ganttId!=null&&(e.ganttId=Number(t.ganttId)),t.sectorId!=null&&(e.sectorId=Number(t.sectorId)),e}var Bt={BEFORE_DIFF:"before-diff",AFTER_DIFF:"after-diff"};async function G(t,e){let n=wC(t,e),i=new Map(e.beforeSnap),r=t.peekWriteCapture();if(r){let p=MC(r);xC(t,r,p,i,n)}let a=e.sirDetection,o=a===Bt.BEFORE_DIFF?_l(i,t,n):[],s=FC(e.correlativeShifts,n),l=await za(t,i,n,s),c=a===Bt.AFTER_DIFF?_l(i,t,n):o,d=e.warnings??[],u=NC(e.links??[],r?bC(t,r):[]);return{source:e.source,activities:l,links:u,calendars:[],trackingEvents:e.trackingEvents??[],...c.length>0?{effects:c}:{},...d.length>0?{warnings:d}:{}}}function bC(t,e){let n=[];for(let i of e.ops){if(i.kind!==Rt.LINK_FIELD)continue;let r=t.getLink(i.linkId);if(!r)continue;let a={};for(let o of["freeSlackHours","isCritical"])Object.is(i.before[o],r[o])||(a[o]={before:i.before[o],after:r[o]});Object.keys(a).length!==0&&n.push({id:i.linkId,kind:x.UPDATED,fields:a,after:zt(r)})}return n}function NC(t,e){let n=[],i=new Map;for(let r of t){let a=i.get(r.id);if(a===void 0){i.set(r.id,n.length),n.push(r);continue}let o=n[a];if((o.kind===x.UPDATED||o.kind===x.CREATED)&&r.kind===x.UPDATED){n[a]={...o,fields:{...o.fields,...r.fields},after:r.after};continue}n[a]=r}for(let r of e){let a=i.get(r.id);if(a===void 0){i.set(r.id,n.length),n.push(r);continue}let o=n[a];if(o.kind===x.DELETED)continue;let s=o.kind===x.CREATED?Object.fromEntries(Object.entries(r.fields??{}).map(([l,c])=>[l,{before:void 0,after:c.after}])):r.fields;n[a]={...o,fields:{...o.fields,...s},after:r.after}}return n}function FC(t,e){if(!t||t.length===0)return;let n=new Map;for(let i of t)n.set(i.activityId,i.before),e.add(i.activityId);return n}function wC(t,e){let n=new Set;for(let i of e.touchedIds)n.add(i);for(let i of e.scheduledIds)n.add(i);if(e.includeAllIds)for(let i of t.getAllIds())n.add(i);return n}function xC(t,e,n,i,r){for(let a of e.dirty){if(n.has(a)||i.has(a))continue;let o=e.before.get(a),s=t.getActivity(a);!o||!s||Object.keys(Gs(o,s)).length!==0&&(i.set(a,o),r.add(a))}}function MC(t){return new Set(t.ops.filter(e=>e.kind===Rt.INSERT).map(e=>e.activityId))}function ro(t,e,n){if(!t||t==="0")return;let i=n.getChildren(t);if(i.length===0)return;let r=new Map,a=new Set,o=0;for(let c of i){let d=HC(String(c),e,n);r.set(String(c),d),o+=d,of(String(c),n)&&a.add(String(c))}let s=o?100/o:0,l=a.size?100/a.size:0;for(let c of i){let d=n.getActivity(c);if(!d)continue;let u=UC(String(c),d,r,a,o,s,l);u!==null&&n.setActivityField(c,E.PONDERATOR,u)}}function UC(t,e,n,i,r,a,o){return e.type===k.PROJECT||Lt(e)?r?a*(n.get(t)??0):i.has(t)?o:0:!Array.isArray(e.baselinePoints)||e.baselinePoints.length===0?0:null}function of(t,e){let n=e.getActivity(t);return n?Lt(n)?!0:n.type!==k.PROJECT?!1:e.getChildren(t).some(i=>of(String(i),e)):!1}function HC(t,e,n){let i=n.getActivity(t);if(!i)return 0;if(i.type===k.PROJECT)return sf(t,e,n);let r=Lt(i);return!r||i.type===k.MILESTONE?0:lf(r,e)}function sf(t,e,n){let i=0;for(let r of n.getChildren(t)){let a=n.getActivity(r);if(!a)continue;if(a.type===k.PROJECT){i+=sf(String(r),e,n);continue}let o=Lt(a);o&&a.type!==k.MILESTONE&&(i+=lf(o,e))}return i}function lf(t,e){return e===_t.COST?El(t.cost):e===_t.WORK_HOURS?El(t.workHours):El(t.durationDays)}function El(t){let e=typeof t=="string"?parseFloat(t):t;return typeof e=="number"&&Number.isFinite(e)?e:0}var vt={ROOTS:"roots"};async function nt(t,e){VC(t);let n=GC(t.adapter),i=BC(t.adapter,e),r=YC(i,n,df(t.adapter));r.has(bt.AUTOSCHEDULE)&&await QC(t.adapter,i);let a=r.has(bt.AUTOSCHEDULE)?await zC(t,i.autoscheduleFrom,i.preventSummaryTargetPullback):ZC();return await tD(t.adapter,i,a.scheduledIds,r,n),await nD(t,r,e.now),rf(t.adapter),a}function BC(t,e){let n=jC(t,e.autoscheduleFrom);return n===e.autoscheduleFrom?e:{...e,autoscheduleFrom:n}}function jC(t,e){if(e===vt.ROOTS)return vt.ROOTS;let n=WC(t);if(n.size===0)return e;if(e!==null&&n.add(String(e)),n.size!==1)return vt.ROOTS;let[i]=n;return i===void 0||!t.activityExists(i)||t.hasChildren(i)?vt.ROOTS:i}function WC(t){let e=new Set,n=t.peekWriteCapture();if(!n)return e;for(let i of n.ops){if(i.kind===Rt.LINK_REMOVE){e.add(String(i.before.target));continue}if(i.kind===Rt.LINK_ADD){let r=t.getLink(i.linkId);r&&e.add(String(r.target));continue}if(i.kind===Rt.LINK_FIELD){e.add(String(i.before.target));let r=t.getLink(i.linkId);r&&e.add(String(r.target))}}return e}function VC(t){let e=t.adapter.peekWriteCapture();if(!e)return;let n=new Set,i=t.sector.activityCreter??_t.DURATION;for(let[r,a]of e.before){let o=t.adapter.getActivity(r);if(a.type===k.PROJECT||o?.type!==k.PROJECT||Lt(o)||!KC(r,t.adapter))continue;let s=r;for(;s!==null&&!V(s);)n.has(s)||(ro(s,i,t.adapter),n.add(s)),s=t.adapter.getParentId(s)}}function KC(t,e){let n=[...e.getChildren(t)];for(;n.length>0;){let i=n.pop();if(i===void 0)continue;let r=e.getActivity(i);if(r&&Lt(r))return!0;n.push(...e.getChildren(i))}return!1}async function cf(t,e,n){if(t.activityId!==void 0&&!n.adapter.activityExists(t.activityId))return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};if(df(n.adapter))return{ok:!1,reason:_.MANUAL_SCHEDULING_ACTIVE};let i=await ot(n.adapter,new Set(n.adapter.getAllIds()));n.scheduler.invalidateAllCaches();let r=t.activityId===void 0?n.adapter.getRootIds():[t.activityId],{scheduledIds:a}=await nt({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:t.activityId??vt.ROOTS,recomputeParentsFrom:r,now:n.now,options:e});return{ok:!0,changes:await G(n.adapter,{source:t,beforeSnap:i,touchedIds:r,scheduledIds:a,hoursPerDay:n.sector.hoursPerDay})}}function df(t){return lt(t.dataDateSettings())}function YC(t,e,n){let i=t.autoscheduleFrom!==null,r=!t.options.skipAutoSchedule&&i&&!n,a=n?{...t.options,skipCriticalPath:!0}:t.options,o=new Set(tf(t.action,{requested:i,ran:r},a));return(t.recomputeParentProgress||e.affectedParents.size>0)&&o.add(bt.PARENT_PROGRESS),o}function GC(t){let e=new Set,n=new Set,i=t.peekWriteCapture();if(!i)return{affectedParents:e,dirtySeeds:n};let r=a=>{if(a===null||V(a))return;let o=String(a);e.add(o);let s=t.getChildren(o)[0];s!==void 0&&n.add(s)};return $C(t,i.ops,r),qC(t,i.before,n,r),{affectedParents:e,dirtySeeds:n}}function $C(t,e,n){for(let i of e)if(i.kind===Rt.INSERT){let r=t.getActivity(i.activityId);r&&n(r.parentId)}else i.kind===Rt.REMOVE&&n(i.before.parentId)}function qC(t,e,n,i){for(let[r,a]of e){let o=t.getActivity(r);if(!o)continue;let s=!Object.is(a.progress,o.progress),l=!Object.is(a.ponderator,o.ponderator),c=!Object.is(a.parentId,o.parentId);(s||l)&&(i(o.parentId),n.add(String(r))),c&&(i(a.parentId),i(o.parentId),n.add(String(r)))}}async function zC(t,e,n=!1){let i=e===vt.ROOTS?{}:{triggerId:e};n&&(i.preventSummaryTargetPullback=!0);let r=await t.scheduler.schedule(i),a=XC(t.adapter,r.updatedIds),o=JC(t.adapter,r);return rr(t.adapter,r),{...a,warnings:o}}function JC(t,e){let n=[];for(let i of e.plans.values()){let r=i.earliestSchedulingStart;if(!r||i.startDate>=r)continue;let a=t.getActivity(i.activityId);!a?.constraintType||!a.constraintDate||n.push({kind:Un.VIOLATION,activityId:a.id,constraintType:a.constraintType,constraintDate:a.constraintDate,projectedDate:r,messageKey:Un.VIOLATION})}return n}function XC(t,e){let n=[];for(let i of e){let r=String(i);n.push(r);let a=t.getActivity(r);a&&t.noteScheduledBefore(r,a)}return{scheduledIds:n,warnings:[]}}function ZC(){return{scheduledIds:[],warnings:[]}}async function QC(t,e){let n=e.collectDirty?e.collectDirty([]):$s(e.recomputeParentsFrom,[]);n.size!==0&&await we(t,n,!1)}async function tD(t,e,n,i,r){i.has(bt.PARENT_PROGRESS)&&eD(t,r.affectedParents);let a=e.collectDirty?e.collectDirty(n):$s(e.recomputeParentsFrom,n);for(let o of r.dirtySeeds)a.add(o);await we(t,a,i.has(bt.PARENT_PROGRESS),{recomputeRealWork:i.has(bt.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function eD(t,e){for(let n of e){if(t.hasChildren(n))continue;let i=t.getProgressFallback(n);i!==null&&(t.setActivityField(n,"progress",i),t.setProgressFallback(n,null))}}async function nD(t,e,n){e.has(bt.EXPECTED_PROGRESS)&&n!==null&&(iD(t.adapter)&&Di(t.adapter,n,t.defaultBaseCalendarId??null),Bn(t.adapter,n),Ue(t.adapter,t.sector.statusCriteria)),e.has(bt.REAL_COST)&&Ti(t.adapter),e.has(bt.BASELINE_VARIANCE)&&jn(t.adapter,t.sector.hoursPerDay),e.has(bt.CRITICAL_PATH)&&await $p(t.adapter,t.sector.hoursPerDay)}function iD(t){let e=!1;return t.forEachActivity(n=>{Lt(n)&&(e=!0)}),e}var rD=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),aD=new Set([D.MSO,D.MFO]);function Ei(t){return rD.has(t)}function ao(t){return t===E.CONSTRAINT_DATE}function oo(t,e,n,i){let r=n.getActivity(t);if(!r)return!1;let a=r.constraintType;if(!a||ln.has(a)||aD.has(a))return!1;let o=Pl(r.startDate),s=Pl(n.getLastStartDate(t));if(!s||!o||o.getTime()!==s.getTime())return!1;let l=oD(e,a,String(r.calendarId??""),i),c=Pl(r.constraintDate);return sD(c,l)?!1:(n.setActivityField(t,"constraintDate",l),!0)}function oD(t,e,n,i){if(t===null)return null;let r=i.getCalendar(n);return r?fe(t,r,e):t}function Pl(t){if(t instanceof Date)return t;if(typeof t=="string"||typeof t=="number"){let e=new Date(t);return Number.isNaN(e.getTime())?null:e}return null}function sD(t,e){return t===null&&e===null?!0:t===null||e===null?!1:t.getTime()===e.getTime()}async function so(t,{postMutationArgs:e,revertTargets:n,revert:i}){let{scheduledIds:r}=await nt(t,uf(e)),a=!1;for(let{activityId:o,priorConstraintDate:s}of n){let l=i(o,s);a=a||l}if(a){let o=await nt(t,uf(e));r=cD(r,o.scheduledIds)}return Yn(e.action)&&await nt(t,lD(e)),{scheduledIds:r}}function uf(t){return{...t,options:{...t.options,skipCriticalPath:!0}}}function lD(t){return{action:t.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:t.options}}function cD(t,e){let n=new Set(t);for(let i of e)n.add(i);return[...n]}function Pi(t,e,n){let i=[];for(let{op:r,finalLinkId:a,rejected:o}of t){if(o!==null)continue;if(r.kind===Et.CREATE){if(!a)continue;let d=n.getLink(a);if(!d)continue;let u=e.get(a);if(u){let p={};String(u.source)!==String(d.source)&&(p.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(p.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(p.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(p.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(p).length>0&&i.push({id:String(a),kind:x.UPDATED,fields:p,after:zt(d)});continue}i.push({id:String(a),kind:x.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:zt(d)});continue}if(r.kind===Et.DELETE){if(n.getLink(r.linkId))continue;let d=e.get(r.linkId);i.push({id:String(r.linkId),kind:x.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=e.get(r.linkId),l=n.getLink(r.linkId);if(!l)continue;let c={};s&&String(s.source)!==String(l.source)&&(c.source={before:String(s.source),after:String(l.source)}),s&&String(s.target)!==String(l.target)&&(c.target={before:String(s.target),after:String(l.target)}),s&&s.type!==l.type&&(c.type={before:s.type,after:l.type}),s&&Number(s.lag)!==Number(l.lag)&&(c.lag={before:Number(s.lag),after:Number(l.lag)}),i.push({id:String(r.linkId),kind:x.UPDATED,fields:c,after:zt(l)})}return i}function Ri(t,e){let n=new Map;if(!t.getActivity(e))return n;for(let i of t.getIncomingLinkIds(e)){let r=t.getLink(i);r&&n.set(String(r.id),Number(r.lag))}return n}function ki(t,e,n){let i=[];if(!e.getActivity(n))return i;for(let r of e.getIncomingLinkIds(n)){let a=e.getLink(r);if(!a)continue;let o=t.get(String(a.id));o===void 0||o===Number(a.lag)||i.push({id:String(a.id),kind:x.UPDATED,fields:{lag:{before:o,after:Number(a.lag)}},after:zt(a)})}return i}function pf(t,e){typeof t=="string"&&t.length>0&&e.releaseCustomId(t)}function lo(t,e){return pp.has(e)?t.p6?.[e]:Reflect.get(t,e)}var Jt={MOVE:"move",RESIZE_START:"resize-start",RESIZE_END:"resize-end"},dD=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Rl=(t,e)=>t===null?e:Math.min(t,e),kl=(t,e)=>t===null?e:Math.max(t,e);function yf(t,e,n){let i=[...new Set(e.kind===Jt.MOVE?e.activityIds.map(String):[String(e.activityId)])];if(i.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let r=uD(t,e,i);return pD(t,i,r),{getDates(a,o){if(n(),!Number.isFinite(o))throw new Error("[ScheduleCore] invalid date gesture edge");let s=r.get(String(a));if(!s)return null;let l=yD(s,o),c=hD(s,o);if(l===null||c===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:l,endTimeMs:c}}}}function uD(t,e,n){let i=new Map,r=e.kind===Jt.MOVE?String(e.anchorActivityId):null,a=r===null?null:ff(t,r);if(r!==null&&!n.includes(r))throw new Error("[ScheduleCore] move anchor is not a participant");for(let o of n){let s=ff(t,o);if(e.kind===Jt.MOVE){let l=a.startDate.getTime();i.set(o,{constantStart:null,variableStartOffset:s.startDate.getTime()-l,constantEnd:null,variableEndOffset:s.endDate.getTime()-l})}else e.kind===Jt.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 pD(t,e,n){let i=cr(t,new Set(e));for(let r of i){let a=dD();for(let o of t.getChildren(r)){let s=n.get(o);if(s){fD(a,s);continue}let l=t.getActivity(o);if(!l)throw new Error(`[ScheduleCore] missing child ${o} while previewing parent ${r}`);a.constantStart=Rl(a.constantStart,l.startDate.getTime()),a.constantEnd=kl(a.constantEnd,l.endDate.getTime())}n.set(r,a)}}function ff(t,e){let n=t.getActivity(e);if(!n)throw new Error(`[ScheduleCore] missing date gesture activity ${e}`);if(t.hasChildren(e))throw new Error(`[ScheduleCore] summary activity ${e} cannot be dragged directly`);return n}function fD(t,e){e.constantStart!==null&&(t.constantStart=Rl(t.constantStart,e.constantStart)),e.variableStartOffset!==null&&(t.variableStartOffset=Rl(t.variableStartOffset,e.variableStartOffset)),e.constantEnd!==null&&(t.constantEnd=kl(t.constantEnd,e.constantEnd)),e.variableEndOffset!==null&&(t.variableEndOffset=kl(t.variableEndOffset,e.variableEndOffset))}function yD(t,e){if(t.variableStartOffset===null)return t.constantStart;let n=e+t.variableStartOffset;return t.constantStart===null?n:Math.min(t.constantStart,n)}function hD(t,e){if(t.variableEndOffset===null)return t.constantEnd;let n=e+t.variableEndOffset;return t.constantEnd===null?n:Math.max(t.constantEnd,n)}function Gn(t,e,n){return t!==void 0&<(e)?n===Jt.RESIZE_END?t.executionStatus===et.COMPLETED?at("data_date_activity_completed","data_date_edit_rejected"):X():t.actualStart===null?X():at("data_date_actual_start_locked","data_date_edit_rejected"):X()}var mD=new Set([ye.HAS_PROGRESS,ye.COMPLETED]),gD={[E.START_DATE]:Jt.MOVE,[E.END_DATE]:Jt.RESIZE_END};function co(t,e,n,i){let r=e.p6;if(!(r!==void 0&<(n))||!t.allowed&&!mD.has(t.reason))return t;if(i===E.PROGRESS&&r.percentCompleteType===ht.UNITS)return at(ye.DATA_DATE_UNITS_PERCENT_READ_ONLY,Ba.DATA_DATE_UNITS_PERCENT_READ_ONLY);let o=gD[i];return o===void 0?X():Gn(r,n,o)}var AD=100,ID=2;function mf(t,e,n,i,r){let{progress:a}=i,o=i.writesProgress?{activityPercentComplete:a}:{};if(e.executionStatus===et.COMPLETED)return a>=100?n:Li(n,{actualFinish:null,...o},wt.UNCOMPLETE);if(e.executionStatus===et.IN_PROGRESS)return a<100?Li(n,o):hf(n,{actualFinish:t.endDate,...o},o,i,r);if(a===0)return n;let s={actualStart:t.startDate};return a<100?Li(n,{...s,...o},wt.START_ON_PROGRESS):hf(n,{...s,actualFinish:t.endDate,...o},{...s,...o},i,r)}function hf(t,e,n,i,r){return i.explicitCompletion||yr(wt.COMPLETE_ON_PROGRESS,r)?Li(t,e):yr(wt.KEEP_IN_PROGRESS,r)?Li(t,n):{...Li(t,e,wt.COMPLETE_ON_PROGRESS),confirmationAlternative:{kind:wt.KEEP_IN_PROGRESS,effects:n}}}function Li(t,e,n){return Object.keys(e).length===0?t:{...t,dataDatePatch:e,...n===void 0?{}:{confirmation:n}}}function Ol(t){switch(t.percentCompleteType){case ht.PHYSICAL:return Ll(t.physicalPercentComplete);case ht.UNITS:return Ll(t.unitsPercentComplete);default:return SD(t)}}function SD(t){if(t.remainingDurationHours===null)return null;if(t.originalDurationHours===0)return t.executionStatus===et.COMPLETED?100:0;let e=(t.originalDurationHours-t.remainingDurationHours)/t.originalDurationHours;return Ll(Math.min(100,Math.max(0,e*AD)))}function Ll(t){return Number(t.toFixed(ID))}function Oi(t,e,n,i,r){let a=t.canEdit(e,n.ctx.hierarchy,r);return n.dataDateCapability===null?a:co(a,e,n.dataDateSettings,i)}function Af(t,e){return e?{...t,dataDatePatch:{...t.dataDatePatch,...e.dataDatePatch}}:t}function vD(t){return t.eventSource==="sir-apply"&&t.edits.some(e=>e.column==="actualStart"||e.column==="actualFinish")}function If(t){if(!vD(t))return t.edits.map(i=>[i]);let e=new Map;for(let i of t.edits){if(i.column!=="actualStart"&&i.column!=="actualFinish")continue;let r=String(i.activityId),a=e.get(r)??[];a.push(i),e.set(r,a)}let n=new Map;for(let i of e.values())i.length!==2||i[0].column===i[1].column||i.every(r=>r.newValue instanceof Date)&&(n.set(i[0],i),n.set(i[1],[]));return t.edits.flatMap(i=>{let r=n.get(i);return r?.length===0?[]:[r??[i]]})}function Sf(t,e){let n=new Map;for(let i of CD(t)){let r=e.ctx.activityReader.getActivity(i);if(!r)continue;let a=Gn(r.p6,e.dataDateSettings,Jt.RESIZE_START);a.allowed||n.set(i,Nl(a))}return n}function CD(t){let e=new Map;for(let i of t){let r=String(i.activityId),a=e.get(r)??new Set;a.add(i.column),e.set(r,a)}let n=new Set;for(let[i,r]of e)r.has(E.START_DATE)&&r.has(E.END_DATE)&&n.add(i);return n}function Nl(t){return{accepted:!1,reason:t.reason,...t.alertKey?{alertKey:t.alertKey}:{}}}var DD={patch:{},needsAutoSchedule:!1,postProcessors:[]};function vf(t,e,n,i,r){return i.dataDateCapability!==null&<(i.dataDateSettings)?St(t,i.ctx.hierarchy)?{accepted:!1,reason:ye.SUMMARY,alertKey:"summary_column_value"}:t.p6===void 0?null:$n(t,n??DD,i,E.PROGRESS,r,{progress:e,explicitCompletion:!0,writesProgress:n!==null}):null}function $n(t,e,n,i,r,a){let o=ED(t,_D(t,e,i),n,i,r,a);if(o===null)return bl(_.INVALID_VALUE);if("accepted"in o)return o;if(o.dataDatePatch===void 0)return gf(o);if(t.p6===void 0||n.dataDateCapability===null)return bl(_.INVALID_VALUE);if(o.confirmation!==void 0&&!yr(o.confirmation,r))return{accepted:!1,reason:_.CONFIRMATION_REQUIRED,confirmation:{kind:o.confirmation,activityId:t.id,effects:o.dataDatePatch,...o.confirmationAlternative===void 0?{}:{alternative:o.confirmationAlternative}}};try{let l=n.dataDateCapability.prepareActivityUpdate(t.p6,o.dataDatePatch,o.patch.constraintType??t.constraintType),c=ND(t,l.next,n);return gf(TD(t,{...o,patch:{...o.patch,...c.patch},dataDateState:c.p6},l.next,n,i))}catch{return bl(_.INVALID_VALUE)}}function TD(t,e,n,i,r){if(r===E.PROGRESS||t.p6===void 0||!lt(i.dataDateSettings))return e;let a=Ol(n);return a===null||a===t.progress||a===Ol(t.p6)||!Ai.canEdit(t,i.ctx.hierarchy).allowed?e:{...e,patch:{...e.patch,progress:a}}}function gf(t){return{accepted:!0,changes:t}}function bl(t){return{accepted:!1,reason:t}}function _D(t,e,n){let i=t.p6,r=e.patch.constraintType;return!(n===E.CONSTRAINT_TYPE&&i!==void 0&&r!==void 0)||Si(r,i.secondaryConstraintType)?e:{...e,dataDatePatch:{secondaryConstraintType:null,secondaryConstraintDate:null},confirmation:wt.CLEAR_SECONDARY_CONSTRAINT}}function ED(t,e,n,i,r,a){let o=t.p6;return o!==void 0&&n.dataDateCapability!==null&<(n.dataDateSettings)?i===E.PHYSICAL_PERCENT_COMPLETE?RD(t,o,e):i===E.PROGRESS?PD(t,o,e,r,a):i===E.DURATION?kD(o,e):i===E.END_DATE?LD(t,o,e,n):i===E.START_DATE?bD(o,e,n):e:e}function PD(t,e,n,i,r){let a=n.patch.progress,o=r??(typeof a=="number"?{progress:a,explicitCompletion:!1,writesProgress:!0}:void 0);return o===void 0?n:mf(t,e,n,o,i)}function RD(t,e,n){let i=n.dataDatePatch?.physicalPercentComplete;return e.executionStatus!==et.NOT_STARTED||i===void 0||i<=0?n:{...n,dataDatePatch:{actualStart:t.startDate,physicalPercentComplete:i},confirmation:wt.START_ON_PROGRESS}}function kD(t,e){let n=e.patch.durationHours;return typeof n!="number"?null:t.executionStatus===et.NOT_STARTED?{...e,dataDatePatch:{originalDurationHours:n,remainingDurationHours:n}}:{...e,patch:{durationHours:n},dataDatePatch:{originalDurationHours:n}}}function LD(t,e,n,i){let r=Gn(e,i.dataDateSettings,Jt.RESIZE_END);if(!r.allowed)return Nl(r);let a=n.patch.endDate,o=i.ctx.calendars.getCalendar(t.calendarId);if(!(a instanceof Date)||o===null)return null;let s=i.dataDateCapability?.prepareFinishEdit(e,a,o);return s==null?null:{...n,patch:OD(n.patch),dataDatePatch:s}}function OD(t){let{constraintType:e,constraintDate:n,...i}=t;return i}function bD(t,e,n){let i=Gn(t,n.dataDateSettings,Jt.MOVE);return i.allowed?e:Nl(i)}function ND(t,e,n){let i=n.dataDateSettings,r=n.ctx.calendars.getCalendar(t.calendarId);if(!lt(i)||r===null)return{p6:e,patch:{}};let a=n.dataDateCapability.projectLocalActivity(t.p6,e,{calendar:r,dataDate:i.dataDate,totalFloatMethod:i.totalFloatMethod});return{p6:a.p6,patch:{...a.startDate===void 0?{}:{startDate:a.startDate},...a.endDate===void 0?{}:{endDate:a.endDate}}}}async function Cf(t,e,n){let{adapter:i,ctx:r,scheduler:a,sector:o}=n,s=_e(t.column);if(!s)return{ok:!1,reason:_.NO_PIPELINE_FOR_COLUMN};t.column===E.DURATION&&a.invalidateExpandedLinksCache();let l=r.activityReader.getActivity(t.activityId);if(!l)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let c=Oi(s,l,n,t.column);if(!c.allowed)return{ok:!1,reason:c.reason??_.CANNOT_EDIT,alertKey:c.alertKey};let d=s.parseInput(t.newValue,l,r);if(!d.ok)return{ok:!1,reason:d.reason??_.PARSE_ERROR};let u=lo(l,s.targetField),p=s.validate(l,u,d.value,r);if(!p.valid)return{ok:!1,reason:p.reason??_.INVALID,alertKey:p.notification?.messageKey};if(t.column===E.CUSTOM_ID&&d.value!==null){let O=i.getActivity(t.activityId),M=O?O.customId:null,j=typeof M=="string"?M:null;if(n.customIdTracker.isCustomIdInUse(String(d.value),j))return{ok:!1,reason:_.CUSTOM_ID_DUPLICATE}}let f=s.transform(l,d.value,r,d.raw),y=$n(l,f,n,t.column,e.confirmations);if(!y.accepted)return{ok:!1,reason:y.reason,...y.alertKey?{alertKey:y.alertKey}:{},...y.confirmation?{confirmation:y.confirmation}:{}};let m=y.changes,h=fn(t.activityId,m),A=await ot(i,h),T=Ri(i,String(t.activityId)),b=l.constraintDate;yn(i,t.activityId,m),an(t.activityId,m.postProcessors??[],i,A.get(String(t.activityId))??null);let S=ki(T,i,String(t.activityId));if(t.column===E.CUSTOM_ID){let O=A.get(String(t.activityId)),M=O?O.customId:null,j=typeof M=="string"?M:null,z=typeof d.value=="string"?d.value:null;j!==z&&n.customIdTracker.trackCustomIdChange(j,z)}let g=()=>({action:t,autoscheduleFrom:m.needsAutoSchedule?String(t.activityId):null,recomputeParentsFrom:[],collectDirty:O=>Ja(t.activityId,h,O),now:n.now,options:e}),w=Ei(t.column),{scheduledIds:R}=await(w?so({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{postMutationArgs:g(),revertTargets:ao(t.column)?[]:[{activityId:t.activityId,priorConstraintDate:b}],revert:(O,M)=>oo(O,M,i,r.calendars)}):nt({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},g())),L=(m.trackingEvents??[]).map(O=>({name:O.name,properties:O.properties??{}}));s.trackEvent&&!(t.column===E.PROGRESS&&Number(d.value)<=0)&&L.unshift({name:s.trackEvent,properties:{activity_name:l.name,activity_id:l.id,activity_index:l.correlativeId}});let P=Hn(t.activityId,m.constraintWarning);return{ok:!0,changes:await G(i,{source:t,beforeSnap:A,touchedIds:h,scheduledIds:R,sirDetection:Bt.BEFORE_DIFF,links:S,trackingEvents:L,...P?{warnings:[P]}:{},hoursPerDay:o.hoursPerDay})}}function uo(t){return Jr(t)}function po(t,e){return Object.hasOwn(t,e)}function FD(t){if(t.kind===I.LINK_CREATE)return uo(t.type)?t.lag===void 0||Number.isFinite(t.lag)?null:_.INVALID_LINK_LAG:_.INVALID_LINK_TYPE;if(t.kind===I.LINK_UPDATE){if(po(t,"type")&&!uo(t.type))return _.INVALID_LINK_TYPE;if(po(t,"lag")&&!Number.isFinite(t.lag))return _.INVALID_LINK_LAG}return null}function wD(t){return t.kind===ut.CREATE?uo(t.type)?t.lag===void 0||Number.isFinite(t.lag)?null:_.INVALID_LINK_LAG:_.INVALID_LINK_TYPE:t.kind===ut.UPDATE?po(t,"type")&&!uo(t.type)?_.INVALID_LINK_TYPE:!po(t,"lag")||Number.isFinite(t.lag)?null:_.INVALID_LINK_LAG:t.kind===ut.DELETE?null:_.INVALID_VALUE}function xD(t){for(let e of t){let n=wD(e);if(n!==null)return n}return null}function MD(t,e){let n=new Set,i=new Map;for(let r of t){if(r.kind===ut.CREATE){n.add(String(r.source)),n.add(String(r.target));continue}let a=e.getLink(r.linkId);a&&(n.add(String(a.source)),n.add(String(a.target)),r.kind===ut.UPDATE&&(r.source!==void 0&&n.add(String(r.source)),r.target!==void 0&&n.add(String(r.target))),i.set(r.linkId,{...a}))}return{activityIds:n,links:i}}function UD(t,e,n,i,r=!1){return t.map((a,o)=>{let s=a.kind===ut.CREATE?i?.get(o):void 0,l=en(a,{port:e,newLinkId:s?()=>s:n.next,rejectParentLinkMutations:r});return{op:a,finalLinkId:l.applied?l.linkId:null,rejected:l.applied?null:l.rejected??_.INVALID}})}function HD(t){return new Map([...t].map(([e,n])=>[String(e),n]))}async function Df(t,e,n){let i=FD(t);return i!==null?{ok:!1,reason:i}:Fl([YD(t,n.sector.hoursPerDay)],t,e,n,t.kind===I.LINK_CREATE&&t.linkId?new Map([[0,t.linkId]]):void 0)}async function Tf(t,e,n){let i=xD(t.operations);if(i!==null)return{ok:!1,reason:i};let{hoursPerDay:r}=n.sector,a=t.operations.map(s=>WD(s,r)),o=BD(t.operations);return Fl(a,t,e,n,o)}function BD(t){let e=new Map;return t.forEach((n,i)=>{n.kind===ut.CREATE&&n.linkId&&e.set(i,n.linkId)}),e.size>0?e:void 0}function jD(t,e){if(t===void 0)return;let n=new Map,i=new Set,r=()=>{let a=e.linkIdGen.next();for(;e.adapter.getLink(a)!==null||e.isLinkIdReserved(String(a))||i.has(String(a));)a=e.linkIdGen.next();return a};for(let[a,o]of t){let s=e.adapter.getLink(o)!==null||e.isLinkIdReserved(String(o))||i.has(String(o)),l=s?r():o;s||e.linkIdGen.bump(o),i.add(String(l)),n.set(a,l)}return n}function WD(t,e){return t.kind===ut.CREATE?{kind:ut.CREATE,source:t.source,target:t.target,type:t.type,lag:ne(t.lag??0,e)}:t.kind===ut.UPDATE?{kind:ut.UPDATE,linkId:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lag===void 0?void 0:ne(t.lag,e)}:{kind:ut.DELETE,linkId:t.linkId}}async function Fl(t,e,n,i,r){let{adapter:a,scheduler:o,sector:s,linkIdGen:l}=i;o.invalidateAllCaches();let{activityIds:c,links:d}=MD(t,a),u=await ot(a,c),p=UD(t,a,l,jD(r,i),n.rejectParentLinkMutations);if(t.length===1&&p[0]&&p[0].rejected!==null&&e.kind!==I.INLINE_EDIT)return{ok:!1,reason:p[0].rejected};let f=VD(p,d,a),{scheduledIds:y,warnings:m}=await nt({adapter:a,scheduler:o,sector:i.sector,defaultBaseCalendarId:i.defaultBaseCalendarId},{action:e,autoscheduleFrom:f,recomputeParentsFrom:c,now:i.now,options:n}),h=Pi(p,d,a);return{ok:!0,linkVerdicts:p.map((A,T)=>A.rejected===null?{operationIndex:T,kind:A.op.kind,ok:!0,linkId:String(A.finalLinkId)}:{operationIndex:T,kind:A.op.kind,ok:!1,reason:A.rejected}),__beforeLinks:HD(d),changes:await G(a,{source:e,beforeSnap:u,touchedIds:c,scheduledIds:y,links:h,warnings:m,hoursPerDay:s.hoursPerDay})}}function VD(t,e,n){for(let i of t){if(i.rejected!==null)continue;let r=KD(i.op,e,n);if(r!==null)return n.hasChildren(r)?vt.ROOTS:String(r)}return null}function KD(t,e,n){return t.kind===ut.CREATE?t.target:t.kind===ut.DELETE?e.get(t.linkId)?.target??null:n.getLink(t.linkId)?.target??null}function YD(t,e){return t.kind===I.LINK_CREATE?{kind:ut.CREATE,source:t.source,target:t.target,type:t.type,lag:ne(t.lag??0,e)}:t.kind===I.LINK_UPDATE?{kind:ut.UPDATE,linkId:t.linkId,source:t.source,target:t.target,type:t.type,lag:t.lag===void 0?void 0:ne(t.lag,e)}:{kind:ut.DELETE,linkId:t.linkId}}async function _f(t,e,n){let{adapter:i,sector:r}=n;if(typeof t.newValue!="string")return{ok:!1,reason:_.INVALID_VALUE};if(!i.getActivity(t.activityId))return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let o=t.column===E.CUSTOM_PREDECESSORS,{specs:s,errors:l}=Ra(t.newValue,{daysPerWeek:r.hoursPerWeek/r.hoursPerDay});if(l.length>0)return{ok:!1,reason:_.INVALID_VALUE};let c=s.map(m=>({...m,lag:ne(ba(m.lag),r.hoursPerDay)})),d=new Map;i.forEachActivity(m=>{m.correlativeId!=null&&d.set(String(m.correlativeId),m.id)});let u=m=>d.get(m)??null,p=o?i.getIncomingLinkIds(t.activityId):i.getOutgoingLinkIds(t.activityId),f=[];for(let m of p){let h=i.getLink(m);h&&f.push(h)}let y=o?La({targetActivityId:t.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:u}):Oa({sourceActivityId:t.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:u});return Fl(y.operations,t,e,n)}var se={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 xt(t){t.invalidateVisualOrderIds?.();let e=[];t.forEachActivity(a=>{V(a.parentId)&&e.push(a)}),e.sort(Rf);let n=[];Ef(n,e);let i=[],r=0;for(;n.length>0;){let a=n.pop();if(a.correlativeId!==r){let s=typeof a.correlativeId=="number"?a.correlativeId:void 0;i.push({activityId:String(a.id),before:s}),s!==void 0&&t.noteCorrelativeBefore?.(String(a.id),s),GD(a,r)}r+=1;let o=er(String(a.id),t);o.sort(Rf),Ef(n,o)}return i}function Ef(t,e){for(let n=e.length-1;n>=0;n-=1)t.push(e[n])}function Pf(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:Ts}var Rf=(t,e)=>Pf(t)-Pf(e);function GD(t,e){t.correlativeId=e}function wl(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let{workHours:i,realWorkHours:r}=Of(n,e);e.setActivityField(n,U.WORK_HOURS,i),e.setActivityField(n,U.REAL_WORK_HOURS,r);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||V(o))break;n=o}}function kf(t,e){let n=e.getActivity(t);if(!n)return;let i=n.parentId;!i||V(i)||wl(i,e)}function Lf(t,e,n){for(let i of t){if(n.hasChildren(i))continue;let r=n.getActivity(i);r&&n.setActivityField(i,U.REAL_WORK_HOURS,$t(Tr(r,U.WORK_HOURS),Tr(r,U.PROGRESS)))}for(let i of e)n.setActivityField(i,U.REAL_WORK_HOURS,Of(i,n).realWorkHours)}function Of(t,e){let n=0,i=0;for(let r of e.getChildren(t)){let a=e.getActivity(r);if(!a)continue;let o=Tr(a,U.WORK_HOURS);n+=o,i+=$D(r,a,o,e)}return{workHours:n,realWorkHours:i}}function Tr(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function $D(t,e,n,i){return i.hasChildren(t)?Tr(e,U.REAL_WORK_HOURS):$t(n,Tr(e,U.PROGRESS))}function xl(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let i=e.getChildren(n),r=0;for(let s of i){let l=e.getActivity(s);l&&(r+=qD(l,U.USED_COST))}e.setActivityField(n,U.USED_COST,r);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||V(o))break;n=o}}function bf(t,e){let n=e.getActivity(t);if(!n)return;let i=n.parentId;!i||V(i)||xl(i,e)}function qD(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}function Ml(t,e){if(!t||t==="0")return;let n=String(t);for(;n!==null;){let i=e.getChildren(n),r=0;for(let s of i){let l=e.getActivity(s);l&&(r+=zD(l,U.COST))}e.setActivityField(n,U.COST,r);let a=e.getActivity(n);if(!a)break;let o=a.parentId;if(!o||V(o))break;n=o}}function Nf(t,e){let n=e.getActivity(t);if(!n)return;let i=n.parentId;!i||V(i)||Ml(i,e)}function zD(t,e){let n=t[e];return typeof n=="number"&&Number.isFinite(n)?n:0}var fo=Object.freeze({proplannerId:null,description:"",type:k.TASK,progress:0,constraintType:D.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,baselineVarianceDays:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),Ff="New Master Plan",wf="New Activity";var JD=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],yo=new Set(JD);function XD(t){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let n of Reflect.ownKeys(t))if(typeof n=="symbol"||!yo.has(n))throw new Error(`activity-create: rejected override key "${String(n)}" \u2014 not a creation-writable canonical field`);return t}function xf(t,e){let n=t.parentId!=null?e.getActivity(t.parentId):null,i=XD(t.activityOverrides??{}),r=t.numTasksInGantt===0?Ff:wf,a=i.name??r,o=i.durationHours??t.sector.hoursPerDay,s=i.calendarId??t.sector.defaultCalendar,l=ZD(n,t.fallbackStartDate,i.startDate),c={...fo,...i,id:t.id,parentId:t.parentId,uniqueCorrelativeId:t.nextUniqueCorrelativeId,name:a,durationHours:o,calendarId:s,startDate:l,endDate:l},d=i.startDate?new Date(c.startDate):e.getClosestWorkTime({date:c.startDate,dir:q.FUTURE,task:c});if(!i.startDate&&n&&Ne(n.type)){let f=new Date(n.startDate);f.setUTCHours(0,0,0,0);let y=new Date(d);y.setUTCHours(0,0,0,0),y.getTime()!==f.getTime()&&(d=e.getClosestWorkTime({date:f,dir:q.FUTURE,task:c}))}let u=e.calculateEndDate({startDate:d,durationHours:c.durationHours,task:c});return{newTask:{...c,startDate:d,endDate:u,calendarDuration:Te({type:c.type,startDate:d,endDate:u}),newActivityIds:[...c.newActivityIds],pendingRequestIds:[...c.pendingRequestIds],responsableIds:[...c.responsableIds],tagIds:[...c.tagIds],baselinePoints:[...c.baselinePoints]}}}function ZD(t,e,n){return n?new Date(n):t?new Date(t.startDate):e?new Date(e):new Date}function bi(t,e,n,i){let r=e,a=r==="0",o=Ul(t,r);if(i!==void 0){let l=o.find(c=>c.id===i);if(l){let c=jt(l),d=o.map(jt).filter(p=>p<c);return d.length===0?c-1:(Math.max(...d)+c)/2}}if(n!==void 0){let l=o.find(c=>c.id===n);if(l){let c=jt(l),d=o.map(jt).filter(p=>p>c);if(d.length===0)return c+1;let u=Math.min(...d);return(c+u)/2}}return o.length===0?0:Math.max(...o.map(jt))+1}var qn=Number.MAX_SAFE_INTEGER,Mf=Number.MAX_SAFE_INTEGER-1;function jt(t){let e=t.correlativeId,n=typeof e=="number"?e:Number(e);return Number.isFinite(n)?n:qn}function Ul(t,e){return er(e,t)}function Uf(t,e,n){let i=t,r=Pe(t,n);for(;r!=null&&e.has(r);)i=r,r=Pe(r,n);return i}function Ni(t,e,n){let i=new Set([t]),r=de(n.getActivity(t)?.parentId);for(;r!=="0"&&!i.has(r);){if(e.has(r))return!0;i.add(r),r=de(n.getActivity(r)?.parentId)}return!1}function Pe(t,e){let n=e.getActivity(t);if(!n)return null;let i=de(n.parentId),r=ee(i,e),a=r.findIndex(o=>String(o)===String(t));return a<=0?null:r[a-1]??null}function Hf(t,e,n,i){let r=ee(e,t).filter(l=>String(l)!==String(i)).map(l=>t.getActivity(l)).filter(l=>l!==null);if(r.length===0)return 0;let a=r.map(jt);if(n<=0)return a[0]-1;if(n>=a.length)return a[a.length-1]+1;let o=a[n-1],s=a[n];return(o+s)/2}var QD=new Set([...[...yo].filter(t=>t!==U.DURATION_HOURS),"durationDays"]);function ho(t,e){if(t===void 0)return{ok:!0,value:{}};let n=Object.getPrototypeOf(t);if(n!==null&&n!==Object.prototype)return{ok:!1,reason:_.INVALID_VALUE};for(let a of Reflect.ownKeys(t))if(typeof a=="symbol"||!QD.has(a))return{ok:!1,reason:_.INVALID_VALUE};let{durationDays:i,...r}=t;return i!==void 0&&(!Number.isFinite(i)||i<0)?{ok:!1,reason:_.INVALID_VALUE}:{ok:!0,value:{...r,...i===0&&(r.type===void 0||r.type===k.TASK)?{type:k.MILESTONE}:{},...i===void 0?{}:{durationHours:wn(i,e)}}}}function Kt(t,e){wl(t,e),xl(t,e),Ml(t,e)}function mo(t,e){let n=new Set,i=[];for(let r of t){let a=String(r);n.has(a)||(n.add(a),i.push(a))}for(;i.length>0;){let r=i.pop(),a=e.getChildren(r);for(let o of a){let s=String(o);n.has(s)||(n.add(s),i.push(s))}}return n}function go(t,e){let n=new Set;for(let i of t){for(let r of e.getOutgoingLinkIds(i))n.add(String(r));for(let r of e.getIncomingLinkIds(i))n.add(String(r))}return[...n]}function tT(t){return t?{type:t.type,startDate:new Date(t.startDate),endDate:new Date(t.endDate),durationHours:t.durationHours,expectedProgressBaseline:t.expectedProgressBaseline,constraintType:t.constraintType,constraintDate:t.constraintDate?new Date(t.constraintDate):null,progress:t.progress}:null}function eT(t,e,n){let i=t.startDate;return!n||!(i instanceof Date)?{}:{endDate:n(i,e)}}function mn(t){if(t.remainingChildIds.length>0)return null;let e=t.parent,n=t.defaultDurationHours,i=Number.isFinite(n),r=tT(t.promotionSnapshot)??(i?{type:li,durationHours:n,progress:0,autoScheduling:!0,constraintType:D.ASAP,constraintDate:null,hasNewActivities:!1,...eT(e,n,t.computeEndDate)}:{type:li});if(t.idsRemoved&&t.idsRemoved.size>0){let o=Array.isArray(e.newActivityIds)?e.newActivityIds:[];if(o.length>0){let s=o.filter(l=>!t.idsRemoved.has(l)&&!t.idsRemoved.has(String(l)));s.length!==o.length&&(r.newActivityIds=s)}}e.hasLookaheadTasks&&(r.isLookahead=!0);let a=nT(e,r);return t.dataDateCapability&&a&&Object.assign(r,t.dataDateCapability.parentDemoted({activity:a,hasCompleteSchedulingState:t.hasCompleteSchedulingState===!0,promotionSnapshot:t.promotionSnapshot})),{parentId:String(e.id),fields:r}}function nT(t,e){let n=e.startDate??t.startDate,i=e.endDate??t.endDate,r=e.durationHours??t.durationHours,a=e.progress??t.progress,o=e.type??t.type;return!(n instanceof Date)||!(i instanceof Date)||typeof r!="number"||typeof a!="number"?null:{type:o,startDate:n,endDate:i,durationHours:r,progress:a}}function Ao(t){if(t.idsRemoved.size===0)return null;let e=t.parent.newActivityIds;if(!Array.isArray(e)||e.length===0)return null;let n=e,i=n.filter(r=>!t.idsRemoved.has(r)&&!t.idsRemoved.has(String(r)));return i.length===n.length?null:{parentId:String(t.parent.id),fields:{newActivityIds:[...i],hasNewActivities:i.length>0}}}var Bf=200;async function jf(t,e,n){let{adapter:i,scheduler:r,customIdTracker:a,sector:o}=n;if(r.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:_.ACTIVITY_IDS_EMPTY};for(let L of t.activityIds)if(!i.getActivity(L))return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let s=t.activityIds.filter(L=>{let P=i.getActivity(L);return!(P?.correlativeId===0&&P.type===k.PROJECT)}),l=mo(s,i),c=go(l,i),d=new Set;for(let L of t.activityIds){let P=i.getActivity(L);if(!P)continue;let O=P.parentId;if(V(O))continue;let M=String(O);l.has(M)||d.add(M)}let u=new Set([...l,...d]),p=await ot(i,u),f=new Map;for(let L of c){let P=i.getLink(L);P&&f.set(L,{...P})}let y=new Set,m=0;for(let L of l){m+=1,m%Bf===0&&await mt();let P=i.getActivity(L);if(!P)continue;let O=V(P.parentId)?null:i.getActivity(String(P.parentId)),M=O?.hasNewActivities===!0&&O.newActivityIds.some(z=>String(z)===String(L));(P.isNewActivity===!0||M)&&y.add(L);let j=P.customId;typeof j=="string"&&j.length>0&&a.releaseCustomId(j)}for(let L of c)i.removeLink(L);let h=_r(i,l),A=0;for(let L of l)A+=1,A%Bf===0&&await mt(),i.removeActivity(L);for(let L of d){let P=i.getActivity(L);if(!P)continue;iT(P,y,i);let O=i.getChildren(L),M=mn({parent:P,remainingChildIds:O.map(String),defaultDurationHours:o.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(L),computeEndDate:(j,z)=>i.calculateEndDate({startDate:j,durationHours:z,task:P}),idsRemoved:l,dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(!M){Fa(L,i);continue}if(i.setActivityFields(L,M.fields),P.customId==null||P.customId===""){let j=Pe(L,i),z=j?i.getActivity(j)?.customId:null,ft=a.generateCustomIdForRestoredChild(typeof z=="string"&&z?z:null);i.setActivityField(L,U.CUSTOM_ID,ft)}}for(let L of d)Kt(L,i);let T=xt(i),{scheduledIds:b}=await nt({adapter:i,scheduler:r,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:vt.ROOTS,recomputeParentsFrom:d,now:n.now,options:e}),S={name:se.ACTIVITY_DELETION,properties:{activity_ids:[...t.activityIds],cascade_count:l.size}};t.eventSource!==void 0&&(S.properties.event_source=t.eventSource);let g=new Map;for(let[L,P]of f)g.set(L,P);let w=new Map;for(let L of l){let P=p.get(String(L));P&&w.set(String(L),P)}let R=await G(i,{source:t,beforeSnap:p,touchedIds:u,scheduledIds:b,sirDetection:Bt.AFTER_DIFF,links:me(f),trackingEvents:[S],hoursPerDay:o.hoursPerDay,correlativeShifts:T});return{ok:!0,changes:h.length>0?{...R,viewState:h}:R,__beforeSnap:w,__beforeLinks:g}}function iT(t,e,n){let i=Ao({parent:t,idsRemoved:e});if(i)for(let[r,a]of Object.entries(i.fields))ae(n,i.parentId,r,a)}function _r(t,e){let n=[];for(let i of e){let r=t.isChecked(i),a=t.isVisible(i);!r&&a||n.push({activityId:String(i),...r?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return n}function me(t){let e=[];for(let[n,i]of t.entries())e.push({id:n,kind:x.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 e}var Fi={CREATE:"create",REPARENT:"reparent"};function rT(t,e={}){let n=t.type;if(n!==k.TASK&&n!==k.MILESTONE)return null;let i=t.startDate,r=t.endDate;return!(i instanceof Date)||!(r instanceof Date)?null:{type:n,startDate:new Date(i),endDate:new Date(r),durationHours:Number(t.durationHours??0),expectedProgressBaseline:typeof t.expectedProgressBaseline=="number"?t.expectedProgressBaseline:null,constraintType:t.constraintType??null,constraintDate:t.constraintDate instanceof Date?new Date(t.constraintDate):null,progress:Number(t.progress??0),...e}}function Wf(t){let e=t.getParent(t.parentId);if(!e)return null;let n=t.isCurrentlyLeaf!==void 0?t.isCurrentlyLeaf&&Ze(e.type):aT(e),i=Array.isArray(e.newActivityIds)?e.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:i.some(s=>String(s)===String(t.newChildId))?[...i]:[...i,t.newChildId]},o=n?t.dataDateCapability?.parentPromoted(e):void 0;return e.customId!=null&&e.customId!==""&&(a.customId=null),n&&(a.type=Ls,o&&Object.assign(a,o.activityPatch),(t.promotionSource??Fi.CREATE)===Fi.CREATE&&(a.constraintType=D.ASAP,a.constraintDate=null)),{parentId:t.parentId,fields:a,promotionSnapshot:rT(e,o?.snapshotPatch)}}function aT(t){return Ze(t.type)&&(!Array.isArray(t.newActivityIds)||t.newActivityIds.length===0)}function gn(t,e){let i=e.adapter.getActivity(t.parentId)?.customId??null,r=Wf({...t,getParent:o=>e.adapter.getActivity(o)??null,dataDateCapability:e.dataDateCapability});if(!r)return{applied:!1,removedLinks:new Map};let a=r.fields.type===k.PROJECT?oT(t.parentId,e):new Map;for(let[o,s]of Object.entries(r.fields))ae(e.adapter,r.parentId,o,s);return r.promotionSnapshot&&e.adapter.setPromotionSnapshot(r.parentId,r.promotionSnapshot),r.fields.customId===null&&e.customIdTracker.releaseCustomId(i),{applied:!0,removedLinks:a}}function oT(t,e){let n=new Map,i=new Set([...e.adapter.getIncomingLinkIds(t),...e.adapter.getOutgoingLinkIds(t)]);for(let r of i){let a=e.adapter.getLink(r);a&&(n.set(String(r),{...a}),e.adapter.removeLink(r))}return n}async function Er(t,e,n={}){let{adapter:i,scheduler:r,sector:a,calendars:o,activityIdGen:s,uidGen:l}=e;n.skipCacheInvalidation||r.invalidateAllCaches();let c=sT(t,i);if(!c.ok)return c;let{parent:d,anchorSiblingId:u,isRoot:p}=c,f=cT(t.activityId,i,s,e.isActivityIdReserved),y=l.next(),m={id:f,parentId:p?null:t.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:yT(o)},numTasksInGantt:i.activityCount(),nextUniqueCorrelativeId:y,activityOverrides:t.overrides??{}},A=xf(m,{getActivity:L=>i.getActivity(L),calculateEndDate:L=>i.calculateEndDate(L),getClosestWorkTime:L=>i.getClosestWorkTime(L)}).newTask;e.dataDateCapability!==null&&Object.assign(A,e.dataDateCapability.activityCreated({activity:A,hasCompleteSchedulingState:e.hasCompleteSchedulingState})),A.realWorkHours=$t(A.workHours,A.progress),uT(A,t,e,u,d,n);let T=n.insertionCorrelativeId??bi(i,p?"0":t.parentId,t.afterSiblingId,t.beforeSiblingId);A.correlativeId=T;let b=new Set([f]);d&&b.add(d.id);let S=d!==null&&i.getChildren(d.id).length===0,g=n.skipBeforeSnap?new Map:await ot(i,b);i.addActivity(A);let w=d?gn({parentId:d.id,newChildId:f,isCurrentlyLeaf:S},e).removedLinks:new Map;n.skipRollupCascades||(kf(f,i),bf(f,i),Nf(f,i));let R=pT(i,f,b,n);return{ok:!0,newId:f,parent:d,newActivity:A,beforeSnap:g,initialTouched:b,correlativeShifts:R,removedParentLinks:w}}function sT(t,e){let n=V(t.parentId),i=n?null:e.getActivity(t.parentId);if(!n&&!i)return{ok:!1,reason:_.PARENT_NOT_FOUND};if(i!==null&&ei(i))return{ok:!1,reason:_.PARENT_FROZEN_BY_SIR};if(t.afterSiblingId!==void 0&&t.beforeSiblingId!==void 0)return{ok:!1,reason:_.ANCHOR_SIBLING_CONFLICT};let o=t.afterSiblingId??t.beforeSiblingId,s=lT(t,e,n,o);return s||{ok:!0,parent:i,anchorSiblingId:o,isRoot:n}}function lT(t,e,n,i){if(i===void 0)return null;let r=e.getActivity(i);if(!r)return{ok:!1,reason:_.ANCHOR_SIBLING_NOT_FOUND};let a=n?"0":t.parentId;return(r.parentId==null?"0":String(r.parentId))!==a?{ok:!1,reason:_.ANCHOR_SIBLING_WRONG_PARENT}:null}function cT(t,e,n,i){let r=()=>{let a=n.next();for(;e.activityExists(a)||i(String(a));)a=n.next();return a};return t===void 0||e.activityExists(t)||i(String(t))?r():(n.bump(t),t)}function dT(t){let e=t.overrides?.customId;return typeof e=="string"?e:void 0}function uT(t,e,n,i,r,a){let{adapter:o,customIdTracker:s}=n,l=dT(e);if(l!==void 0){if(l.length===0)return;if(!s.isCustomIdInUse(l)){s.registerCustomId(l);return}}let c=a.customIdReferenceId??i,d=c!==void 0,u=d?o.getActivity(c):r;t.customId=s.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function pT(t,e,n,i){if(i.skipCorrelativeRecompute)return[];let r=xt(t).filter(a=>a.activityId!==String(e));for(let a of r)n.add(a.activityId);return r}async function fT(t,e,n,i,r){let{newId:a,newActivity:o,beforeSnap:s,initialTouched:l,correlativeShifts:c,removedParentLinks:d}=n,u={name:se.ACTIVITY_CREATION,properties:{parent_id:e.parentId,activity_id:a,created_duration:o.durationHours}};return e.eventSource!==void 0&&(u.properties.event_source=e.eventSource),G(t,{source:e,beforeSnap:s,touchedIds:l,scheduledIds:i,correlativeShifts:c,trackingEvents:[u],links:me(new Map(d)),hoursPerDay:r})}async function Vf(t,e,n){let{adapter:i,scheduler:r,sector:a}=n,o=ho(t.overrides,a.hoursPerDay);if(!o.ok)return o;let s=await Er({...t,overrides:o.value},n);if(!s.ok)return s;let{newId:l}=s,c=s.newActivity.autoScheduling;i.setActivityField(l,"autoScheduling",!1);let d;try{d=await nt({adapter:i,scheduler:r,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:l,recomputeParentsFrom:[l],preventSummaryTargetPullback:!0,now:n.now,options:e})}finally{i.setActivityField(l,"autoScheduling",c)}let{scheduledIds:u}=d;return{ok:!0,changes:await fT(i,t,s,u,a.hoursPerDay),...s.removedParentLinks.size>0?{__beforeLinks:new Map(s.removedParentLinks)}:{}}}function yT(t){for(let n of t.values())if(n.is_default)return n.id;let e=t.values().next();return!e.done&&e.value?e.value.id:"global"}async function Gf(t,e,n){let i=hT(t,n);if(i)return{ok:!1,reason:i};let r=gT(t,n);if(!r.ok)return r;let a=t.mode===Dt.REPLACE?new Set(n.adapter.getAllIds().map(S=>String(S))):new Set,o=t.mode===Dt.REPLACE?await ot(n.adapter,a):new Map,s=t.mode===Dt.REPLACE?DT(n):new Map,l=t.mode===Dt.REPLACE?_r(n.adapter,a):[];n.scheduler.invalidateAllCaches();let c=[];if(t.mode===Dt.REPLACE){for(let S of s.keys()){let g=en({kind:ut.DELETE,linkId:S},{port:n.adapter});if(!g.applied)return{ok:!1,reason:g.rejected??_.INVALID};c.push({op:{kind:ut.DELETE,linkId:S},finalLinkId:S,rejected:null})}for(let S of a){let g=n.adapter.getActivity(S)?.customId;typeof g=="string"&&g.length>0&&n.customIdTracker.releaseCustomId(g),n.adapter.removeActivity(S)}}let d=await CT(t,r.plan.items,n);if(!d.ok)return d;for(let[S,g]of d.removedParentLinks)s.set(S,g),c.push({op:{kind:ut.DELETE,linkId:S},finalLinkId:S,rejected:null});let u=$f(t)?[]:xt(n.adapter),p=new Set(r.plan.items.map(S=>String(S.activityId))),f=u.filter(S=>!p.has(S.activityId)),y=t.mode===Dt.REPLACE?new Set(a):new Set;vi(n.adapter,u,p,o,y);for(let S of r.plan.items)y.add(String(S.activityId));let m=r.plan.links.map(S=>({operation:{kind:ut.CREATE,source:S.source,target:S.target,type:S.type,lag:ne(S.lag??0,n.sector.hoursPerDay)},linkId:S.linkId})),h=_a(m,{port:n.adapter,preserved:s,rejectParentLinkMutations:e.rejectParentLinkMutations??!1});if(!h.applied)return{ok:!1,reason:h.rejected??_.INVALID};for(let{operation:S,linkId:g}of m)c.push({op:S,finalLinkId:g,rejected:null});let A=r.plan.items.map(S=>S.activityId),{scheduledIds:T}=await nt({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:t.items.length>0||t.links.length>0?vt.ROOTS:null,recomputeParentsFrom:A,now:n.now,options:e}),b=await G(n.adapter,{source:t,beforeSnap:o,touchedIds:y,scheduledIds:T,links:Pi(c,s,n.adapter),hoursPerDay:n.sector.hoursPerDay,correlativeShifts:f,...t.mode===Dt.REPLACE?{sirDetection:Bt.AFTER_DIFF}:{}});return{ok:!0,changes:l.length>0?{...b,viewState:l}:b,...t.mode===Dt.REPLACE||s.size>0?{...t.mode===Dt.REPLACE?{__beforeSnap:o}:{},__beforeLinks:TT(s)}:{}}}function hT(t,e){if(t.mode!==Dt.APPEND&&t.mode!==Dt.REPLACE)return _.INVALID;let n=new Set,i=new Set;for(let a of t.items){if(a.batchId.length===0||n.has(a.batchId))return _.INVALID;if(n.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return _.INVALID;if(a.activityId!==void 0){let o=String(a.activityId);if(o.length===0||o==="0"||i.has(o))return _.INVALID;i.add(o)}}for(let a of t.items)if(!Bl(a.parent,!0,t.mode,n,e))return _.PARENT_NOT_FOUND;if(mT(t.items))return _.INVALID;let r=new Set;for(let a of t.links){if(!Object.values(H).includes(a.type))return _.INVALID_LINK_TYPE;if(a.lag!==void 0&&!Number.isFinite(a.lag))return _.INVALID_LINK_LAG;if(!Bl(a.source,!1,t.mode,n,e)||!Bl(a.target,!1,t.mode,n,e))return _.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let o=String(a.linkId);if(o.length===0||r.has(o))return _.INVALID;r.add(o)}}return null}function Bl(t,e,n,i,r){return typeof t=="string"?t==="0"?e:n===Dt.APPEND&&r.adapter.getActivity(String(t))!==null:t!==null&&t.batchId.length>0&&i.has(t.batchId)}function mT(t){let e=new Map;for(let i of t)typeof i.parent!="string"&&e.set(i.batchId,i.parent.batchId);let n=new Set;for(let i of t){let r=new Set,a=i.batchId;for(;a!==void 0&&!n.has(a);){if(r.has(a))return!0;r.add(a),a=e.get(a)}for(let o of r)n.add(o)}return!1}function gT(t,e){let n=new Map;for(let d of t.items){let u=ho(d.overrides,e.sector.hoursPerDay);if(!u.ok)return u;n.set(d.batchId,u.value)}let i=new Map,r=new Set;for(let d of t.items){let u=AT(d.activityId,t.mode,r,e);r.add(String(u)),i.set(d.batchId,u)}let a=new Set,o=t.links.map(d=>{let u=IT(d.linkId,t.mode,a,e);return a.add(String(u)),u}),s=ST(t,i,e),l=[];for(let d of t.items){let u=i.get(d.batchId),p=s.get(d.batchId);if(u===void 0||p===void 0)return{ok:!1,reason:_.INVALID};let f=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:_.PARENT_NOT_FOUND};l.push({input:d,activityId:u,parentId:y,parentBatchId:f,insertionCorrelativeId:p,overrides:n.get(d.batchId)??{}})}let c=[];for(let[d,u]of t.links.entries()){let p=Yf(u.source,i),f=Yf(u.target,i),y=o[d];if(p===null||f===null||y===void 0)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};c.push({source:p,target:f,type:u.type,lag:u.lag??0,linkId:y})}return{ok:!0,plan:{items:l,links:c}}}function AT(t,e,n,i){if(t!==void 0&&(e===Dt.REPLACE||i.adapter.getActivity(t)===null&&!i.isActivityIdReserved(String(t)))&&!n.has(String(t)))return i.activityIdGen.bump(t),t;let a=i.activityIdGen.next();for(;n.has(String(a))||e===Dt.APPEND&&(i.adapter.getActivity(a)!==null||i.isActivityIdReserved(String(a)));)a=i.activityIdGen.next();return a}function IT(t,e,n,i){if(t!==void 0&&(e===Dt.REPLACE||i.adapter.getLink(t)===null&&!i.isLinkIdReserved(String(t)))&&!n.has(String(t)))return i.linkIdGen.bump(t),t;let a=i.linkIdGen.next();for(;n.has(String(a))||e===Dt.APPEND&&(i.adapter.getLink(a)!==null||i.isLinkIdReserved(String(a)));)a=i.linkIdGen.next();return a}function ST(t,e,n){if($f(t)){let s=n.adapter.activityCount();return new Map(t.items.map((l,c)=>[l.batchId,s+c]))}let i=new Set(Array.from(e.values(),s=>String(s))),r=new Map;for(let s of t.items){let l=e.get(s.batchId);if(l===void 0)continue;let c=typeof s.parent=="string"?s.parent:e.get(s.parent.batchId);if(c===void 0)continue;let d=String(c),u=r.get(d);u||(u={existing:t.mode===Dt.REPLACE||typeof s.parent!="string"&&e.has(s.parent.batchId)?[]:Ul(n.adapter,d).sort((m,h)=>jt(m)-jt(h)||String(m.id).localeCompare(String(h.id))).map(m=>String(m.id)),newIdsByTarget:new Map},r.set(d,u));let p=s.index===void 0?u.existing.length:Math.min(s.index,u.existing.length),f=u.newIdsByTarget.get(p)??[];f.push(String(l)),u.newIdsByTarget.set(p,f)}let a=new Map,o=new Map(Array.from(e,([s,l])=>[String(l),s]));for(let s of r.values()){let l=[];for(let d=0;d<=s.existing.length;d+=1){for(let p of s.newIdsByTarget.get(d)??[])l.push(p);let u=s.existing[d];u!==void 0&&l.push(u)}let c=0;for(;c<l.length;){if(!i.has(l[c])){c+=1;continue}let d=c;for(;c<l.length&&i.has(l[c]);)c+=1;let u=c-d,p=d>0?Kf(l[d-1],n):null,f=c<l.length?Kf(l[c],n):null;for(let y=0;y<u;y+=1){let m=l[d+y],h=o.get(m);h!==void 0&&a.set(h,vT(p,f,y+1,u))}}}return a}function $f(t){return t.mode===Dt.APPEND&&t.items.every(e=>e.parent==="0"&&e.index===void 0)}function Kf(t,e){let n=e.adapter.getActivity(t);return n?jt(n):0}function vT(t,e,n,i){return t!==null&&e!==null&&e>t?t+(e-t)*n/(i+1):t!==null?t+n:e!==null?e-(i-n+1):n-1}async function CT(t,e,n){let i=new Map,r=new Map,a=[];for(let s of e){if(s.parentBatchId===null){a.push(s);continue}let l=i.get(s.parentBatchId)??[];l.push(s),i.set(s.parentBatchId,l)}for(let s=0;s<a.length;s+=1){let l=a[s],c=await Er({kind:I.ACTIVITY_CREATE,parentId:l.parentId,activityId:l.activityId,overrides:l.overrides,...t.eventSource===void 0?{}:{eventSource:t.eventSource}},n,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:l.insertionCorrelativeId});if(!c.ok)return c;for(let[d,u]of c.removedParentLinks)r.set(d,u);for(let d of i.get(l.input.batchId)??[])a.push(d)}if(a.length!==e.length)return{ok:!1,reason:_.INVALID};let o=new Set;for(let s=a.length-1;s>=0;s-=1){let l=a[s].parentId;l==="0"||o.has(String(l))||(o.add(String(l)),Kt(l,n.adapter))}return{ok:!0,removedParentLinks:r}}function Yf(t,e){return typeof t=="string"?t:e.get(t.batchId)??null}function DT(t){return new Map(t.adapter.getAllLinks().map(e=>[String(e.id),{...e}]))}function TT(t){return new Map(Array.from(t,([e,n])=>[String(e),n]))}function qf(t,e){let{adapter:n}=e,i=t.activityId,r=n.getActivity(i);if(!r)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let a=r.pendingRequestIds??[],o=t.pendingRequests.map(c=>c.id);n.setActivityField(t.activityId,"pendingRequestIds",o);let s=n.getActivity(i);if(!s)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let l={id:i,kind:x.UPDATED,fields:{pendingRequestIds:{before:a,after:o}},after:rt(s)};return{ok:!0,changes:{source:t,activities:[l],links:[],calendars:[],trackingEvents:[]}}}function zf(t){let e=new Map;for(let n of t){let i=n.proplannerId;typeof i=="number"&&Number.isSafeInteger(i)&&i>0&&e.set(i,String(n.id))}return e}function Jf(t,e,n){let i=new Set(e.map(({id:r})=>String(r)));for(let r of t)if((r.proplannerId==null||r.proplannerId===0)&&!i.has(String(r.id)))throw new Error(`persistence-acknowledge: missing ${n} proplannerId for "${String(r.id)}"`)}function _T(t,e,n,i,r,a){let o=String(t.id);if(o.length===0||r.has(o))throw new Error(`persistence-acknowledge: duplicate or empty ${e} id "${o}"`);if(!Number.isSafeInteger(t.proplannerId)||t.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${e} proplannerId ${String(t.proplannerId)}`);if(a.has(t.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${e} proplannerId ${String(t.proplannerId)}`);let s=n(o);if(!s.exists)throw new Error(`persistence-acknowledge: unknown ${e} id "${o}"`);if(s.current!==null&&s.current!==0&&s.current!==t.proplannerId)throw new Error(`persistence-acknowledge: ${e} "${o}" already has proplannerId ${String(s.current)}`);let l=i.get(t.proplannerId);if(l!==void 0&&l!==o)throw new Error(`persistence-acknowledge: ${e} proplannerId ${String(t.proplannerId)} already belongs to "${l}"`);r.add(o),a.add(t.proplannerId)}function Xf(t,e,n,i){let r=new Set,a=new Set;for(let o of t)_T(o,e,n,i,r,a)}async function Zf(t,e){let n=t.filter(s=>{let l=e.adapter.getActivity(String(s.activityId));return l!==null&&l.progress!==s.progress}),i=new Set(n.map(s=>String(s.activityId))),r=cr(e.adapter,i),a=new Set(i);for(let s of r)a.add(String(s));let o=await ot(e.adapter,a);return e.adapter.batchUpdate(()=>{for(let s of n){let l=String(s.activityId);e.adapter.setActivityField(l,"progress",s.progress),e.adapter.setActivityField(l,"autoScheduling",Nn(s.progress))}cu(r,e.adapter),Lf(i,r,e.adapter)}),[...await za(e.adapter,o,a)]}async function Qf(t,e){let n=t.activities??[],i=t.links??[],r=e.adapter.getAllActivities(),a=e.adapter.getAllLinks(),o=t.checkpoint?.activities??r,s=t.checkpoint?.links??a,l=new Map(o.map(y=>[String(y.id),y])),c=new Map(s.map(y=>[String(y.id),y])),d=zf(o),u=zf(s);Xf(n,"activity",y=>{let m=l.get(y);return{exists:m!==void 0,current:m?.proplannerId??null}},d),Xf(i,"link",y=>{let m=c.get(y);return{exists:m!==void 0,current:m?.proplannerId??null}},u),Jf(o,n,"activity"),Jf(s,i,"link");let p=[],f=[];return e.adapter.batchUpdate(()=>{for(let y of n){let m=e.adapter.getActivity(y.id);if(!m||m.proplannerId===y.proplannerId)continue;let h=m.proplannerId;e.adapter.setActivityField(y.id,"proplannerId",y.proplannerId),p.push({id:y.id,kind:x.UPDATED,fields:{proplannerId:{before:h,after:y.proplannerId}},after:{...m,proplannerId:y.proplannerId}})}for(let y of i){let m=e.adapter.getLink(y.id);if(!m||m.proplannerId===y.proplannerId)continue;let h=m.proplannerId;e.adapter.setLinkProplannerId(y.id,y.proplannerId),f.push({id:y.id,kind:x.UPDATED,fields:{proplannerId:{before:h,after:y.proplannerId}},after:{...m,proplannerId:y.proplannerId}})}}),{ok:!0,changes:{source:t,activities:p,links:f,calendars:[],trackingEvents:[]}}}async function ty(t,e,n){if(ET(t))return{ok:!1,reason:_.INVALID_VALUE};let i=[...new Set(t.activityIds.map(String))];if(t.acknowledgePersistedLookahead===!0&&i.some(s=>!n.isActivityIdReserved(s)))return{ok:!1,reason:_.INVALID};let a=i.map(s=>n.adapter.getActivity(s));if(a.some(s=>!s))return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let o=[];for(let[s,l]of i.entries()){let c=a[s];if(!c)continue;let d={};c.isLookahead!==t.isLookahead&&(d.isLookahead={before:c.isLookahead,after:t.isLookahead},n.adapter.setActivityField(l,"isLookahead",t.isLookahead)),c.hasLookaheadTasks!==t.hasLookaheadTasks&&(d.hasLookaheadTasks={before:c.hasLookaheadTasks,after:t.hasLookaheadTasks},n.adapter.setActivityField(l,"hasLookaheadTasks",t.hasLookaheadTasks)),Object.keys(d).length!==0&&o.push({id:l,kind:x.UPDATED,fields:d,after:{...c,isLookahead:t.isLookahead,hasLookaheadTasks:t.hasLookaheadTasks}})}return t.persistedProgress!==void 0&&(await Zf([{activityId:i[0],progress:t.persistedProgress}],n)).length>0?(await nt({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:t.persistedProgress===0?i[0]:null,recomputeParentsFrom:[],now:n.now,options:e}),{ok:!0,changes:await G(n.adapter,{source:t,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:n.sector.hoursPerDay})}):{ok:!0,changes:{source:t,activities:o,links:[],calendars:[],trackingEvents:[]}}}function ET(t){let e=t.persistedProgress;return e!==void 0&&(t.activityIds.length!==1||!Number.isFinite(e)||e<0||e>100)}function Wl(t,e){let{adapter:n}=e,i=new Set(t.conversionRootIds.map(p=>String(p)));if(i.size===0)throw new Error("Conversion requires at least one root");for(let p of i)xT(p,n);let r=n.getVisualOrderIds().filter(p=>i.has(p)&&!Ni(p,i,n)),a=r.map(p=>PT(p,n)),o=a.map(({conversionRootId:p,convertedActivities:f})=>({conversionRootId:p,convertedActivities:f})),s=a.flatMap(p=>p.milestoneMoves),l=a.flatMap(p=>p.activityIdsToDelete),c=a.map(p=>p.formerParent),d=new Set(l),u=go(d,n);return{sourceStateRevision:e.stateRevision,conversionRootIds:r,conversionGroups:o,milestoneMoves:s,activityIdsToDelete:l,linkIdsToDelete:u,formerParents:c}}async function iy(t,e,n){if(t.expectedStateRevision!==n.stateRevision)return{ok:!1,reason:_.STALE_STATE_REVISION};let i=Wl(t,n);if(!MT(i,n.adapter))return{ok:!1,reason:_.HIERARCHY_CYCLE};let{adapter:r,scheduler:a}=n;a.invalidateAllCaches();let o=await OT(i,r);bT(i,n),ry(i,r),NT(i,o.deletedIds,r);let s=FT(i,r);vi(r,s,o.deletedIds,o.beforeSnap,o.touchedIds);let{scheduledIds:l}=await nt({adapter:r,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:"roots",recomputeParentsFrom:o.touchedIds,now:n.now,options:e,recomputeParentProgress:!0}),c=await G(r,{source:t,beforeSnap:o.beforeSnap,touchedIds:o.touchedIds,scheduledIds:l,sirDetection:"after-diff",links:me(o.beforeLinks),hoursPerDay:n.sector.hoursPerDay,correlativeShifts:s});return wT(i,o,c)}function PT(t,e){let n=jl(t,e),i=mo([t],e);if(i.delete(t),i.size===0)throw new Error(`Conversion root ${t} has no descendants`);let r=e.getVisualOrderIds().filter(l=>i.has(l)).map(l=>jl(l,e));ny(n);for(let l of r)ny(l);let a=r.filter(l=>l.type!==k.MILESTONE),o=r.filter(l=>l.type===k.MILESTONE),s=RT(n,a);return{conversionRootId:t,convertedActivities:a.map(l=>kT(l,s)),milestoneMoves:LT(n,o),activityIdsToDelete:a.map(l=>l.id),formerParent:{activity:rt(n),hasConvertedActivities:a.length>0}}}function RT(t,e){let n=new Map;e.length>0&&n.set(t.id,ey(t));for(let i of e)n.set(i.id,ey(i));return n}function kT(t,e){let n=rt(t),i=de(t.parentId),r=e.get(i);return n.parentId=r===void 0?null:String(r),n}function LT(t,e){let n=[],i=de(t.parentId),r=t.id;for(let a of e)n.push({activityId:a.id,parentId:i,afterSiblingId:r}),r=a.id;return n}async function OT(t,e){let n=new Set(t.activityIdsToDelete),i=new Set([...t.conversionRootIds,...t.activityIdsToDelete,...t.milestoneMoves.map(({activityId:r})=>r),...t.milestoneMoves.map(({parentId:r})=>r).filter(r=>r!=="0")]);return{deletedIds:n,touchedIds:i,beforeSnap:await ot(e,i),beforeLinks:UT(t.linkIdsToDelete,e),viewStateChanges:_r(e,n)}}function bT(t,e){for(let n of t.activityIdsToDelete){let i=e.adapter.getActivity(n)?.customId;i&&e.customIdTracker.releaseCustomId(i)}}function ry(t,e){for(let n of t.milestoneMoves)e.setActivityFields(n.activityId,{parentId:n.parentId,correlativeId:bi(e,n.parentId,n.afterSiblingId,void 0)});for(let n of t.linkIdsToDelete)e.removeLink(n);for(let n of[...t.activityIdsToDelete].reverse())e.removeActivity(n);for(let{activity:n}of t.formerParents)e.setActivityField(n.id,U.TYPE,k.TASK)}function NT(t,e,n){for(let{activity:i,hasConvertedActivities:r}of t.formerParents){let a=jl(i.id,n),o=Ao({parent:a,idsRemoved:e});n.setActivityFields(i.id,{isLookahead:i.isLookahead||r,hasLookaheadTasks:i.hasLookaheadTasks||r,...o?.fields??{}})}}function FT(t,e){for(let{activity:n}of t.formerParents)Kt(n.parentId,e);return xt(e)}function wT(t,e,n){let i=new Map;for(let r of e.deletedIds){let a=e.beforeSnap.get(r);a&&i.set(r,a)}return{ok:!0,changes:e.viewStateChanges.length===0?n:{...n,viewState:e.viewStateChanges},conversionGroups:t.conversionGroups.map(({conversionRootId:r,convertedActivities:a})=>({conversionRootId:r,convertedActivities:a.map(o=>rt(o))})),__beforeSnap:i,__beforeLinks:e.beforeLinks}}function xT(t,e){let n=e.getActivity(t);if(!n)throw new Error(`Conversion root ${t} was not found`);if(n.type===k.PROJECT&&n.correlativeId===0)throw new Error(`Conversion root ${t} is the visual project root`)}function jl(t,e){let n=e.getActivity(t);if(!n)throw new Error(`Conversion activity ${t} is missing`);return n}function ey(t){if(t.proplannerId==null)throw new Error(`Conversion activity ${t.id} has no persisted identifier`);return t.proplannerId}function ny(t){if(!Number.isFinite(t.startDate.getTime()))throw new Error(`Conversion activity ${t.id} has invalid startDate`);if(!Number.isFinite(t.endDate.getTime()))throw new Error(`Conversion activity ${t.id} has invalid endDate`)}function MT(t,e){let n=e.fork();return ry(t,n),tn({port:e,proposedPort:n,currentLinks:e.getAllLinks(),proposedLinks:n.getAllLinks()}).ok}function UT(t,e){let n=new Map;for(let i of t){let r=e.getLink(i);r&&n.set(i,{...r})}return n}function wi(t,e){let n=new Set;for(let r of t)n.add(String(r));let i=[];for(let r of e.getAllLinks()){let a=String(r.source),o=String(r.target);!n.has(a)&&!n.has(o)||oy(r,e)&&i.push(String(r.id))}return i}function oy(t,e){let n=String(t.source),i=String(t.target);return ay(i,n,e)||ay(n,i,e)}function Io(t,e){return[...t].filter(([,n])=>oy(n,e)).map(([n])=>String(n))}function ay(t,e,n){let i=String(t),r=new Set;for(;i!=null;){if(r.has(i))return!1;r.add(i);let a=n.getActivity(i);if(!a)return!1;let o=a.parentId;if(o===null||V(o))return!1;let s=o;if(s===e)return!0;i=s}return!1}function So(t,e){let n=t.getAllLinks();return!tn({port:t,currentLinks:n,proposedLinks:n,proposal:{reparented:e}}).ok}function vo(t,e){let n=new Set;if(t.length===0)return n;let i=new Map(t.map(a=>[a.activityId,a.newParentId]));if(!So(e,i))return n;let r=new Map;for(let a of t){let o=new Map(r);if(o.set(a.activityId,a.newParentId),So(e,o)){n.add(a.activityId);continue}r.set(a.activityId,a.newParentId)}return n}async function sy(t,e,n){let{adapter:i,scheduler:r,sector:a}=n;r.invalidateAllCaches();let o=i.getActivity(t.activityId);if(!o)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let s=V(t.parentId);if(!s&&!i.getActivity(t.parentId))return{ok:!1,reason:_.PARENT_NOT_FOUND};if(!s&&(t.parentId===t.activityId||i.isChildOf(t.parentId,t.activityId)))return{ok:!1,reason:_.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(t.afterSiblingId!==void 0&&t.beforeSiblingId!==void 0)return{ok:!1,reason:_.ANCHOR_SIBLING_CONFLICT};let l=t.afterSiblingId??t.beforeSiblingId;if(l!==void 0){let R=i.getActivity(l);if(!R)return{ok:!1,reason:_.ANCHOR_SIBLING_NOT_FOUND};if((R.parentId===null?"0":String(R.parentId))!==t.parentId)return{ok:!1,reason:_.ANCHOR_SIBLING_WRONG_PARENT}}let c=o.parentId,d=de(c),u=String(t.parentId),p=d!==u;if(p){let R=new Map([[t.activityId,s?null:t.parentId]]);if(So(i,R))return{ok:!1,reason:_.HIERARCHY_CYCLE}}let f=new Set([t.activityId]);p?(d!=="0"&&f.add(d),u!=="0"&&f.add(u)):d!=="0"&&f.add(d);let y=await ot(i,f),m=new Map;p&&i.setActivityField(t.activityId,U.PARENT,u);let h=bi(i,t.parentId,t.afterSiblingId,t.beforeSiblingId);if(i.setActivityField(t.activityId,U.CORRELATIVE_ID,h),p){if(!s){let R=i.getActivity(t.parentId);if(R){let L=Ze(R.type)&&i.getChildren(t.parentId).filter(O=>O!==t.activityId).length===0,P=gn({parentId:t.parentId,newChildId:t.activityId,isCurrentlyLeaf:L,promotionSource:Fi.REPARENT},n);if(P.applied)for(let[O,M]of P.removedLinks)m.set(O,M)}}if(d!=="0"){let R=i.getActivity(d);if(R){let L=i.getChildren(d),P=mn({parent:R,remainingChildIds:L.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(d),computeEndDate:(O,M)=>i.calculateEndDate({startDate:O,durationHours:M,task:R}),idsRemoved:new Set([t.activityId]),dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(P){i.setActivityFields(d,P.fields);let O=Pe(d,i),M=O?i.getActivity(O)?.customId:null,j=typeof M=="string"&&M?M:null,z=n.customIdTracker.generateCustomIdForRestoredChild(j);i.setActivityField(d,U.CUSTOM_ID,z)}}}}p&&(d!=="0"&&Kt(d,i),s||Kt(t.parentId,i));let A=xt(i);for(let R of A){if(f.add(R.activityId),y.has(R.activityId))continue;let L=i.getActivity(R.activityId);if(!L)continue;let P=rt(L);R.before!==void 0&&(P.correlativeId=R.before),y.set(R.activityId,P)}let T=p&&d!=="0"?i.getChildren(d).map(String):[],{scheduledIds:b}=await nt({adapter:i,scheduler:r,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:t.activityId,recomputeParentsFrom:[t.activityId,t.parentId,...T],now:n.now,options:e,recomputeParentProgress:p}),S=p?wi([t.activityId],i):[],g=Io(m,i),w={name:se.ACTIVITY_MOVE,properties:{activity_id:t.activityId,new_parent_id:t.parentId,after_sibling_id:t.afterSiblingId??null,before_sibling_id:t.beforeSiblingId??null,invalid_link_ids:[...new Set([...g,...S.map(String)])]}};return t.eventSource!==void 0&&(w.properties.event_source=t.eventSource),{ok:!0,changes:await G(i,{source:t,beforeSnap:y,touchedIds:f,scheduledIds:b,sirDetection:Bt.BEFORE_DIFF,links:me(m),trackingEvents:[w],hoursPerDay:a.hoursPerDay}),...m.size>0?{__beforeLinks:m}:{}}}function Co(t,e){let n=new Set(t),i=[],r=[],a=new Set,o=new Set(n),s=[...t].sort((d,u)=>{let p=e.getActivity(d),f=e.getActivity(u),y=p?jt(p):qn,m=f?jt(f):qn;return y-m});for(let d of s){if(!e.getActivity(d)){i.push({activityId:d,reason:_.ACTIVITY_NOT_FOUND}),o.delete(d);continue}if(Ni(d,a,e))continue;let p=Ed(d,o,e);if(p==null){i.push({activityId:d,reason:_.INDENT_NO_ELIGIBLE_SIBLING}),o.delete(d);continue}let f=e.getActivity(d)?.parentId,y=V(f)?"0":String(f);r.push({activityId:d,newParentId:p,oldParentId:y}),a.add(d)}let l=vo(r,e);for(let d of l)i.push({activityId:d,reason:_.HIERARCHY_CYCLE});let c=r.filter(d=>!l.has(d.activityId));return{moves:r,cyclicMoveIds:l,allowedMoves:c,failed:i}}async function ly(t,e,n){let{adapter:i,scheduler:r,sector:a}=n;if(r.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:_.ACTIVITY_IDS_EMPTY};let o=new Set,s=[],l=Co(t.activityIds,i),c=[...l.failed];for(let g of l.moves)o.add(String(g.activityId)),o.add(String(g.newParentId)),g.oldParentId!=="0"&&o.add(String(g.oldParentId));let d=l.allowedMoves,u=await ot(i,o);for(let{activityId:g,newParentId:w}of d)i.setActivityField(g,U.PARENT,w),i.setActivityField(g,U.CORRELATIVE_ID,Mf),s.push(g);let p=new Set,f=new Map;for(let{activityId:g,newParentId:w}of d){if(p.has(w))continue;p.add(w);let R=i.getActivity(w);if(!R)continue;let L=R.customId,P=Ze(R.type)&&i.getChildren(w).filter(j=>!s.includes(j)).length===0,O=R.hasNewActivities&&R.newActivityIds.some(j=>String(j)===String(g)),M=gn({parentId:w,newChildId:g,isCurrentlyLeaf:P,promotionSource:Fi.REPARENT},n);if(M.applied){for(let[j,z]of M.removedLinks)f.set(j,z);O||(i.setActivityField(w,U.HAS_NEW_ACTIVITIES,!1),i.setActivityField(w,U.NEW_ACTIVITIES_ARRAY,[]))}i.setActivityField(w,U.CONSTRAINT_TYPE,D.ASAP),i.setActivityField(w,U.CONSTRAINT_DATE,null),i.setActivityField(w,U.CUSTOM_ID,null),M.applied||pf(L,n.customIdTracker)}let y=new Set;for(let g of d)g.oldParentId!=="0"&&y.add(g.oldParentId),y.add(g.newParentId);for(let g of y)Kt(g,i);let m=xt(i);for(let g of m){if(o.add(g.activityId),u.has(g.activityId))continue;let w=i.getActivity(g.activityId);if(!w)continue;let R=rt(w);g.before!==void 0&&(R.correlativeId=g.before),u.set(g.activityId,R)}let h=Io(f,i),A=wi(s,i);for(let g of A){let w=i.getLink(g);w&&(f.set(g,{...w}),i.removeLink(g))}let{scheduledIds:T}=await nt({adapter:i,scheduler:r,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:null,recomputeParentsFrom:s,now:n.now,options:e}),b={name:se.ACTIVITY_INDENT,properties:{activity_ids:s,failed:c.map(g=>({activity_id:g.activityId,reason:g.reason})),invalid_link_ids:[...new Set([...h,...A.map(String)])]}};t.eventSource!==void 0&&(b.properties.event_source=t.eventSource);let S=await G(i,{source:t,beforeSnap:u,touchedIds:o,scheduledIds:T,links:me(f),trackingEvents:[b],hoursPerDay:a.hoursPerDay});return{ok:!0,activityVerdicts:t.activityIds.map(g=>{let w=c.find(R=>String(R.activityId)===String(g));return w?{activityId:String(g),ok:!1,reason:w.reason}:{activityId:String(g),ok:!0}}),changes:S,__beforeLinks:f}}async function cy(t,e,n){let{adapter:i,scheduler:r,sector:a}=n;if(r.invalidateAllCaches(),t.activityIds.length===0)return{ok:!1,reason:_.ACTIVITY_IDS_EMPTY};let o=new Set(t.activityIds),s=new Map,l=new Map;for(let R of t.activityIds){let L=R;i.getActivity(L)&&(s.set(L,_s(L,i)),l.set(L,Uf(L,o,i)))}let c=new Set,d=[],u=[],p=new Set,f=[],y=new Set,m=[...t.activityIds].sort((R,L)=>{let P=i.getActivity(R),O=i.getActivity(L),M=P?jt(P):qn,j=O?jt(O):qn;return M-j});for(let R of m){let L=R,P=i.getActivity(L);if(!P){d.push({activityId:L,reason:_.ACTIVITY_NOT_FOUND});continue}if(Ni(L,y,i))continue;let O=P.parentId;if(V(O)){d.push({activityId:L,reason:_.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let M=String(O),j=i.getActivity(M);if(!j){d.push({activityId:L,reason:_.ACTIVITY_NOT_FOUND});continue}let z=j.parentId;if(V(z)){d.push({activityId:L,reason:_.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let ft=String(z),st=_s(M,i)+1,Nt=l.get(L);if(Nt!=null&&o.has(Nt)){let kt=s.get(Nt)??-1,Ce=s.get(L)??-1;kt>=0&&Ce>=0&&(st+=Ce-kt)}f.push({activityId:L,grandparentKey:ft,oldParentKey:M,targetIndexInGrandparent:st}),y.add(L),c.add(String(L)),c.add(String(M)),ft!=="0"&&c.add(String(ft)),p.add(M)}let h=vo(f.map(R=>({activityId:R.activityId,newParentId:R.grandparentKey})),i);for(let R of h)d.push({activityId:R,reason:_.HIERARCHY_CYCLE});let A=f.filter(R=>!h.has(R.activityId)),T=await ot(i,c);for(let R of A){i.setActivityField(R.activityId,U.PARENT,R.grandparentKey);let L=Hf(i,R.grandparentKey,R.targetIndexInGrandparent,R.activityId);i.setActivityField(R.activityId,U.CORRELATIVE_ID,L),u.push(R.activityId)}for(let R of p){let L=i.getActivity(R);if(!L)continue;let P=i.getChildren(R),O=mn({parent:L,remainingChildIds:P.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:i.getPromotionSnapshot(R),computeEndDate:(st,Nt)=>i.calculateEndDate({startDate:st,durationHours:Nt,task:L}),idsRemoved:new Set(A.filter(st=>st.oldParentKey===R).map(st=>st.activityId)),dataDateCapability:n.dataDateCapability,hasCompleteSchedulingState:n.hasCompleteSchedulingState});if(!O){Fa(R,i);continue}i.setActivityFields(R,O.fields);let M=Pe(R,i),j=M?i.getActivity(M)?.customId:null,z=typeof j=="string"&&j?j:null,ft=n.customIdTracker.generateCustomIdForRestoredChild(z);i.setActivityField(R,U.CUSTOM_ID,ft)}let b=new Set;for(let R of p)b.add(String(R));for(let R of A)R.grandparentKey!=="0"&&b.add(String(R.grandparentKey));for(let R of b)Kt(R,i);let S=xt(i);for(let R of S){if(c.add(R.activityId),T.has(R.activityId))continue;let L=i.getActivity(R.activityId);if(!L)continue;let P=rt(L);R.before!==void 0&&(P.correlativeId=R.before),T.set(R.activityId,P)}let{scheduledIds:g}=await nt({adapter:i,scheduler:r,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:u.length>0?vt.ROOTS:null,recomputeParentsFrom:u,now:n.now,options:e}),w={name:se.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(R=>({activity_id:String(R.activityId),reason:R.reason}))}};return t.eventSource!==void 0&&(w.properties.event_source=t.eventSource),{ok:!0,activityVerdicts:t.activityIds.map(R=>{let L=d.find(P=>String(P.activityId)===String(R));return L?{activityId:String(R),ok:!1,reason:L.reason}:{activityId:String(R),ok:!0}}),changes:await G(i,{source:t,beforeSnap:T,touchedIds:c,scheduledIds:g,trackingEvents:[w],hoursPerDay:a.hoursPerDay})}}async function dy(t,e,n){let{adapter:i,scheduler:r,sector:a}=n,o=i.getActivity(t.activityId);if(!o)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};if(!Xi(t.type))return{ok:!1,reason:_.INVALID_VALUE};let s=i.getChildren(t.activityId),l=t.type===k.PROJECT;if(l!==s.length>0)return{ok:!1,reason:_.INVALID_VALUE};let c=new Set(i.getAllIds()),d=await ot(i,c);r.invalidateAllCaches();let u=l&&o.type!==k.PROJECT?gn({parentId:t.activityId,newChildId:s[0],isCurrentlyLeaf:!0},n).removedLinks:new Map;!l&&o.type===k.PROJECT&&HT(t.activityId,n),t.type!==k.PROJECT?(BT(t.activityId,t.type,n),jT(t.activityId,n)):Kt(t.activityId,i);let p=WT(t.activityId,n);for(let[y,m]of u)p.set(y,m);let{scheduledIds:f}=await nt({adapter:i,scheduler:r,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:t.activityId,recomputeParentsFrom:[t.activityId],recomputeParentProgress:!0,now:n.now,options:e});return{ok:!0,changes:await G(i,{source:t,beforeSnap:d,touchedIds:c,scheduledIds:f,sirDetection:Bt.BEFORE_DIFF,links:me(p),hoursPerDay:a.hoursPerDay}),__beforeLinks:new Map(p)}}function HT(t,e){let n=e.adapter.getActivity(t);if(!n)return;let i=mn({parent:n,remainingChildIds:[],defaultDurationHours:e.sector.hoursPerDay,promotionSnapshot:e.adapter.getPromotionSnapshot(t),computeEndDate:(r,a)=>e.adapter.calculateEndDate({startDate:r,durationHours:a,task:n}),dataDateCapability:e.dataDateCapability,hasCompleteSchedulingState:e.hasCompleteSchedulingState});i&&e.adapter.setActivityFields(t,i.fields)}function BT(t,e,n){let i=n.adapter.getActivity(t);if(!i)return;n.adapter.setActivityField(t,U.TYPE,e);let r=e===k.MILESTONE?0:i.durationHours===0?n.sector.hoursPerDay:i.durationHours;r!==i.durationHours&&n.adapter.setActivityField(t,U.DURATION_HOURS,r);let a=n.adapter.getActivity(t);if(!a)return;let o=n.adapter.calculateEndDate({startDate:a.startDate,durationHours:r,task:a});n.adapter.setActivityField(t,U.END_DATE,o)}function jT(t,e){if(e.adapter.getActivity(t)?.customId)return;let i=Pe(t,e.adapter),r=i?e.adapter.getActivity(i)?.customId:null,a=e.customIdTracker.generateCustomIdForRestoredChild(r||null);e.adapter.setActivityField(t,U.CUSTOM_ID,a)}function WT(t,e){let n=new Map;for(let i of wi([t],e.adapter)){let r=e.adapter.getLink(i);r&&(n.set(String(i),{...r}),e.adapter.removeLink(i))}return n}async function uy(t,e,n){let{adapter:i,ctx:r,scheduler:a,sector:o}=n;if(t.newValue!==0&&t.newValue!==100)return{ok:!1,reason:_.INVALID_PROGRESS_VALUE};let s=r.activityReader.getActivity(t.activityId);if(!s)return{ok:!1,reason:_.ACTIVITY_NOT_FOUND};let l=_e(E.PROGRESS);if(!l)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let c=l.canEdit(s,r.hierarchy);if(!c.allowed&&!YT(t,c))return{ok:!1,reason:c.reason,...c.alertKey?{alertKey:c.alertKey}:{}};let d=l.transform(s,t.newValue,r,t.newValue),u=vf(s,t.newValue,c.allowed?d:null,n,e.confirmations);if(u!==null&&!u.accepted)return GT(u);let p=u===null?d:u.changes,f=u===null||c.allowed,y=fn(t.activityId,p),m=await ot(i,y);yn(i,t.activityId,p),f&&uu(t.activityId,t.newValue,i),an(t.activityId,p.postProcessors??[],i);let h=VT(t.activityId,p,n),{scheduledIds:A}=await nt({adapter:i,scheduler:a,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:h,recomputeParentsFrom:[],collectDirty:T=>Ja(t.activityId,y,T),now:n.now,options:e});return{ok:!0,changes:await G(i,{source:t,beforeSnap:m,touchedIds:y,scheduledIds:A,trackingEvents:KT(p),hoursPerDay:o.hoursPerDay})}}function VT(t,e,n){return e.needsAutoSchedule?n.ctx.hierarchy.hasChildren(t)?vt.ROOTS:t:null}function KT(t){return(t.trackingEvents??[]).map(e=>({name:e.name,properties:e.properties??{}}))}function YT(t,e){return t.origin===Ya.ACTION_BUTTON&&(e.reason===ye.HAS_LOOKAHEAD_TASKS||e.reason===ye.SUMMARY)}function GT(t){return{ok:!1,reason:t.reason,...t.alertKey?{alertKey:t.alertKey}:{},...t.confirmation?{confirmation:t.confirmation}:{}}}function $T(t){return t===E.START_DATE||t===E.END_DATE}async function py(t,e,n){if(t.edits.some(y=>!$T(y.column)))return{ok:!1,reason:_.INVALID_VALUE};let{adapter:i,scheduler:r,sector:a}=n,o=[],s=new Map,l=new Set,c=[],d=[],u=[],p=!1;for(let y of t.edits){let m=qT(y,n,e);if(o.push(m.verdict),!m.verdict.ok||!m.changes)continue;let h=fn(y.activityId,m.changes);zT(s,h,n);for(let S of h)l.add(S);let A=Ri(i,y.activityId),T=qa(i,String(y.activityId));yn(i,y.activityId,m.changes),an(y.activityId,m.changes.postProcessors??[],i,T),d.push(...ki(A,i,y.activityId)),p||=!!m.changes.needsAutoSchedule;for(let S of m.changes.trackingEvents??[])c.push({name:S.name,properties:S.properties??{}});let b=Hn(y.activityId,m.changes.constraintWarning);b&&u.push(b)}let{scheduledIds:f}=await nt({adapter:i,scheduler:r,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p?vt.ROOTS:null,recomputeParentsFrom:l,now:n.now,options:e});return{ok:!0,verdicts:o,changes:await G(i,{source:t,beforeSnap:s,touchedIds:l,scheduledIds:f,sirDetection:Bt.BEFORE_DIFF,links:d,trackingEvents:c,warnings:u,hoursPerDay:a.hoursPerDay})}}function qT(t,e,n){let{ctx:i}=e,r=t.activityId,a=_e(t.column);if(!a)throw new Error(`[ScheduleCore] no pipeline registered for column "${t.column}"`);let o=i.activityReader.getActivity(t.activityId);if(!o)throw new Error(`[ScheduleCore] activity "${t.activityId}" not found`);let s=Oi(a,o,e,t.column);if(!s.allowed)return{verdict:{activityId:r,ok:!1,reason:s.reason??_.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let l=a.parseInput(t.newValue,o,i);if(!l.ok)return{verdict:{activityId:r,ok:!1,reason:l.reason??_.PARSE_ERROR},changes:null};let c=Reflect.get(o,a.targetField),d=a.validate(o,c,l.value,i);if(!d.valid)return{verdict:{activityId:r,ok:!1,reason:d.reason??_.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};let u=a.transform(o,l.value,i,l.raw),p=$n(o,u,e,t.column,n.confirmations);return p.accepted?{verdict:{activityId:r,ok:!0},changes:p.changes}:{verdict:{activityId:r,ok:!1,reason:p.reason,...p.alertKey?{alertKey:p.alertKey}:{},...p.confirmation?{confirmation:p.confirmation}:{}},changes:null}}function zT(t,e,n){let i=new Set;for(let r of e)t.has(r)||i.add(r);if(i.size!==0)for(let r of i){let a=n.adapter.getActivity(r);a&&t.set(r,rt(a))}}var Vl=E.CUSTOM_ID,JT="sir-apply";async function fy(t,e,n){let{adapter:i,scheduler:r,sector:a}=n;t.edits.some(P=>P.column===E.DURATION)&&r.invalidateExpandedLinksCache();let s=[],l=new Map,c=new Map,d=new Set,u=new Set,p=[],f=[],y=[],m=new Set,h=new Map,A=new Map,T=!1,b=Sf(t.edits,n);for(let P of If(t)){let O=P[0],M=b.get(String(O.activityId));if(M!==void 0&&(O.column===E.START_DATE||O.column===E.END_DATE)){s.push({activityId:O.activityId,ok:!1,reason:M.reason,...M.alertKey?{alertKey:M.alertKey}:{}});continue}let z=i_(P,n,t.eventSource,e);for(let It of P)s.push(z.verdict);if(!z.verdict.ok||!z.changes)continue;let ft=Hn(O.activityId,z.changes.constraintWarning);ft&&y.push(ft);let st=fn(O.activityId,z.changes);s_(l,st,n);for(let It of st)u.add(It);o_(c,O,l),ao(O.column)&&d.add(String(O.activityId)),QT(h,O);let Nt=Ri(i,O.activityId),kt=qa(i,String(O.activityId)),Ce=r_(O,n),Le=z.changes;yn(i,O.activityId,Le),an(O.activityId,z.changes.postProcessors??[],i,kt),XT(m,y,O),ZT(A,O,i.getActivity(O.activityId)),a_(O,Ce,n),f.push(...ki(Nt,i,O.activityId)),T||=!!z.changes.needsAutoSchedule;for(let It of z.changes.trackingEvents??[])p.push({name:It.name,properties:It.properties??{}})}let S=t.eventSource===JT?s.find(P=>!P.ok&&P.reason!==Ha.UNCHANGED):void 0;if(S&&!S.ok)return{ok:!1,reason:S.reason??_.INVALID,...S.alertKey?{alertKey:S.alertKey}:{}};let g={action:t,autoscheduleFrom:T?vt.ROOTS:null,recomputeParentsFrom:u,now:n.now,options:e},w=t_(h,A,l,y,m,n),R=c.size>0,{scheduledIds:L}=await(R?so({adapter:i,scheduler:r,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId},{postMutationArgs:g,revertTargets:[...c].filter(([P])=>!d.has(P)).map(([P,O])=>({activityId:P,priorConstraintDate:O})),revert:(P,O)=>oo(P,O,i,n.ctx.calendars)}):nt({adapter:i,scheduler:r,sector:a,defaultBaseCalendarId:n.defaultBaseCalendarId},g));return{ok:!0,verdicts:s,changes:await G(i,{source:t,beforeSnap:l,touchedIds:u,scheduledIds:L,sirDetection:Bt.BEFORE_DIFF,links:f,trackingEvents:p,warnings:w,hoursPerDay:a.hoursPerDay})}}function XT(t,e,n){if(!Ei(n.column))return;let i=String(n.activityId);for(let r of e)String(r.activityId)===i&&t.add(r)}function ZT(t,e,n){!Ei(e.column)||!n||t.set(String(e.activityId),{constraintType:n.constraintType,constraintDate:n.constraintDate?new Date(n.constraintDate.getTime()):null})}function QT(t,e){if(e.column!==E.START_DATE&&e.column!==E.END_DATE)return;let n=String(e.activityId),i=t.get(n)??new Set;i.add(e.column),t.set(n,i)}function t_(t,e,n,i,r,a){let o=new Set,s=[],l=new Set;for(let[c,d]of t){if(!d.has(E.START_DATE)||!d.has(E.END_DATE))continue;let u=e.get(c);if(u){a.adapter.setActivityFields(c,u);for(let h of r)String(h.activityId)===c&&l.add(h);continue}let p=n.get(c),f=a.adapter.getActivity(c);if(!p?.constraintType||!p.constraintDate||!f)continue;let y=En(p.constraintType,f.startDate,f.endDate),m=e_(p.constraintType,p.constraintDate,y);if(o.add(c),m){a.adapter.setActivityField(c,"constraintType",D.SNET),a.adapter.setActivityField(c,"constraintDate",new Date(f.startDate.getTime()));let h=Hn(c,zr(p.constraintType,p.constraintDate,y));h&&s.push(h);continue}a.adapter.setActivityField(c,"constraintType",p.constraintType),a.adapter.setActivityField(c,"constraintDate",p.constraintDate)}return[...i.filter(c=>!l.has(c)&&!o.has(String(c.activityId))),...s]}function e_(t,e,n){return t===D.MSO||t===D.MFO?e.getTime()!==n.getTime():qr(t,e,n).violated}function n_(t,e,n){let{ctx:i}=e,r=t.activityId,a=_e(t.column);if(!a)return{verdict:{activityId:r,ok:!1,reason:_.NO_PIPELINE_FOR_COLUMN},changes:null};let o=i.activityReader.getActivity(t.activityId);if(!o)return{verdict:{activityId:r,ok:!1,reason:_.ACTIVITY_NOT_FOUND},changes:null};let s=Oi(a,o,e,t.column,{eventSource:n,newValue:t.newValue});if(!s.allowed)return{verdict:{activityId:r,ok:!1,reason:s.reason??_.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let l=a.parseInput(t.newValue,o,i);if(!l.ok)return{verdict:{activityId:r,ok:!1,reason:l.reason??_.PARSE_ERROR},changes:null};let c=lo(o,a.targetField),d=a.validate(o,c,l.value,i);if(!d.valid)return{verdict:{activityId:r,ok:!1,reason:d.reason??_.INVALID,...d.notification?.messageKey?{alertKey:d.notification.messageKey}:{}},changes:null};if(t.column===Vl&&l.value!==null){let p=e.adapter.getActivity(t.activityId),f=p?p.customId:null,y=typeof f=="string"?f:null;if(e.customIdTracker.isCustomIdInUse(String(l.value),y))return{verdict:{activityId:r,ok:!1,reason:_.CUSTOM_ID_DUPLICATE},changes:null}}let u=a.transform(o,l.value,i,l.raw);return{verdict:{activityId:r,ok:!0},changes:u}}function i_(t,e,n,i){let r=t[0],a=t.map(d=>n_(d,e,n)),o=a.find(d=>!d.verdict.ok);if(o)return o;let s=a[0].changes,l=Af(s,a[1]?.changes),c=$n(e.ctx.activityReader.getActivity(r.activityId),l,e,r.column,i.confirmations);return c.accepted?{verdict:{activityId:r.activityId,ok:!0},changes:c.changes}:{verdict:{activityId:r.activityId,ok:!1,reason:c.reason,...c.alertKey?{alertKey:c.alertKey}:{},...c.confirmation?{confirmation:c.confirmation}:{}},changes:null}}function r_(t,e){if(t.column!==Vl)return null;let n=e.adapter.getActivity(t.activityId),i=n?n.customId:null;return typeof i=="string"?i:null}function a_(t,e,n){if(t.column!==Vl)return;let i=n.adapter.getActivity(t.activityId),r=i?i.customId:null,a=typeof r=="string"?r:null;e!==a&&n.customIdTracker.trackCustomIdChange(e,a)}function o_(t,e,n){if(!Ei(e.column))return;let i=String(e.activityId);if(t.has(i))return;let r=n.get(i);r&&t.set(i,r.constraintDate??null)}function s_(t,e,n){let i=new Set;for(let r of e)t.has(r)||i.add(r);if(i.size!==0)for(let r of i){let a=n.adapter.getActivity(r);a&&t.set(r,rt(a))}}var Wt={INVALID_BASELINE_POINT:"invalid_baseline_point",UNKNOWN_CONSTRAINT:"unknown_constraint",ORPHAN_ACTIVITY:"orphan_activity",INVALID_LINK:"invalid_link",DUPLICATE_LINK:"duplicate_link"},l_=[Wt.INVALID_BASELINE_POINT,Wt.UNKNOWN_CONSTRAINT,Wt.ORPHAN_ACTIVITY,Wt.INVALID_LINK,Wt.DUPLICATE_LINK],xi=()=>{};function yy(){let t=new Map,e=new Map;return{record:(r,a)=>{t.set(r,(t.get(r)??0)+1);let o=e.get(r)??[];o.length<10&&!o.includes(a)&&(o.push(a),e.set(r,o))},snapshot:()=>Object.freeze(l_.flatMap(r=>{let a=t.get(r);return a===void 0?[]:[Object.freeze({code:r,count:a,sampleIds:Object.freeze([...e.get(r)??[]])})]}))}}function hy(t){return typeof t=="string"&&t.length>0?Me(t):t instanceof Date?t:null}function Kl(t){let e=typeof t=="number"?t:typeof t=="string"&&t.trim()!==""?Number(t):Number.NaN;return!Number.isFinite(e)||e<0?null:e}function Do(t,e,n,i=!1){let r=Kl(t.duration),a=Kl(t.cost),o=Kl(t.hh_work);if(r===null||a===null||o===null)return n&&n.record(Wt.INVALID_BASELINE_POINT,n.sampleId),e.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(t.duration)}, cost=${JSON.stringify(t.cost)}, hh_work=${JSON.stringify(t.hh_work)}`),null;let s=hy(t.start_date),l=hy(t.end_date),c=i&&r===0&&s!==null&&l!==null&&l<s;return c&&e.warn("[baseline] normalizing inverted zero-duration milestone to one instant"),{startDate:s,endDate:c?s:l,durationDays:r,cost:a,workHours:o,versionId:typeof t.sectorbaselineversionId=="number"?t.sectorbaselineversionId:null,isActiveVersion:!!t.sectorbaselineversion?.active,isVisibleVersion:!!t.sectorbaselineversion?.visible,baseCalendarId:t.baseCalendarId!=null?String(t.baseCalendarId):null,hoursPerDay:typeof t.hoursPerDay=="number"?t.hoursPerDay:null,hoursPerWeek:typeof t.hoursPerWeek=="number"?t.hoursPerWeek:null}}function my(t,e,n,i=xi){let r=new Map;t.forEachActivity((s,l)=>{let c=s.proplannerId;typeof c=="number"&&r.set(c,l)});let a=new Map;for(let s of e){let l=s.activityId;if(typeof l!="number"){i(Wt.INVALID_BASELINE_POINT,String(l??"unknown"));continue}let c=r.get(l);if(c===void 0){i(Wt.INVALID_BASELINE_POINT,String(l));continue}let d=a.get(c);d?d.push(s):a.set(c,[s])}let o=[];for(let[s,l]of a){let c=t.getActivity(s)?.type===k.MILESTONE;t.setActivityField(s,"baselinePoints",l.map(d=>Do(d,n,{record:i,sampleId:s},c)).filter(d=>d!==null)),o.push(s)}return t.forEachActivity((s,l)=>{if(a.has(l))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(t.setActivityField(l,"baselinePoints",[]),o.push(l))}),o}function c_(t){let e=Lt(t);return e?{startDate:e.startDate,endDate:e.endDate,durationDays:e.durationDays,cost:e.cost,workHours:e.workHours}:null}function gy(t){let e=[];return t.forEachActivity((n,i)=>{let r=c_(n);if(!r){n.baselineSnapshot!==null&&(t.setActivityField(i,"baselineSnapshot",null),e.push(i));return}t.setActivityField(i,"baselineSnapshot",r),e.push(i)}),e}function To(t,e,n,i,r=null,a=xi){let o=new Set;for(let s of my(t,e,i,a))o.add(s);if(n)for(let s of Di(t,n,r))o.add(s);for(let s of gy(t))o.add(s);for(let s of Ti(t))o.add(s);return[...o]}function Ay(t,e){e.forEachActivity((n,i)=>{e.setActivityField(i,E.PONDERATOR,0)}),e.forEachActivity((n,i)=>{e.getChildren(i).length>0&&ro(String(i),t,e)})}function _o(t,e){Ay(e,t.adapter),sr(t.adapter),t.now&&(Di(t.adapter,t.now,t.defaultBaseCalendarId??null),Bn(t.adapter,t.now)),Ti(t.adapter),t.now&&Ue(t.adapter,t.sector.statusCriteria)}function Iy(t){return JSON.stringify(t.adapter.getAllIds().map(e=>{let n=t.adapter.getActivity(e)?.baselinePoints.find(i=>i.isActiveVersion);return n?[String(e),n.versionId,n.startDate?.getTime()??null,n.endDate?.getTime()??null,n.durationDays,n.cost,n.workHours,n.baseCalendarId,n.hoursPerDay,n.hoursPerWeek]:[String(e),null]}))}async function Sy(t,e){let n=await ot(e.adapter,new Set(e.adapter.getAllIds())),i=Iy(e),r=To(e.adapter,t.points,e.now,e.reporter,e.defaultBaseCalendarId??null);return jn(e.adapter,e.sector.hoursPerDay),Iy(e)!==i&&_o(e,e.sector.activityCreter??_t.DURATION),{ok:!0,changes:await G(e.adapter,{source:t,beforeSnap:n,touchedIds:r,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}function d_(t){return Object.values(_t).includes(t)}async function vy(t,e){if(!d_(t.criterion))return{ok:!1,reason:_.INVALID_VALUE};let n=new Set(e.adapter.getAllIds()),i=await ot(e.adapter,n);return _o(e,t.criterion),e.sector.activityCreter=t.criterion,{ok:!0,changes:await G(e.adapter,{source:t,beforeSnap:i,touchedIds:n,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}async function Cy(t,e){let n=Xa(t.criteria),i=new Set(e.adapter.getAllIds()),r=await ot(e.adapter,i),a=Ue(e.adapter,n);return e.sector.statusCriteria=n,{ok:!0,changes:await G(e.adapter,{source:t,beforeSnap:r,touchedIds:a,scheduledIds:[],hoursPerDay:e.sector.hoursPerDay})}}async function Ty(t,e,n){let i=new Map,r=new Set;for(let o of n.adapter.getAllActivities()){if(!u_(o,n))continue;let s=n.ctx.calendars.getCalendar(o.calendarId);if(!s)continue;let l=s.isWorkTime(o.startDate,dt.HOUR)?p_(o.startDate):o.startDate,c=s.getClosestWorkTime({date:l,direction:q.FUTURE,unit:dt.HOUR}),d=s.calculateEndDate(c,o.durationHours);if(Dy(c,o.startDate)&&Dy(d,o.endDate))continue;let u=String(o.id);i.set(u,rt(o)),r.add(u),n.adapter.setActivityFields(u,{startDate:c,endDate:d})}let{scheduledIds:a}=await nt({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:vt.ROOTS,recomputeParentsFrom:r,now:n.now,options:e});return{ok:!0,changes:await G(n.adapter,{source:t,beforeSnap:i,touchedIds:r,scheduledIds:a,hoursPerDay:n.sector.hoursPerDay})}}function u_(t,e){return!ue(t.type,e.adapter.hasChildren(t.id))}function Dy(t,e){return t.getTime()===e.getTime()}function p_(t){return new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()))}var _y=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function f_(t){let e={};for(let n of _y)Object.assign(e,{[n]:v(t[n])});return e}function y_(t,e){let n=[],i=r=>{e.has(String(r))&&n.push(r);for(let a of t.getChildren(r))i(a)};for(let r of t.getRootIds())i(r);return n}function Ey(t,e){let n=new Set(e.adapter.checkedIds().map(String));if(n.size===0)return{ok:!1,reason:_.NO_ACTIVITY_SELECTION};let i=y_(e.adapter,n);e.clipboard.value={activities:i.map(a=>{let o=e.adapter.getActivity(a);if(o===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:o.parentId??"0",overrides:f_(o)}}),links:e.adapter.getAllLinks().filter(a=>n.has(String(a.source))&&n.has(String(a.target))).map(a=>v(a))};let r=Zr({kind:I.SELECTION_REPLACE,activityIds:[]},{adapter:e.adapter});return r.ok?{...r,changes:{...r.changes,source:t}}:r}function Py(t,e){return e.value=null,{ok:!0,changes:{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}}function h_(t,e){let n=e.getActivity(t);return n?n.parentId==null?e.getRootIds().length===1?{ok:!0,parentId:n.id,beforeSiblingId:e.getChildren(n.id)[0]}:{ok:!0,parentId:"0",afterSiblingId:t}:e.hasChildren(n.id)?{ok:!0,parentId:n.id,beforeSiblingId:e.getChildren(n.id)[0]}:{ok:!0,parentId:String(n.parentId),afterSiblingId:t}:{ok:!1,reason:_.ANCHOR_SIBLING_NOT_FOUND}}var Ry=()=>({ok:!1,reason:_.ACTIVITY_PASTE_INVARIANT_FAILED});async function ky(t,e,n){let i=n.activityClipboard.value;if(i===null)return{ok:!1,reason:_.CLIPBOARD_EMPTY};let r=h_(t.destination.afterSiblingId,n.adapter);if(!r.ok)return r;let a=await ot(n.adapter,new Set),o=new Set,s=new Map,l=[],c;for(let m of i.activities){let h=s.get(m.originalParentId),A=h===void 0?c??r.afterSiblingId:void 0,T=h===void 0&&A===void 0?r.beforeSiblingId:void 0,b=await Er({kind:I.ACTIVITY_CREATE,parentId:h??r.parentId,...A===void 0?{}:{afterSiblingId:A},...T===void 0?{}:{beforeSiblingId:T},overrides:v(m.overrides),eventSource:t.eventSource},n,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:t.destination.afterSiblingId});if(!b.ok)return b;s.set(m.originalId,b.newId),l.push(b.newId),h===void 0&&(c=b.newId)}let d=xt(n.adapter),u=new Set(l.map(String));vi(n.adapter,d,u,a,o);for(let m of l)o.add(String(m));let p=[];for(let m of i.links){let h=s.get(m.source),A=s.get(m.target);if(h===void 0||A===void 0)return Ry();let T={kind:Et.CREATE,source:h,target:A,type:m.type,lag:m.lag},b=en(T,{port:n.adapter,newLinkId:n.linkIdGen.next});if(!b.applied)return Ry();p.push({op:T,finalLinkId:b.linkId,rejected:null})}let{scheduledIds:f}=await nt({adapter:n.adapter,scheduler:n.scheduler,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:l[0]??null,recomputeParentsFrom:l,now:n.now,options:e}),y=Pi(p,new Map,n.adapter);return{ok:!0,changes:await G(n.adapter,{source:t,beforeSnap:a,touchedIds:o,scheduledIds:f,links:y,hoursPerDay:n.sector.hoursPerDay})}}async function Ly(t,e,n){return t.kind===I.ACTIVITY_COPY?Ey(t,{adapter:n.adapter,clipboard:n.activityClipboard}):t.kind===I.CALENDAR_RECONCILE?Ty(t,e,n):t.kind===I.ACTIVITY_CLIPBOARD_CLEAR?Py(t,n.activityClipboard):t.kind===I.ACTIVITY_PASTE_COPIED?ky(t,e,n):t.kind===qe?Gf(t,e,n):t.kind===I.PERSISTENCE_ACKNOWLEDGE?Qf(t,n):t.kind===I.BASELINE_APPLY?Sy(t,n):t.kind===I.PONDERATOR_CRITERION_SET?vy(t,n):t.kind===I.STATUS_CRITERIA_SET?Cy(t,n):t.kind===I.LINK_CREATE||t.kind===I.LINK_UPDATE||t.kind===I.LINK_DELETE?Df(t,e,n):t.kind===I.LINKS_BATCH?Tf(t,e,n):t.kind===I.ACTIVITY_CREATE?Vf(t,e,n):t.kind===I.ACTIVITY_DELETE?jf(t,e,n):t.kind===I.ACTIVITY_MOVE?sy(t,e,n):t.kind===I.ACTIVITY_INDENT?ly(t,e,n):t.kind===I.ACTIVITY_OUTDENT?cy(t,e,n):t.kind===I.ACTIVITY_TYPE_SET?dy(t,e,n):t.kind===I.ACTIVITY_SET_PROGRESS?uy(t,e,n):t.kind===I.DATES_BATCH?py(t,e,n):t.kind===I.BULK_EDIT?fy(t,e,n):t.kind===I.SELECTION_TOGGLE?od(t,Yl(n)):t.kind===I.SELECTION_REPLACE?Zr(t,Yl(n)):t.kind===I.VISIBILITY_SET?sd(t,Yl(n)):t.kind===I.FILTER_SET?Cd(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.SORT_SET?Rd(t,{adapter:n.adapter}):t.kind===I.VIEW_ATTRIBUTES_SET?Od(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.GROUP_SET?bd(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.WBS_DEPTH_SET?Nd(t,{adapter:n.adapter,hoursPerDay:n.sector.hoursPerDay}):t.kind===I.SIR_SYNC?qf(t,n):t.kind===I.ACTIVITY_LOOKAHEAD_SYNC?ty(t,e,n):t.kind===I.ACTIVITY_LOOKAHEAD_CONVERT?iy(t,e,n):t.kind===I.SCHEDULE_AUTO_SCHEDULE?cf(t,e,n):t.kind===I.INLINE_EDIT&&(t.column===E.CUSTOM_PREDECESSORS||t.column===E.CUSTOM_SUCESSORS)?_f(t,e,n):t.kind!==I.INLINE_EDIT?Fd(t,`[ScheduleCore] dispatch kind "${t.kind}" not supported yet`):Cf(t,e,n)}function Yl(t){return{adapter:t.adapter}}var m_=new Set(["startDate","endDate","constraintDate"]);function Oy(t,e){return m_.has(t)&&typeof e=="string"?new Date(e):e}function by(t,e={}){let n=e.defaultUnit??dt.HOUR;return{getCalendar(i){let r=t.getCalendar(String(i));return r?g_(r,n):null}}}function g_(t,e){return{getClosestWorkTime(n){return t.getClosestWorkTime({date:n.date,dir:n.direction,unit:n.unit})},calculateEndDate(n,i){return t.calculateEndDate({start_date:n,duration:i,unit:e})},calculateDuration(n,i){return t.calculateDuration({start_date:n,end_date:i,unit:e})},isWorkTime(n,i){return t.isWorkTime({date:n,unit:i})},getWorkHours(n){return t.getWorkHours(n)}}}function A_(t){return Array.isArray?Array.isArray(t):t&&t.length!==void 0&&t.pop&&t.push}function zn(t){return t&&typeof t=="object"?!!(t.getFullYear&&t.getMonth&&t.getDate):!1}function Jn(t){return zn(t)&&!isNaN(t.getTime())}var I_={}.constructor.toString();function S_(t){var e=t.constructor.toString();return e!==I_}function v_(t){return t.$$typeof&&t.$$typeof.toString().includes("react.")}function ge(t){var e,n;if(t&&typeof t=="object")switch(!0){case zn(t):n=new Date(t);break;case A_(t):for(n=new Array(t.length),e=0;e<t.length;e++)n[e]=ge(t[e]);break;default:if(S_(t))n=Object.create(t);else{if(v_(t))return n=t,n;n={}}for(e in t)Object.prototype.hasOwnProperty.apply(t,[e])&&(n[e]=ge(t[e]));break}return n||t}function Mi(t,e,n){for(var i in e)(t[i]===void 0||n)&&(t[i]=e[i]);return t}function Ny(t){return typeof t<"u"}var Eo;function Gl(){return Eo||(Eo=new Date().valueOf()),Eo++,Eo}function te(t,e){return t.bind?t.bind(e):function(){return t.apply(e,arguments)}}var D_=(t,e,n)=>{t=t.replace(/%[a-zA-Z]/g,r=>{switch(r){case"%d":return`"+to_fixed(date.get${e?"UTC":""}Date())+"`;case"%m":return`"+to_fixed((date.get${e?"UTC":""}Month()+1))+"`;case"%j":return`"+date.get${e?"UTC":""}Date()+"`;case"%n":return`"+(date.get${e?"UTC":""}Month()+1)+"`;case"%y":return`"+to_fixed(date.get${e?"UTC":""}FullYear()%100)+"`;case"%Y":return`"+date.get${e?"UTC":""}FullYear()+"`;case"%D":return`"+locale.date.day_short[date.get${e?"UTC":""}Day()]+"`;case"%l":return`"+locale.date.day_full[date.get${e?"UTC":""}Day()]+"`;case"%M":return`"+locale.date.month_short[date.get${e?"UTC":""}Month()]+"`;case"%F":return`"+locale.date.month_full[date.get${e?"UTC":""}Month()]+"`;case"%h":return`"+to_fixed((date.get${e?"UTC":""}Hours()+11)%12+1)+"`;case"%g":return`"+((date.get${e?"UTC":""}Hours()+11)%12+1)+"`;case"%G":return`"+date.get${e?"UTC":""}Hours()+"`;case"%H":return`"+to_fixed(date.get${e?"UTC":""}Hours())+"`;case"%i":return`"+to_fixed(date.get${e?"UTC":""}Minutes())+"`;case"%a":return`"+(date.get${e?"UTC":""}Hours()>11?"pm":"am")+"`;case"%A":return`"+(date.get${e?"UTC":""}Hours()>11?"PM":"AM")+"`;case"%s":return`"+to_fixed(date.get${e?"UTC":""}Seconds())+"`;case"%W":return'"+to_fixed(getISOWeek(date))+"';case"%w":return'"+to_fixed(getWeek(date))+"';default:return r}});let i=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${t}";`);return r=>i(r,n.date.to_fixed,n.locale,n.date.getISOWeek,n.date.getWeek)},T_=(t,e,n)=>{let i="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",r=t.match(/%[a-zA-Z]/g);for(let s=0;s<r.length;s++)switch(r[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]";e&&(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,n.locale)},Fy={date_to_str:D_,str_to_date:T_},__=(t,e,n)=>i=>t.replace(/%[a-zA-Z]/g,r=>{switch(r){case"%d":return e?n.date.to_fixed(i.getUTCDate()):n.date.to_fixed(i.getDate());case"%m":return e?n.date.to_fixed(i.getUTCMonth()+1):n.date.to_fixed(i.getMonth()+1);case"%j":return e?i.getUTCDate():i.getDate();case"%n":return e?i.getUTCMonth()+1:i.getMonth()+1;case"%y":return e?n.date.to_fixed(i.getUTCFullYear()%100):n.date.to_fixed(i.getFullYear()%100);case"%Y":return e?i.getUTCFullYear():i.getFullYear();case"%D":return e?n.locale.date.day_short[i.getUTCDay()]:n.locale.date.day_short[i.getDay()];case"%l":return e?n.locale.date.day_full[i.getUTCDay()]:n.locale.date.day_full[i.getDay()];case"%M":return e?n.locale.date.month_short[i.getUTCMonth()]:n.locale.date.month_short[i.getMonth()];case"%F":return e?n.locale.date.month_full[i.getUTCMonth()]:n.locale.date.month_full[i.getMonth()];case"%h":return e?n.date.to_fixed((i.getUTCHours()+11)%12+1):n.date.to_fixed((i.getHours()+11)%12+1);case"%g":return e?(i.getUTCHours()+11)%12+1:(i.getHours()+11)%12+1;case"%G":return e?i.getUTCHours():i.getHours();case"%H":return e?n.date.to_fixed(i.getUTCHours()):n.date.to_fixed(i.getHours());case"%i":return e?n.date.to_fixed(i.getUTCMinutes()):n.date.to_fixed(i.getMinutes());case"%a":return e?i.getUTCHours()>11?"pm":"am":i.getHours()>11?"pm":"am";case"%A":return e?i.getUTCHours()>11?"PM":"AM":i.getHours()>11?"PM":"AM";case"%s":return e?n.date.to_fixed(i.getUTCSeconds()):n.date.to_fixed(i.getSeconds());case"%W":return e?n.date.to_fixed(n.date.getUTCISOWeek(i)):n.date.to_fixed(n.date.getISOWeek(i));case"%w":return n.date.to_fixed(n.date.getWeek(i));default:return r}}),E_=(t,e,n)=>i=>{let r=[0,0,1,0,0,0],a=i.match(/[a-zA-Z]+|[0-9]+/g),o=t.match(/%[a-zA-Z]/g);for(let s=0;s<o.length;s++)switch(o[s]){case"%j":case"%d":r[2]=a[s]||1;break;case"%n":case"%m":r[1]=(a[s]||1)-1;break;case"%y":r[0]=a[s]*1+(a[s]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":r[3]=a[s]||0;break;case"%i":r[4]=a[s]||0;break;case"%Y":r[0]=a[s]||0;break;case"%a":case"%A":r[3]=r[3]%12+((a[s]||"").toLowerCase()==="am"?0:12);break;case"%s":r[5]=a[s]||0;break;case"%M":r[1]=n.locale.date.month_short_hash[a[s]]||0;break;case"%F":r[1]=n.locale.date.month_full_hash[a[s]]||0;break}return e?new Date(Date.UTC(r[0],r[1],r[2],r[3],r[4],r[5])):new Date(r[0],r[1],r[2],r[3],r[4],r[5])},wy={date_to_str:__,str_to_date:E_};function xy(t){var e=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function n(s){var l=new Date(s);return isNaN(l.getTime())?null:l}var i=null;function r(){try{new Function("canUseCsp = false;")}catch{i=!0}}function a(){var s=!1;return t.config.csp==="auto"?(i===null&&r(),s=i):s=t.config.csp,s}var o={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(s){return s.toISOString()},formatISODateOnly:function(s){return s.getUTCFullYear()+"-"+t.date.to_fixed(s.getUTCMonth()+1)+"-"+t.date.to_fixed(s.getUTCDate())},init:function(){for(var s=t.locale,c=s.date.month_short,d=s.date.month_short_hash={},l=0;l<c.length;l++)d[c[l]]=l;for(var c=s.date.month_full,d=s.date.month_full_hash={},l=0;l<c.length;l++)d[c[l]]=l},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 l=s.getUTCDay();return t.config.start_on_monday&&(l===0?l=6:l--),this.date_part(this.add(s,-1*l,"day"))},month_start:function(s){return s.setUTCDate(1),this.date_part(s)},quarter_start:function(s){this.month_start(s);var l=s.getUTCMonth(),c;return l>=9?c=9:l>=6?c=6:l>=3?c=3:c=0,s.setUTCMonth(c),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,l,c){return s.setUTCDate(s.getUTCDate()+l),s},add:function(s,l,c){var d=new Date(s.valueOf());switch(c){case"day":d=this._add_days(d,l,s);break;case"week":d=this._add_days(d,l*7,s);break;case"month":d.setUTCMonth(d.getUTCMonth()+l);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+l);break;case"hour":d.setTime(d.getTime()+l*60*60*1e3);break;case"minute":d.setTime(d.getTime()+l*60*1e3);break;default:return this["add_"+c](s,l,c)}return d},add_quarter:function(s,l){return this.add(s,l*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,l){var c=Fy;return a()&&(c=wy),c.date_to_str(s,l,t)},str_to_date:function(s,l){var c=Fy;return a()&&(c=wy),c.str_to_date(s,l,t)},getISOWeek:function(s){return t.date._getWeekNumber(s,!0)},_getWeekNumber:function(s,l){if(!s)return!1;var c=s.getUTCDay();l&&c===0&&(c=7);var d=new Date(s.valueOf());d.setUTCDate(s.getUTCDate()+(4-c));var u=d.getUTCFullYear(),p=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),f=1+Math.floor(p/7);return f},getWeek:function(s){return t.date._getWeekNumber(s,t.config.start_on_monday)},getUTCISOWeek:function(s){return t.date.getISOWeek(s)},parseDate:function(s,l){if(s&&!s.getFullYear){var c=!l||l==="parse_date"||l==="xml_date",d=c&&(t.defined(t.templates.xml_date)||t.templates.parse_date&&!t.templates.parse_date._ganttAuto);if(!d&&typeof s=="string"&&e.test(s)){var u=s.indexOf("T")!==-1,p=n(s);if(p)return o._isoDateDetected?u&&(o._isoDateOnly=!1):(o._isoDateDetected=!0,o._isoDateOnly=!u),p}typeof l!="function"&&(typeof l=="string"?l==="parse_date"||l==="xml_date"?l=t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date:l=t.defined(t.templates[l])?t.templates[l]:t.date.str_to_date(l,!0):l=t.defined(t.templates.xml_date)?t.templates.xml_date:t.templates.parse_date),s?s=l(s):s=null}return s}};return o}function $l(t,e,n,i,r){return this.date=t,this.unit=e,this.task=n,this.id=i,this.calendar=r,this}function ql(t,e,n,i,r,a){return this.date=t,this.dir=e,this.unit=n,this.task=i,this.id=r,this.calendar=a,this}function zl(t,e,n,i,r,a,o){return this.start_date=t,this.duration=e,this.unit=n,this.step=i,this.task=r,this.id=a,this.calendar=o,this}function P_(t,e,n,i){return this.start_date=t,this.end_date=e,this.task=n,this.calendar=i,this.unit=null,this.step=null,this}var My=function(t){return{getWorkHoursArguments:function(){var e=arguments[0];if(zn(e)?e={date:e}:e=Mi({},e),!Jn(e.date))throw t.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return e},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var e=arguments[0];if(e instanceof $l)return e;var n;if(e.date?n=new $l(e.date,e.unit,e.task,null,e.calendar):n=new $l(arguments[0],arguments[1],arguments[2],null,arguments[3]),n.unit=n.unit||t.config.duration_unit,!Jn(n.date))throw t.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return n},getClosestWorkTimeArguments:function(e){var n=arguments[0];if(n instanceof ql)return n;var i;if(zn(n)?i=new ql(n):i=new ql(n.date,n.dir,n.unit,n.task,null,n.calendar),n.id&&(i.task=n),i.dir=n.dir||"any",i.unit=n.unit||t.config.duration_unit,!Jn(i.date))throw t.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return i},_getStartEndConfig:function(e){var n=P_,i;if(e instanceof n)return e;if(zn(e)?i=new n(arguments[0],arguments[1],arguments[2],arguments[3]):(i=new n(e.start_date,e.end_date,e.task),e.id!==null&&e.id!==void 0&&(i.task=e)),i.unit=i.unit||t.config.duration_unit,i.step=i.step||t.config.duration_step,i.start_date=i.start_date||i.start||i.date,!Jn(i.start_date))throw t.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!Jn(i.end_date))throw t.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return i},getDurationArguments:function(e,n,i,r){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(e,n,i,r){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(e,n,i,r){var a=arguments[0];if(a instanceof zl)return a;var o;if(zn(a)?o=new zl(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):o=new zl(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||t.config.duration_unit,o.step=o.step||t.config.duration_step,!Jn(o.start_date))throw t.assert(!1,"Invalid start_date argument for calculateEndDate method"),new Error("Invalid start_date argument for calculateEndDate method");return o}}};function Uy(){}Uy.prototype={_getIntervals:function(t){for(var e=[],n=0;n<t.length;n+=2)e.push({start:t[n],end:t[n+1]});return e},_toHoursArray:function(t){var e=[];function n(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,l=Math.floor(s/60);return o+":"+n(l)}for(var r=0;r<t.length;r++)e.push(i(t[r].start)+"-"+i(t[r].end));return e},_intersectHourRanges:function(t,e){var r=[],n=t.length>e.length?t:e,i=t===n?e:t;n=n.slice(),i=i.slice();for(var r=[],a=0;a<n.length;a++)for(var o=n[a],s=0;s<i.length;s++){var l=i[s];l.start<o.end&&l.end>o.start&&(r.push({start:Math.max(o.start,l.start),end:Math.min(o.end,l.end)}),o.end>l.end&&(i.splice(s,1),s--,a--))}return r},_mergeAdjacentIntervals:function(t){var e=t.slice();e.sort(function(a,o){return a.start-o.start});for(var n=e[0],i=1;i<e.length;i++){var r=e[i];r.start<=n.end?(r.end>n.end&&(n.end=r.end),e.splice(i,1),i--):n=r}return e},_mergeHoursConfig:function(t,e){return this._mergeAdjacentIntervals(this._intersectHourRanges(t,e))},merge:function(t,e){let n=ge(t.getConfig()),i=ge(e.getConfig()),r=n.parsed,a=i.parsed;r.customWeeks=n.customWeeks,a.customWeeks=i.customWeeks;var o={hours:this._toHoursArray(this._mergeHoursConfig(r.hours,a.hours)),dates:{},customWeeks:{}};let s=(c,d)=>{for(let u in c.dates){let p=c.dates[u];+u>1e3&&(o.dates[u]=!1);for(let f in d.dates){let y=d.dates[f];if(f==u&&(o.dates[u]=!!(p&&y)),Array.isArray(p)){let m=Array.isArray(y)?y:d.hours;o.dates[u]=this._toHoursArray(this._mergeHoursConfig(p,m))}}}};if(s(r,a),s(a,r),r.customWeeks)for(var l in r.customWeeks)o.customWeeks[l]=r.customWeeks[l];if(a.customWeeks)for(var l in a.customWeeks)o.customWeeks[l]?o.customWeeks[l+"_second"]=a.customWeeks[l]:o.customWeeks[l]=a.customWeeks[l];return o}};var Jl=class{constructor(){this.clear()}getItem(e,n,i){if(this._cache.has(e)){let a=this._cache.get(e)[i.getUTCFullYear()];if(a&&a.has(n))return a.get(n)}return-1}setItem(e,n,i,r){if(!e||!n)return;let a=this._cache,o=r.getUTCFullYear(),s;a.has(e)?s=a.get(e):(s=[],a.set(e,s));let l=s[o];l||(l=s[o]=new Map),l.set(n,i)}clear(){this._cache=new Map}},Xl=class{constructor(){this.clear()}getItem(e,n,i){let r=this._cache;if(r&&r[e]){let a=r[e];if(a===void 0)return-1;let o=a[i.getUTCFullYear()];if(o&&o[n]!==void 0)return o[n]}return-1}setItem(e,n,i,r){if(!e||!n)return;let a=this._cache;if(!a)return;a[e]||(a[e]=[]);let o=a[e],s=r.getUTCFullYear(),l=o[s];l||(l=o[s]={}),l[n]=i}clear(){this._cache={}}},Zl=class{constructor(e){this.getMinutesPerWeek=n=>{let i=n.valueOf();if(this._weekCache.has(i))return this._weekCache.get(i);let r=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(n));for(let l=0;l<7;l++)o+=r.getHoursPerDay(s)*60,s=a.date.add(s,1,"day");return this._weekCache.set(i,o),o},this.getMinutesPerMonth=n=>{let i=n.valueOf();if(this._monthCache.has(i))return this._monthCache.get(i);let r=this._calendar,a=this._calendar.$gantt,o=0,s=a.date.week_start(new Date(n)),l=a.date.add(s,1,"month").valueOf();for(;s.valueOf()<l;)o+=r.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=e}};function R_(){return typeof Map<"u"?new Jl:new Xl}var Ql=class{constructor(){this.clear()}_getCacheObject(e,n,i){let r=this._cache;r[n]||(r[n]=[]);let a=r[n];a||(a=r[n]={});let o=a[i];o||(o=a[i]={});let s=e.getUTCFullYear(),l=o[s];return l||(l=o[s]={durations:{},endDates:{}}),l}_endDateCacheKey(e,n){return String(e)+"-"+String(n)}_durationCacheKey(e,n){return String(e)+"-"+String(n)}getEndDate(e,n,i,r,a){let o=this._getCacheObject(e,i,r),s=e.valueOf(),l=this._endDateCacheKey(s,n),c;if(o.endDates[l]===void 0){let d=a(),u=d.valueOf();o.endDates[l]=u,o.durations[this._durationCacheKey(s,u)]=n,c=d}else c=new Date(o.endDates[l]);return c}getDuration(e,n,i,r,a){let o=this._getCacheObject(e,i,r),s=e.valueOf(),l=n.valueOf(),c=this._durationCacheKey(s,l),d;if(o.durations[c]===void 0){let u=a();o.durations[c]=u.valueOf(),d=u}else d=o.durations[c];return d}clear(){this._cache={}}};function tc(t,e){this.argumentsHelper=e,this.$gantt=t,this._workingUnitsCache=R_(),this._largeUnitsCache=new Zl(this),this._dateDurationCache=new Ql,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}tc.prototype={units:["year","month","week","day","hour","minute"],_clearCaches:function(){this._workingUnitsCache.clear(),this._largeUnitsCache.clear(),this._dateDurationCache.clear()},_getUnitOrder:function(t){for(var e=0,n=this.units.length;e<n;e++)if(this.units[e]==t)return e},_resetTimestampCache:function(){this._cached_timestamps={},this._cached_timestamps_count=0},_timestamp:function(t){this._cached_timestamps_count>1e6&&this._resetTimestampCache();var e=null;if(t.day||t.day===0)e=t.day;else if(t.date){var n=String(t.date.valueOf());this._cached_timestamps[n]?e=this._cached_timestamps[n]:(e=Date.UTC(t.date.getUTCFullYear(),t.date.getUTCMonth(),t.date.getUTCDate()),this._cached_timestamps[n]=e,this._cached_timestamps_count++)}return e},_checkIfWorkingUnit:function(t,e){if(!this["_is_work_"+e]){let n=this.$gantt.date[`${e}_start`](new Date(t)),i=this.$gantt.date.add(n,1,e);return this.hasDuration(n,i)}return this["_is_work_"+e](t)},_is_work_day:function(t){var e=this._getWorkHours(t);return Array.isArray(e)?e.length>0:!1},_is_work_hour:function(t){for(var e=this._getWorkHours(t),n=t.getUTCHours(),i=0;i<e.length;i++)if(n>=e[i].startHour&&n<e[i].endHour)return!0;return!1},_getTimeOfDayStamp:function(t,e){var n=t.getUTCHours();return!t.getUTCHours()&&!t.getUTCMinutes()&&e&&(n=24),n*60*60+t.getUTCMinutes()*60},_is_work_minute:function(t){for(var e=this._getWorkHours(t),n=this._getTimeOfDayStamp(t),i=0;i<e.length;i++)if(n>=e[i].start&&n<e[i].end)return!0;return!1},_nextDate:function(t,e,n){return this.$gantt.date.add(t,n,e)},_getWorkUnitsBetweenGeneric:function(t,e,n,i){var r=this.$gantt.date,a=new Date(t),o=new Date(e);i=i||1;var s=0,l=null,c,d,u=!1;c=r[n+"_start"](new Date(a)),c.valueOf()!=a.valueOf()&&(u=!0);var p=!1;d=r[n+"_start"](new Date(e)),d.valueOf()!=e.valueOf()&&(p=!0);for(var f=!1;a.valueOf()<o.valueOf();){if(l=this._nextDate(a,n,i),f=l.valueOf()>o.valueOf(),this._isWorkTime(a,n))(u||p&&f)&&(c=r[n+"_start"](new Date(a)),d=r.add(c,i,n)),u?(u=!1,l=this._nextDate(c,n,i),s+=(d.valueOf()-a.valueOf())/(d.valueOf()-c.valueOf())):p&&f?(p=!1,s+=(o.valueOf()-a.valueOf())/(d.valueOf()-c.valueOf())):s++;else{var y=this._getUnitOrder(n),m=this.units[y-1];m&&!this._isWorkTime(a,m)&&(l=this._getClosestWorkTimeFuture(a,m))}a=l}return s},_getMinutesPerHour:function(t){var e=this._getTimeOfDayStamp(t),n=this._getTimeOfDayStamp(this._nextDate(t,"hour",1));n===0&&(n=1440*60);for(var i=this._getWorkHours(t),r=0;r<i.length;r++){var a=i[r];if(e>=a.start&&n<=a.end)return 60;if(e<a.end&&n>a.start){var o=Math.min(n,a.end)-Math.max(e,a.start);return o/60}}return 0},_getMinutesPerDay:function(t){var e=this._getWorkHours(t),n=0;return e.forEach(function(i){n+=i.durationMinutes}),n},getHoursPerDay:function(t){var e=this._getWorkHours(t),n=0;return e.forEach(function(i){n+=i.durationHours}),n},_getWorkUnitsForRange:function(t,e,n,i){var r=0,a=new Date(t),o=new Date(e),s;for(n=="minute"?s=te(this._getMinutesPerDay,this):s=te(this.getHoursPerDay,this);a.valueOf()<o.valueOf();){if(o-a>1e3*60*60*24*32&&a.getUTCDate()===0){var l=this._largeUnitsCache.getMinutesPerMonth(a);n=="hour"&&(l=l/60),r+=l,a=this.$gantt.date.add(a,1,"month");continue}else if(o-a>1e3*60*60*24*16){var c=this.$gantt.date.week_start(new Date(a));if(a.valueOf()===c.valueOf()){var l=this._largeUnitsCache.getMinutesPerWeek(a);n=="hour"&&(l=l/60),r+=l,a=this.$gantt.date.add(a,7,"day");continue}}r+=s(a),a=this._nextDate(a,"day",1)}return r/i},_getMinutesBetweenSingleDay:function(t,e){for(var n=this._getIntervalTimestamp(t,e),i=this._getWorkHours(t),r=0,a=0;a<i.length;a++){var o=i[a];if(n.end>=o.start&&n.start<=o.end){var s=Math.max(o.start,n.start),l=Math.min(o.end,n.end);r+=(l-s)/60,n.start=l}}return Math.floor(r)},_getMinutesBetween:function(t,e,n,i){var r=new Date(t),a=new Date(e);i=i||1;var o=new Date(r),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(r)),1,"day");if(a.valueOf()<=s.valueOf())return this._getMinutesBetweenSingleDay(t,e);var l=this.$gantt.date.day_start(new Date(a)),c=a,d=this._getMinutesBetweenSingleDay(o,s),u=this._getMinutesBetweenSingleDay(l,c),p=this._getWorkUnitsForRange(s,l,n,i),f=d+p+u;return f},_getHoursBetween:function(t,e,n,i){var r=new Date(t),a=new Date(e);i=i||1;var o=new Date(r),s=this.$gantt.date.add(this.$gantt.date.day_start(new Date(r)),1,"day");if(a.valueOf()<=s.valueOf())return Math.round(this._getMinutesBetweenSingleDay(t,e)/60);var l=this.$gantt.date.day_start(new Date(a)),c=a,d=this._getMinutesBetweenSingleDay(o,s,n,i)/60,u=this._getMinutesBetweenSingleDay(l,c,n,i)/60,p=this._getWorkUnitsForRange(s,l,n,i),f=d+p+u;return Math.round(f)},getConfig:function(){return this._worktime},_setConfig:function(t){this._worktime=t,this._parseSettings(),this._clearCaches()},_parseSettings:function(){var t=this.getConfig();t.parsed={dates:{},hours:null,haveCustomWeeks:!1,customWeeks:{},customWeeksRangeStart:null,customWeeksRangeEnd:null,customWeeksBoundaries:[]},t.parsed.hours=this._parseHours(t.hours);for(var e in t.dates)t.parsed.dates[e]=this._parseHours(t.dates[e]);if(t.customWeeks){var n=null,i=null;for(var e in t.customWeeks){var r=t.customWeeks[e];if(r.from&&r.to){var a=r.from,o=r.to;(!n||n>a.valueOf())&&(n=a.valueOf()),(!i||i<o.valueOf())&&(i=o.valueOf()),t.parsed.customWeeksBoundaries.push({from:a.valueOf(),fromReadable:new Date(a),to:o.valueOf(),toReadable:new Date(o),name:e}),t.parsed.haveCustomWeeks=!0;var s=t.parsed.customWeeks[e]={from:r.from,to:r.to,hours:this._parseHours(r.hours),dates:{}};if(r.days&&!r.dates){r.dates=r.dates||{};for(var e=0;e<r.days.length;e++)r.dates[e]=r.days[e],r.days[e]instanceof Array||(r.dates[e]=!!r.days[e]);delete r.days}for(var l in r.dates)s.dates[l]=this._parseHours(r.dates[l])}}t.parsed.customWeeksRangeStart=n,t.parsed.customWeeksRangeEnd=i}},_tryChangeCalendarSettings:function(t){var e=JSON.stringify(this.getConfig());return t(),this.hasWorkTime()?!0:(this._setConfig(JSON.parse(e)),this._clearCaches(),!1)},_arraysEqual:function(t,e){if(t===e)return!0;if(!t||!e||t.length!=e.length)return!1;for(var n=0;n<t.length;++n)if(t[n]!==e[n])return!1;return!0},_compareSettings:function(t,e){if(!this._arraysEqual(t.hours,e.hours))return!1;var n=Object.keys(t.dates),i=Object.keys(e.dates);if(n.sort(),i.sort(),!this._arraysEqual(n,i))return!1;for(var r=0;r<n.length;r++){var a=n[r],o=t.dates[a],s=e.dates[a];if(o!==s&&!(Array.isArray(o)&&Array.isArray(s)&&this._arraysEqual(o,s)))return!1}return!0},equals:function(t){if(!(t instanceof tc))return!1;var e=this.getConfig(),n=t.getConfig();if(!this._compareSettings(e,n))return!1;if(e.parsed.haveCustomWeeks&&n.parsed.haveCustomWeeks){if(e.parsed.customWeeksBoundaries.length!=n.parsed.customWeeksBoundaries.length)return!1;for(var i in e.parsed.customWeeks){var r=e.parsed.customWeeks[i],a=n.parsed.customWeeks[i];if(!a||!this._compareSettings(r,a))return!1}}else if(e.parse.haveCustomWeeks!==n.parsed.haveCustomWeeks)return!1;return!0},getWorkHours:function(){var t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);return this._getWorkHours(t.date,!1)},_getWorkHours:function(t,e){var n=this.getConfig();if(e!==!1&&(n=n.parsed),!t)return n.hours;let i=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()));var r=this._timestamp({date:i});if(n.haveCustomWeeks&&n.customWeeksRangeStart<=r&&n.customWeeksRangeEnd>r){for(var a=0;a<n.customWeeksBoundaries.length;a++)if(n.customWeeksBoundaries[a].from<=r&&n.customWeeksBoundaries[a].to>r){n=n.customWeeks[n.customWeeksBoundaries[a].name];break}}var o=!0;return n.dates[r]!==void 0?o=n.dates[r]:n.dates[t.getUTCDay()]!==void 0&&(o=n.dates[t.getUTCDay()]),o===!0?n.hours:o||[]},_getIntervalTimestamp:function(t,e){var n={start:0,end:0};n.start=t.getUTCHours()*60*60+t.getUTCMinutes()*60+t.getUTCSeconds();var i=e.getUTCHours();return!i&&!e.getUTCMinutes()&&!e.getUTCSeconds()&&t.valueOf()<e.valueOf()&&(i=24),n.end=i*60*60+e.getUTCMinutes()*60+e.getUTCSeconds(),n},_parseHours:function(t){if(Array.isArray(t)){var e=[];t.forEach(function(s){typeof s=="number"?e.push(s*60*60):typeof s=="string"&&s.split("-").map(function(l){return l.trim()}).forEach(function(l){var c=l.split(":").map(function(u){return u.trim()}),d=parseInt(c[0]*60*60);c[1]&&(d+=parseInt(c[1]*60)),c[2]&&(d+=parseInt(c[2])),e.push(d)})});for(var n=[],i=0;i<e.length;i+=2){var r=e[i],a=e[i+1],o=a-r;n.push({start:r,end:a,startHour:Math.floor(r/3600),startMinute:Math.floor(r/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:o,durationMinutes:o/60,durationHours:o/3600})}return n}else return t},setWorkTime:function(t){return this._tryChangeCalendarSettings(te(function(){var e=t.hours!==void 0?t.hours:!0,n=this._timestamp(t),i=this.getConfig();if(n!==null?i.dates[n]=e:t.customWeeks||(i.hours=e),t.customWeeks){if(i.customWeeks||(i.customWeeks={}),typeof t.customWeeks=="string")n!==null?i.customWeeks[t.customWeeks].dates[n]=e:t.customWeeks||(i.customWeeks[t.customWeeks].hours=e);else if(typeof t.customWeeks=="object"&&t.customWeeks.constructor===Object)for(var r in t.customWeeks)i.customWeeks[r]=t.customWeeks[r]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(t){return this._tryChangeCalendarSettings(te(function(){if(!t)this.reset_calendar();else{var e=this._timestamp(t);e!==null&&delete this.getConfig().dates[e]}this._parseSettings(),this._clearCaches()},this))},_isWorkTime:function(t,e){var n=-1,i=null;return i=String(t.valueOf()),n=this._workingUnitsCache.getItem(e,i,t),n==-1&&(n=this._checkIfWorkingUnit(t,e),this._workingUnitsCache.setItem(e,i,n,t)),n},isWorkTime:function(){var t=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._isWorkTime(t.date,t.unit)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments);if(!t.unit)return!1;var e=this;return this._dateDurationCache.getDuration(t.start_date,t.end_date,t.unit,t.step,function(){return e._calculateDuration(t.start_date,t.end_date,t.unit,t.step)})},_calculateDuration:function(t,e,n,i){var r=0,a=1;if(t.valueOf()>e.valueOf()){var o=e;e=t,t=o,a=-1}return n=="hour"&&i==1?r=this._getHoursBetween(t,e,n,i):n=="minute"&&i==1?r=this._getMinutesBetween(t,e,n,i):r=this._getWorkUnitsBetweenGeneric(t,e,n,i),a*Math.round(r)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,i=t.unit,r=t.step;if(!i)return!1;var a=new Date(e),o=new Date(n);for(r=r||1;a.valueOf()<o.valueOf();){if(this._isWorkTime(a,i))return!0;a=this._nextDate(a,i,r)}return!1},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,i=t.unit,r=t.step;if(!i)return!1;var a=t.duration>=0?1:-1;n=Math.abs(n*1);var o=this;return this._dateDurationCache.getEndDate(e,n,i,r*a,function(){return o._calculateEndDate(e,n,i,r*a)})},_calculateEndDate:function(t,e,n,i){if(!n)return!1;if(i==1&&n=="minute")return this._calculateMinuteEndDate(t,e,i);if(i==-1&&n=="minute")return this._subtractMinuteDate(t,e,i);if(i==1&&n=="hour")return this._calculateHourEndDate(t,e,i);var r=this._addInterval(t,e,n,i,null);return r.end},_addInterval:function(t,e,n,i,r){for(var a=0,o=t;a<e&&!(r&&r(o));){var s=this._nextDate(o,n,i),l=new Date(s.valueOf()+1);i>0&&(l=new Date(s.valueOf()-1));var c=this._isWorkTime(l,n);c&&a++,o=s}return{end:o,start:t,added:a}},_addHoursUntilDayEnd:function(t,e){for(var n=this.$gantt.date.add(this.$gantt.date.day_start(new Date(t)),1,"day"),i=0,r=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&i<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),d=Math.min(l.end,a.end),u=(d-c)/3600;u>r&&(u=r,d=c+r*60*60);var p=Math.round((d-c)/3600);i+=p,r-=p,a.start=d}}var f=n;return i===e&&(f=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,a.start))),{added:i,end:f}},_calculateHourEndDate:function(t,e,n){var i=new Date(t),r=0;n=n||1,e=Math.abs(e*1);var a=this._addHoursUntilDayEnd(i,e);r=a.added,i=a.end;var o=e-r;if(o){for(var s=i;r<e;){var l=this._nextDate(s,"day",n);l.setUTCHours(0),l.setUTCMinutes(0),l.setUTCSeconds(0);var c=0;if(n>0?c=this.getHoursPerDay(new Date(l.valueOf()-1)):c=this.getHoursPerDay(new Date(l.valueOf()+1)),r+c>=e)break;r+=c,s=l}i=s}if(r<e){var o=e-r;a=this._addHoursUntilDayEnd(i,o),i=a.end}return i},_addMinutesUntilHourEnd:function(t,e){if(t.getUTCMinutes()===0)return{added:0,end:new Date(t)};for(var n=this.$gantt.date.add(this.$gantt.date.hour_start(new Date(t)),1,"hour"),i=0,r=e,a=this._getIntervalTimestamp(t,n),o=this._getWorkHours(t),s=0;s<o.length&&i<e;s++){var l=o[s];if(a.end>=l.start&&a.start<=l.end){var c=Math.max(l.start,a.start),d=Math.min(l.end,a.end),u=(d-c)/60;u>r&&(u=r,d=c+r*60);var p=Math.round((d-c)/60);r-=p,i+=p,a.start=d}}var f=n;return i===e&&(f=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,a.start))),{added:i,end:f}},_subtractMinutesUntilHourStart:function(t,e){for(var n=this.$gantt.date.hour_start(new Date(t)),i=0,r=e,a=n.getUTCHours()*60*60+n.getUTCMinutes()*60+n.getUTCSeconds(),o=t.getUTCHours()*60*60+t.getUTCMinutes()*60+t.getUTCSeconds(),s=this._getWorkHours(t),l=s.length-1;l>=0&&i<e;l--){var c=s[l];if(o>c.start&&a<=c.end){var d=Math.min(o,c.end),u=Math.max(a,c.start),p=(d-u)/60;p>r&&(p=r,u=d-r*60);var f=Math.abs(Math.round((d-u)/60));r-=f,i+=f,o=u}}var y=n;return i===e&&(y=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),0,0,o))),{added:i,end:y}},_subtractMinuteDate:function(t,e,n){var i=this.getClosestWorkTime({date:t,dir:"past",unit:"minute"}),r=0;n=n||-1,e=Math.abs(e*1),e=Math.round(e);let a=this._isMinutePrecision(i),o=this._subtractMinutesUntilHourStart(i,e);r+=o.added,i=o.end;for(var s=0,l=[],c=0;r<e;){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 p=new Date(Date.UTC(d.getUTCFullYear(),d.getUTCMonth(),d.getUTCDate(),23,59,59,999)).valueOf();p!==s&&(l=this._getWorkHours(d),c=this._getMinutesPerDay(d),s=p);var f=e-r,y=this._getTimeOfDayStamp(i,u);if(!l.length||!c){i=this.$gantt.date.add(i,-1,"day");continue}if(l[l.length-1].end<=y&&f>c){r+=c,i=this.$gantt.date.add(i,-1,"day");continue}for(var m=!1,h=null,A=null,T=l.length-1;T>=0;T--)if(l[T].start<y-1&&l[T].end>=y-1){m=!0,h=l[T],A=l[T-1];break}if(m)if(y===h.end&&f>=h.durationMinutes)r+=h.durationMinutes,i=this.$gantt.date.add(i,-h.durationMinutes,"minute");else if(!a&&f<=y/60-h.startMinute)r+=f,i=this.$gantt.date.add(i,-f,"minute");else if(a)f<=y/60-h.startMinute?(r+=f,i=this.$gantt.date.add(i,-f,"minute")):(r+=y/60-h.startMinute,A?i=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,A.end)):i=this.$gantt.date.day_start(i));else{var b=this._getMinutesPerHour(i);b<=f?(r+=b,i=this._nextDate(i,"hour",n)):(o=this._subtractMinutesUntilHourStart(i,f),r+=o.added,i=o.end)}else if(i.getUTCHours()===0&&i.getUTCMinutes()===0&&i.getUTCSeconds()===0){var S=this._getClosestWorkTimePast(i,"hour");if(S.valueOf()===i.valueOf()){var S=this.$gantt.date.add(i,-1,"day"),g=this._getWorkHours(S);if(g.length){var w=g[g.length-1];S.setUTCSeconds(w.durationSeconds)}}i=S}else i=this._getClosestWorkTimePast(new Date(i-1),"hour")}if(r<e){var R=e-r;o=this._subtractMinutesUntilHourStart(i,R),r+=o.added,i=o.end}return i},_calculateMinuteEndDate:function(t,e,n){var i=new Date(t),r=0;n=n||1,e=Math.abs(e*1),e=Math.round(e);var a=this._addMinutesUntilHourEnd(i,e);r+=a.added,i=a.end;for(var o=0,s=[],l=0,c=this._isMinutePrecision(i);r<e;){var d=this.$gantt.date.day_start(new Date(i)).valueOf();d!==o&&(s=this._getWorkHours(i),l=this._getMinutesPerDay(i),o=d);var u=e-r,p=this._getTimeOfDayStamp(i);if(!s.length||!l){i=this.$gantt.date.add(this.$gantt.date.day_start(i),1,"day");continue}if(s[0].start>=p&&u>=l){if(r+=l,u==l){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 f=!1,y=null,m=0;m<s.length;m++)if(s[m].start<=p&&s[m].end>p){f=!0,y=s[m];break}if(f)if(p===y.start&&u>=y.durationMinutes)r+=y.durationMinutes,i=this.$gantt.date.add(i,y.durationMinutes,"minute");else if(u<=y.endMinute-p/60)r+=u,i=this.$gantt.date.add(i,u,"minute");else{var h=this._getMinutesPerHour(i);h<=u?(r+=h,c?i=this.$gantt.date.add(i,h,"minute"):i=this._nextDate(i,"hour",n)):(a=this._addMinutesUntilHourEnd(i,u),r+=a.added,i=a.end)}else i=this._getClosestWorkTimeFuture(i,"hour")}if(r<e){var A=e-r;a=this._addMinutesUntilHourEnd(i,A),r+=a.added,i=a.end}return i},getClosestWorkTime:function(){var t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(t.date,t.unit,t.dir)},_getClosestWorkTime:function(t,e,n){var i=new Date(t);if(this._isWorkTime(i,e))return i;if(i=this.$gantt.date[e+"_start"](i),n=="any"||!n){var r=this._getClosestWorkTimeFuture(i,e),a=this._getClosestWorkTimePast(i,e);Math.abs(r-t)<=Math.abs(t-a)?i=r:i=a}else n=="past"?i=this._getClosestWorkTimePast(i,e):i=this._getClosestWorkTimeFuture(i,e);return i},_getClosestWorkTimeFuture:function(t,e){return this._getClosestWorkTimeGeneric(t,e,1)},_getClosestWorkTimePast:function(t,e){var n=this._getClosestWorkTimeGeneric(t,e,-1);return this.$gantt.date.add(n,1,e)},_findClosestTimeInDay:function(t,e,n){var i=new Date(t),r=null,a=!1;this._getWorkHours(i).length||(i=this._getClosestWorkTime(i,"day",e<0?"past":"future"),e<0&&(i=new Date(i.valueOf()-1),a=!0),n=this._getWorkHours(i));var o=this._getTimeOfDayStamp(i);if(a&&(o=this._getTimeOfDayStamp(new Date(i.valueOf()+1),a)),e>0){for(var s=0;s<n.length;s++)if(n[s].start>=o){r=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,n[s].start));break}}else for(var s=n.length-1;s>=0;s--)if(n[s].end<=o){r=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,n[s].end));break}else if(n[s].end>o&&n[s].start<=o){r=new Date(Date.UTC(i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate(),0,0,o));break}return r},_getClosestWorkMinute:function(t,e,n){var i=new Date(t),r=this._getWorkHours(i),a=this._findClosestTimeInDay(i,n,r);return a||(n>0?(i=this.calculateEndDate(i,n,e),i=this.$gantt.date.day_start(i)):(i=this.calculateEndDate(i,n,"day"),i=this.$gantt.date.day_start(i),i=this.$gantt.date.add(i,1,"day"),i=new Date(i.valueOf()-1)),r=this._getWorkHours(i),a=this._findClosestTimeInDay(i,n,r)),n<0&&(a=this.$gantt.date.add(a,-1,e)),a},_getClosestWorkTimeGeneric:function(t,e,n){if(e==="hour"||e==="minute")return this._getClosestWorkMinute(t,e,n);for(var i=this._getUnitOrder(e),r=this.units[i-1],a=t,o=3e3,s=0;!this._isWorkTime(a,e)&&!(r&&!this._isWorkTime(a,r)&&(n>0?a=this._getClosestWorkTimeFuture(a,r):a=this._getClosestWorkTimePast(a,r),this._isWorkTime(a,e)));){if(s++,s>o)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,n,e),this.$gantt.date[e+"_start"]&&(a=this.$gantt.date[e+"_start"](a))}return a},hasWorkTime:function(){var t=this.getConfig(),e=t.dates,n=[0,1,2,3,4,5,6];for(var i in t.dates);var r=this._checkWorkHours(t.hours),a=!1;return n.forEach((function(o){if(!a){var s=e[o];s===!0?a=r:Array.isArray(s)&&(a=this._checkWorkHours(s))}}).bind(this)),a},_checkWorkHours:function(t){if(t.length===0)return!1;for(var e=!1,n=0;n<t.length;n+=2)t[n]!==t[n+1]&&(e=!0);return e},_isMinutePrecision:function(t){let e=!1;return this._getWorkHours(t).forEach(function(n){(n.startMinute%60||n.endMinute%60)&&(e=!0)}),e}};var Pr={isLegacyResourceCalendarFormat:function(t){if(!t)return!1;for(var e in t)if(t[e]&&typeof t[e]=="object")return!0;return!1},getResourceProperty:function(t){var e=t.resource_calendars,n=t.resource_property;if(this.isLegacyResourceCalendarFormat(e))for(var i in t){n=i;break}return n},getCalendarIdFromLegacyConfig:function(t,e){if(e)for(var n in e){var i=e[n];if(t[n]){var r=i[t[n]];if(r)return r}}return null}};function k_(){function t(r){return r.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var e={};function n(r,a){return a.mergeCalendars(r.map(function(o){var s=o&&o.resource_id?o.resource_id:o;return a.getResourceCalendar(s)}))}function i(r,a){var o=t(r);if(r.length){if(r.length===1)return a.getResourceCalendar(o).id;if(e[o])return e[o].id;var s=n(r,a);return e[o]=s,a.addCalendar(s)}else return null}return{getCalendarIdFromMultipleResources:i}}var L_=k_();function Hy(t){this.$gantt=t,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))}Hy.prototype={_calendars:{},_convertWorkTimeSettings:function(t){let e=t.days;if(typeof e=="object"&&!Array.isArray(e)&&e!==null){let n={};if(e?.weekdays)for(let i=0;i<7;i++)n[i]=e.weekdays[i];e?.dates&&Object.entries(e.dates).forEach(([i,r])=>{n[new Date(i).valueOf()]=r}),Object.entries(n).forEach(([i,r])=>{r instanceof Array||(n[i]=!!r)}),t={...t,dates:n}}else if(e&&!t.dates){t.dates=t.dates||{};for(let n=0;n<e.length;n++)t.dates[n]=e[n],e[n]instanceof Array||(t.dates[n]=!!e[n])}return delete t.days,t},mergeCalendars:function(){var t=[],e=arguments;if(Array.isArray(e[0]))t=e[0].slice();else for(var n=0;n<arguments.length;n++)t.push(arguments[n]);var i=new Uy,r;return t.forEach((function(a){r?r=this._createCalendarFromConfig(i.merge(r,a)):r=a}).bind(this)),this.createCalendar(r)},_createCalendarFromConfig:function(t){var e=new tc(this.$gantt,My(this.$gantt));e.id=String(Gl());var n=this._convertWorkTimeSettings(t);if(n.customWeeks)for(var i in n.customWeeks)n.customWeeks[i]=this._convertWorkTimeSettings(n.customWeeks[i]);return e._setConfig(n),e},createCalendar:function(t){var e;t||(t={}),t.getConfig?e=ge(t.getConfig()):t.worktime?e=ge(t.worktime):e=ge(t);var n=ge(this.defaults.fulltime.worktime);return Mi(e,n),this._createCalendarFromConfig(e)},getCalendar:function(t){t=t||"global";var e=this._calendars[t];return e||(this.createDefaultCalendars(),e=this._calendars[t]),e},getCalendars:function(){var t=[];for(var e in this._calendars)t.push(this.getCalendar(e));return t},_getOwnCalendar:function(t){var e=this.$gantt.config;if(t[e.calendar_property])return this.getCalendar(t[e.calendar_property]);if(e.resource_calendars){var n,i,r;if(this._legacyConfig===!1?r=e.resource_property:r=Pr.getResourceProperty(e),Array.isArray(t[r])&&t[r].length)e.dynamic_resource_calendars?i=L_.getCalendarIdFromMultipleResources(t[r],this):n=this.getResourceCalendar(t[r]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Pr.isLegacyResourceCalendarFormat(e.resource_calendars)),this._legacyConfig)var i=Pr.getCalendarIdFromLegacyConfig(t,e.resource_calendars);else if(r&&t[r]&&e.resource_calendars[t[r]])var n=this.getResourceCalendar(t[r]);if(i&&(n=this.getCalendar(i)),n)return n}return null},getResourceCalendar:function(t){if(t==null)return this.getCalendar();var e=null;typeof t=="number"||typeof t=="string"?e=t:e=t.id||t.key;var n=this.$gantt.config,i=n.resource_calendars,r=null;if(Array.isArray(t)&&t.length===1&&(typeof t[0]=="object"?e=t[0].resource_id:e=t[0]),i){if(this._legacyConfig===void 0&&(this._legacyConfig=Pr.isLegacyResourceCalendarFormat(n.resource_calendars)),this._legacyConfig){for(var a in i)if(i[a][e]){r=i[a][e];break}}else var r=i[e];if(r)return this.getCalendar(r)}return this.getCalendar()},getTaskCalendar:function(t){var e=this.$gantt,n;if(t==null)return this.getCalendar();if((typeof t=="number"||typeof t=="string")&&e.isTaskExists(t)?n=e.getTask(t):n=t,!n)return this.getCalendar();var i=this._getOwnCalendar(n),r=!!e.getState().group_mode;if(!i&&e.config.inherit_calendar&&e.isTaskExists(n.parent)){for(var a=n;e.isTaskExists(a.parent)&&(a=e.getTask(a.parent),!(e.isSummaryTask(a)&&(i=this._getOwnCalendar(a),i))););r&&!i&&t.$effective_calendar&&(i=this.getCalendar(t.$effective_calendar))}return i||this.getCalendar()},addCalendar:function(t){if(!this.isCalendar(t)){var e=t.id;t=this.createCalendar(t),t.id=e}if(t._tryChangeCalendarSettings(function(){})){var n=this.$gantt.config;return t.id=t.id||Gl(),this._calendars[t.id]=t,n.worktimes||(n.worktimes={}),n.worktimes[t.id]=t.getConfig(),t.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},t]),null},deleteCalendar:function(t){var e=this.$gantt.config;return t&&this._calendars[t]?(delete this._calendars[t],e.worktimes&&e.worktimes[t]&&delete e.worktimes[t],!0):!1},restoreConfigCalendars:function(t){for(var e in t)if(!this._calendars[e]){var n=t[e],i=this.createCalendar(n);i.id=e,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 t=this.$gantt.config;this.restoreConfigCalendars(this.defaults),this.restoreConfigCalendars(t.worktimes)},isCalendar:function(t){var e=[t.isWorkTime,t.setWorkTime,t.getWorkHours,t.unsetWorkTime,t.getClosestWorkTime,t.calculateDuration,t.hasDuration,t.calculateEndDate];return e.every(function(n){return n instanceof Function})}};function ec(t,e){this.argumentsHelper=e,this.$gantt=t}ec.prototype={getWorkHours:function(){return[0,24]},setWorkTime:function(){return!0},unsetWorkTime:function(){return!0},isWorkTime:function(){return!0},getClosestWorkTime:function(e){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return e.date},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,i=t.unit,r=t.step;return this._calculateDuration(e,n,i,r)},_calculateDuration:function(t,e,n,i){var r=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[n])o=Math.round((e-t)/(i*a[n]));else{for(var s=new Date(t),l=new Date(e);s.valueOf()<l.valueOf();)o+=1,s=r.add(s,i,n);s.valueOf()!=e.valueOf()&&(o+=(l-s)/(r.add(s,i,n)-s))}return Math.round(o)},hasDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.end_date,i=t.unit;return i?(e=new Date(e),n=new Date(n),e.valueOf()<n.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(t){return t instanceof ec},calculateEndDate:function(){var t=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),e=t.start_date,n=t.duration,i=t.unit,r=t.step;return this.$gantt.date.add(e,r*n,i)}};function By(t){this.$gantt=t.$gantt,this.argumentsHelper=My(this.$gantt),this.calendarManager=t,this.$disabledCalendar=new ec(this.$gantt,this.argumentsHelper)}By.prototype={_getCalendar:function(t){var e;if(!this.$gantt.config.work_time)e=this.$disabledCalendar;else{var n=this.calendarManager;t.task?e=n.getTaskCalendar(t.task):t.id?e=n.getTaskCalendar(t):t.calendar&&(e=t.calendar),e||(e=n.getTaskCalendar())}return e},getWorkHours:function(t){t=this.argumentsHelper.getWorkHoursArguments.apply(this.argumentsHelper,arguments);var e=this._getCalendar(t);return e.getWorkHours(t.date)},setWorkTime:function(t,e){return t=this.argumentsHelper.setWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.setWorkTime(t)},unsetWorkTime:function(t,e){return t=this.argumentsHelper.unsetWorkTimeArguments.apply(this.argumentsHelper,arguments),e||(e=this.calendarManager.getCalendar()),e.unsetWorkTime(t)},isWorkTime:function(t,e,n,i){var r=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return i=this._getCalendar(r),i.isWorkTime(r)},getClosestWorkTime:function(t){t=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);var e=this._getCalendar(t);return e.getClosestWorkTime(t)},calculateDuration:function(){var t=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),e=this._getCalendar(t);return e.calculateDuration(t)},hasDuration:function(){var t=this.argumentsHelper.hasDurationArguments.apply(this.argumentsHelper,arguments),e=this._getCalendar(t);return e.hasDuration(t)},calculateEndDate:function(e){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),n=this._getCalendar(e);return n.calculateEndDate(e)}};var O_=function(t,e){return{getWorkHours:function(n){return e.getWorkHours(n)},setWorkTime:function(n){return e.setWorkTime(n)},unsetWorkTime:function(n){e.unsetWorkTime(n)},isWorkTime:function(n,i,r){return e.isWorkTime(n,i,r)},getClosestWorkTime:function(n){return e.getClosestWorkTime(n)},calculateDuration:function(n,i,r){return e.calculateDuration(n,i,r)},_hasDuration:function(n,i,r){return e.hasDuration(n,i,r)},calculateEndDate:function(n,i,r,a){return e.calculateEndDate(n,i,r,a)},mergeCalendars:te(t.mergeCalendars,t),createCalendar:te(t.createCalendar,t),addCalendar:te(t.addCalendar,t),getCalendar:te(t.getCalendar,t),getCalendars:te(t.getCalendars,t),getResourceCalendar:te(t.getResourceCalendar,t),getTaskCalendar:te(t.getTaskCalendar,t),deleteCalendar:te(t.deleteCalendar,t)}},b_={create:O_};function jy(t){var e=new Hy(t),n=new By(e),i=b_.create(e,n);Mi(t,i)}var Wy={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 Vy(t={}){let e=t.config||{},n={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},e),locale:t.locale||Wy,templates:t.templates||{},getTask:t.getTask||function(i){return null},isTaskExists:t.isTaskExists||function(i){return!1},isSummaryTask:t.isSummaryTask||function(i){return!1},getState:function(){return{group_mode:!1}},callEvent:function(i,r){let a=t.onEvent;return a&&a(i,r),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Ny,mixin:Mi,copy:ge,assert:function(i,r){if(!i){if(t.throwOnAssert)throw new Error("[calendar] "+r);t.silent!==!0&&console.error("[calendar]",r)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return n._correct_dst_change=function(i){return i},n.date=xy(n),n.date.init(),jy(n),n}function N_(t={}){let e=Vy(t);return{addCalendar:function(n){return e.addCalendar(n)},deleteCalendar:function(n){return e.deleteCalendar(n)},getCalendar:function(n){return e.getCalendar(n)},getCalendars:function(){return e.getCalendars()},mergeCalendars:function(){return e.mergeCalendars.apply(e,arguments)},getTaskCalendar:function(n){return e.getTaskCalendar(n)},getResourceCalendar:function(n){return e.getResourceCalendar(n)},setWorkTime:function(n){return e.setWorkTime(n)},unsetWorkTime:function(n){return e.unsetWorkTime(n)},isWorkTime:function(){return e.isWorkTime.apply(e,arguments)},getClosestWorkTime:function(){return e.getClosestWorkTime.apply(e,arguments)},getWorkHours:function(){return e.getWorkHours.apply(e,arguments)},calculateDuration:function(){return e.calculateDuration.apply(e,arguments)},calculateEndDate:function(){return e.calculateEndDate.apply(e,arguments)},_internals:e}}var Ky={createCalendar:N_};var nz=3600*1e3;function qy(t){return{getActivity(e){return t.getActivity(e)}}}var{createCalendar:F_}=Ky,Rr="__replay_default__";function w_(t){if(!t||t.length===0||typeof t[0]=="string")return t;let e=t.map(Number);if(e.some(a=>Number.isNaN(a)))return t;let n=e[0],i=e[e.length-1];return e.every((a,o)=>a===n+o)?[`${n}:00-${i+1}:00`]:t}var Yy={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Gy="__main_global__",x_={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function $y(t){return!t||t.hours===void 0||t.hours.length>0||t.days?.some(e=>Array.isArray(e)&&e.length>0)===!0?!0:Object.values(t.dates??{}).some(e=>Array.isArray(e)&&e.length>0)}function M_(t){let e={};if(Array.isArray(t.days))for(let i=0;i<t.days.length;i+=1)e[i]=t.days[i];if(t.dates)for(let[i,r]of Object.entries(t.dates))e[i]=r;let n={hours:w_(t.hours),dates:e};return t.customWeeks&&(n.customWeeks=t.customWeeks),n}function Po(t){let e=F_({config:{work_time:!0}});e.addCalendar({id:Rr,worktime:Yy}),e.addCalendar({id:Gy,worktime:x_});let n=new Set(t.filter(d=>!$y(d.worktime)).map(d=>String(d.id))),i=t.filter(d=>$y(d.worktime));for(let d of i)e.addCalendar({id:d.id,worktime:d.worktime?M_(d.worktime):Yy});let r=by(e),a=r.getCalendar(Rr),o=r.getCalendar(Gy);if(!a||!o)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let s=new Set([Rr]);for(let d of i)s.add(String(d.id));let l=new Map;return{reader:{getCalendar(d){let u=String(d),p=l.get(u);if(p)return p;let f=a;return s.has(u)?f=r.getCalendar(d)??a:n.has(u)&&(f=o),l.set(u,f),f}}}}function zy(t){return{hasChildren(e){return t.hasChildren(e)},getParentStartDateIfHasPredecessors(e){let n=t.getActivity(e);if(!n)return null;let i=t.getParent(n.id);return!i||t.getIncomingLinkIds(i.id).length===0?null:i.startDate},getDescendantIds(e){return U_(t,e).map(n=>String(n))},getAncestorIds(e){let n=[],i=t.getActivity(e);for(;i;){let r=i.parentId;if(r===null)break;let a=t.getActivity(r);if(!a)break;n.push(String(r)),i=a}return n},getChildProgressInfo(e){return t.getChildren(e).map(i=>{let r=t.getActivity(i);return{id:i,progress:Number(r?.progress??0),ponderator:Number(r?.ponderator??0)}})},getChildHhInfo(e){return t.getChildren(e).map(i=>{let r=t.getActivity(i);return{id:i,workHours:Number(r?.workHours??0),progress:Number(r?.progress??0),realWorkHours:Number(r?.realWorkHours??0)}})},getChildUsedCostInfo(e){return t.getChildren(e).map(i=>{let r=t.getActivity(i);return{id:i,usedCost:Number(r?.usedCost??0)}})},getChildCostInfo(e){return t.getChildren(e).map(i=>{let r=t.getActivity(i);return{id:i,cost:Number(r?.cost??0)}})}}}function U_(t,e){let n=[],i=new Xt;for(let r of t.getChildren(e))i.enqueue(r);for(;!i.isEmpty();){let r=i.dequeue();n.push(r);for(let a of t.getChildren(r))i.enqueue(a)}return n}var Ro=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(e){this.reader=e.reader}resolveCalendar(e){let n=Jy(e);return this.reader.getCalendar(n??Rr)}getClosestWorkTime(e){let n=`${ic(e.task)}|${e.dir}|${e.date.getTime()}`;return nc(this._cache.closestWorkTime,n,()=>this.resolveCalendar(e.task).getClosestWorkTime({direction:e.dir,date:e.date,unit:dt.HOUR}))}isWorkTime(e){return this.resolveCalendar(e.task).isWorkTime(e.date,dt.MINUTE)}calculateEndDate(e){let n=`${ic(e.task)}|${e.startDate.getTime()}|${e.durationHours}`;return nc(this._cache.endDate,n,()=>this.resolveCalendar(e.task).calculateEndDate(e.startDate,e.durationHours))}calculateDuration(e){let n=`${ic(e.task)}|${e.startDate.getTime()}|${e.endDate.getTime()}`;return nc(this._cache.duration,n,()=>this.resolveCalendar(e.task).calculateDuration(e.startDate,e.endDate))}clearCache(){this._cache.closestWorkTime.clear(),this._cache.endDate.clear(),this._cache.duration.clear()}};function nc(t,e,n){let i=t.get(e);if(i!==void 0)return i;let r=n();return t.set(e,r),r}var H_="__default__";function Jy(t){if(!t)return null;let e=t.calendarId;return e==null?null:String(e)}function ic(t){return Jy(t)??H_}var ko=class{constructor(e){this.activities=e}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(e){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(e))??[]}hasChildren(e){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(e))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(e,n){let i=this.activities.get(e)?.parentId,r=0,a=this.activities.size;for(;i&&!V(i);){if(i===n)return!0;if(++r>a)return!1;i=this.activities.get(i)?.parentId}return!1}getParent(e){let n=this.activities.get(e)?.parentId;return!n||V(n)?null:this.activities.get(n)??null}getParentId(e){return this.activities.get(e)?.parentId??null}addChild(e,n){if(this._dirty)return;if(V(e)){this._roots.push(n);return}let i=String(e),r=this._childrenByParent.get(i);r?r.push(n):this._childrenByParent.set(i,[n])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let n of this.activities.values()){if(V(n.parentId)){this._roots.push(n.id);continue}let i=String(n.parentId),r=this._childrenByParent.get(i)??[];r.push(n.id),this._childrenByParent.set(i,r)}let e=(n,i)=>{let r=this.activities.get(n),a=this.activities.get(i);return r&&a?oi(r,a):String(n).localeCompare(String(i))};this._roots.sort(e);for(let n of this._childrenByParent.values())n.sort(e)}};var Lo=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(e){return this.checkedSet.has(e)}isVisible(e){return!this.hiddenSet.has(e)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(e){this.activeFilter=e}getActiveOrder(){return this.activeOrder}setActiveOrder(e){this.activeOrder=e}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(e,n){return n===this.checkedSet.has(e)?!1:(n?this.checkedSet.add(e):this.checkedSet.delete(e),!0)}setVisible(e,n){return n===!this.hiddenSet.has(e)?!1:(n?this.hiddenSet.delete(e):this.hiddenSet.add(e),!0)}forget(e){this.checkedSet.delete(e),this.hiddenSet.delete(e)}hydrate(e){this.checkedSet=new Set(e.checkedIds??[]),this.hiddenSet=new Set(e.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(e){this.checkedSet=new Set(e.checked),this.hiddenSet=new Set(e.hidden),this.activeFilter=e.activeFilter,this.activeOrder=e.activeOrder}};function sc(t,e,n,i,r,a){return{valueId:e,id:t,label:n,color:i,level:r,sequence:a,children:new Map,activities:[]}}function Xy(t,e,n,i,r){let{attributeKey:a,startLevel:o,depth:s}=e;for(let l of t){let c=n.assignmentByActivityId.get(String(l.id)),d=c===void 0?[]:fd(n,c,o,s),u=d.length===0?[On]:d,p=i;u.forEach((f,y)=>{let m=p.children.get(f);if(m===void 0){let h=n.valueById.get(f);m=sc(r?ia(p.id,a,f):na(a,f),f,h?.label??(f===On?Qr:f),h?.color??null,i.level+1+y,h?.sequence??Number.MAX_SAFE_INTEGER),p.children.set(f,m)}p=m}),p.activities.push(l)}return i}function Zy(t){let e=t.activities.length;for(let n of t.children.values())e+=Zy(n);return e}function rc(t,e){let n=[...t.children.values()];return n.sort((i,r)=>i.valueId===On?1:r.valueId===On?-1:i.sequence!==r.sequence?i.sequence-r.sequence:i.valueId.localeCompare(r.valueId)),e===Ut.DESCENDING&&n.reverse(),n}var B_=1,j_=Number.POSITIVE_INFINITY;function ac(t){return{kind:ri.ACTIVITY,activityId:String(t.id)}}function W_(t,e,n){let i=[],r=new Map;for(let a of e){if(!t.has(String(a.id)))continue;let o=n(a.id),s=o===null?null:String(o);if(s===null||!t.has(s)){i.push(a);continue}let l=r.get(s);l===void 0?r.set(s,[a]):l.push(a)}return{roots:i,childrenOf:r}}function Qy(t,e){let{roots:n,childrenOf:i}=W_(t,e.activitiesInVisualOrder,e.parentOf),r=e.wbsDepth??j_,a=l=>i.get(String(l.id))??[],o=l=>{let c=[],d=u=>{for(let p of u){let f=a(p);f.length===0?c.push(p):d(f)}};return d(l),c},s=(l,c)=>{if(c>r){let d=o(l),u=e.comparator===null?d:la(d,e.comparator,e.orderMode,()=>!1);for(let p of u)e.rows.push(ac(p));return}for(let d of l){e.rows.push(ac(d));let u=a(d);u.length>0&&s(u,c+1)}};s(n,B_)}function V_(t,e){let n=new Set(t.map(i=>String(i.id)));for(let i of t){let r=e.parentOf(i.id);for(;r!==null;)n.add(String(r)),r=e.parentOf(r)}Qy(n,e)}function K_(t,e){let{rows:n}=e;if(e.group.includeWbs){V_(t.activities,{activitiesInVisualOrder:e.activitiesInVisualOrder,parentOf:e.parentOf,wbsDepth:e.wbsDepth,comparator:e.comparator,orderMode:e.orderMode,rows:n});return}for(let i of la([...t.activities],e.comparator,e.orderMode,e.hasChildren))n.push({kind:ri.ACTIVITY,activityId:String(i.id)})}function oc(t,e,n,i){let{group:r,rows:a}=i;if(a.push({kind:ri.GROUP,id:t.id,label:t.label,level:t.level,color:t.color,activityCount:Zy(t)}),r.collapsedIds.has(t.id))return;for(let s of rc(t,e))oc(s,e,n,i);if(t.activities.length===0)return;let o=r.secondary;if(n&&o!=null&&i.secondaryCatalog!=null){let s=Xy(t.activities,o,i.secondaryCatalog,sc(t.id,"","",null,t.level,0),!0);for(let l of rc(s,o.direction))oc(l,o.direction,!1,i);return}K_(t,i)}function th(t){let e=t.activitiesInVisualOrder.filter(s=>t.isVisible(s.id));if(t.group===null||t.catalog===null){if(t.wbsDepth===null)return e.map(ac);let s=[];return Qy(new Set(e.map(l=>String(l.id))),{activitiesInVisualOrder:e,parentOf:t.parentOf,wbsDepth:t.wbsDepth,comparator:t.comparator,orderMode:t.orderMode,rows:s}),s}let{group:n,catalog:i}=t,r=Xy(e,n,i,sc("","","",null,-1,0),!1),a=[],o={group:n,activitiesInVisualOrder:t.activitiesInVisualOrder,parentOf:t.parentOf,hasChildren:t.hasChildren,comparator:t.comparator,orderMode:t.orderMode,wbsDepth:t.wbsDepth,secondaryCatalog:t.secondaryCatalog,rows:a};for(let s of rc(r,n.direction))oc(s,n.direction,!0,o);return a}var Oo=class t{catalogs=new Map;group=null;wbsDepth=null;getCatalog(e){return this.catalogs.get(e)??null}getCatalogMap(){return this.catalogs}setCatalogs(e){let n=new Map;for(let i of e)n.set(i.key,ud(i));this.catalogs=n}getGroup(){return this.group}setGroup(e){this.group=e}getWbsDepth(){return this.wbsDepth}setWbsDepth(e){this.wbsDepth=e}clone(){let e=new t;return e.catalogs=new Map(this.catalogs),e.group=this.group===null?null:v(this.group),e.wbsDepth=this.wbsDepth,e}};var Y_={settings:null,projectState:null,latestRunLog:null},Ui=class t{_activities=new Map;_missingSchedulingStateCount=0;_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,visualRows:null,orderComparator:null};_writeCapture=new io;_viewState=new Lo;_viewAttributes=new Oo;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_missingSchedulingStateCountBefore=null;_dataDate=Y_;_dataDateBefore=null;_calendar;_flags;_calendarSnapshot;constructor(e,n=()=>null){this._buildOrderComparator=n,this._calendarSnapshot=v(e.calendars);for(let i of e.activities)this._activities.set(i.id,i);for(let i of this._activities.values())An(i)&&(this._missingSchedulingStateCount+=1);for(let i of e.links){let r={...i,freeSlackHours:i.freeSlackHours??null,isCritical:i.isCritical===!0};this._links.set(String(i.id),r),this._indexLink(r)}this._calendar=new Ro(Po(this._calendarSnapshot)),this._flags=$_(e),this._hierarchy=new ko(this._activities),this._hierarchy.rebuild()}fork(){let e=new t({activities:this.getAllActivities().map(xe),links:this.getAllLinks().map(n=>({...n})),calendars:v(this._calendarSnapshot)},this._buildOrderComparator);return e._viewState.restore(v(this._viewState.snapshot())),e._lastStartDate=new Map(Array.from(this._lastStartDate,([n,i])=>[n,new Date(i)])),e._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([n,i])=>[n,v(i)])),e._progressFallback=new Map(this._progressFallback),e._flags=v(this._flags),e._filterProjection=v(this._filterProjection),e._viewAttributes=this._viewAttributes.clone(),e._dataDate=v(this._dataDate),e}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}hasCompleteSchedulingState(){return this._missingSchedulingStateCount===0}dataDateSettings(){return this._dataDate.settings}dataDateProjectState(){return this._dataDate.projectState}dataDateLatestRunLog(){return this._dataDate.latestRunLog}setDataDateSettings(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,settings:v(e)}}setDataDateProjectState(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,projectState:v(e)}}setDataDateLatestRunLog(e){this._captureDataDateOnce(),this._dataDate={...this._dataDate,latestRunLog:v(e)}}_captureDataDateOnce(){this._writeCapture.peek()!==null&&this._dataDateBefore===null&&(this._dataDateBefore=this._dataDate)}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=_d(this).map(e=>String(e.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null,this.invalidateVisualRows()}forEachActivity(e){for(let[n,i]of this._activities)e(i,n)}getParentId(e){return this._hierarchy.getParentId(e)}getActivity(e){return this._activities.get(String(e))??null}getLastStartDate(e){return this._lastStartDate.get(String(e))??null}setLastStartDate(e,n){this._captureLastStartDateOnce(),this._lastStartDate.set(String(e),n)}getPromotionSnapshot(e){return this._promotionSnapshot.get(String(e))??null}setPromotionSnapshot(e,n){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(e),n)}getProgressFallback(e){return this._progressFallback.get(String(e))??null}setProgressFallback(e,n){let i=String(e),r=this._progressFallback.get(i)??null;Object.is(r,n)||(this._writeCapture.noteProgressFallback(i,r),n===null?this._progressFallback.delete(i):this._progressFallback.set(i,n))}_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(e){return this._links.get(String(e))??null}activityExists(e){return this._activities.has(String(e))}isChecked(e){return this._viewState.isChecked(String(e))}isVisible(e){return this._viewState.isVisible(String(e))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(e,n){return this._captureViewStateOnce(),this._viewState.setChecked(String(e),n)}setVisible(e,n){this._captureViewStateOnce();let i=this._viewState.setVisible(String(e),n);return i&&this.invalidateVisualRows(),i}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(e){this._captureViewStateOnce(),this._viewState.setActiveFilter(e),this._filterProjection=null,this.invalidateVisualRows()}getFilterProjection(){return this._filterProjection}setFilterProjection(e){this._filterProjection=e}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(e){this._captureViewStateOnce(),this._viewState.setActiveOrder(e),this.invalidateDerivedOrder()}getOrderComparator(){let e=this._viewState.getActiveOrder();return e===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(e,this._viewAttributes.getCatalogMap()),this._cache.orderComparator)}getOrderMode(){return this._viewState.getActiveOrder()?.mode??be.STANDARD}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null,this.invalidateVisualRows()}getViewAttributeCatalogMap(){return this._viewAttributes.getCatalogMap()}setViewAttributeCatalogs(e){this._viewAttributes.setCatalogs(e),this.invalidateDerivedOrder()}getGroup(){return this._viewAttributes.getGroup()}setGroup(e){this._viewAttributes.setGroup(e),this.invalidateVisualRows()}getWbsDepth(){return this._viewAttributes.getWbsDepth()}setWbsDepth(e){this._viewAttributes.setWbsDepth(e),this.invalidateVisualRows()}invalidateVisualRows(){this._cache.visualRows=null}getVisualRows(){if(this._cache.visualRows)return this._cache.visualRows;let e=this._viewAttributes.getGroup(),n=e===null?null:this._viewAttributes.getCatalog(e.attributeKey),i=e?.secondary==null?null:this._viewAttributes.getCatalog(e.secondary.attributeKey),r=[];for(let a of this.getVisualOrderIds()){let o=this.getActivity(a);o!==null&&r.push(o)}return this._cache.visualRows=th({activitiesInVisualOrder:r,isVisible:a=>this.isVisible(a),parentOf:a=>this.getParentId(a),hasChildren:a=>this.hasChildren(a),group:e,catalog:n,secondaryCatalog:i,comparator:this.getOrderComparator(),orderMode:this.getOrderMode(),wbsDepth:this._viewAttributes.getWbsDepth()}),this._cache.visualRows}hydrateViewState(e){this._viewState.hydrate(e),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(e){return this._outgoing.get(String(e))??eh}getIncomingLinkIds(e){return this._incoming.get(String(e))??eh}getChildren(e){return this._hierarchy.getChildren(e)}hasChildren(e){return this._hierarchy.hasChildren(e)}isChildOf(e,n){return this._hierarchy.isChildOf(e,n)}getParent(e){return this._hierarchy.getParent(e)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(e){return this._calendar.getClosestWorkTime(e)}isWorkTime(e){return this._calendar.isWorkTime(e)}calculateEndDate(e){return this._calendar.calculateEndDate(e)}calculateDuration(e){return this._calendar.calculateDuration(e)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(e){e()}updateActivity(e){}getLiveActivity(e){return this.getActivity(e)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null,this._missingSchedulingStateCountBefore=this._missingSchedulingStateCount,this._dataDateBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null,this._missingSchedulingStateCountBefore=null,this._dataDateBefore=null}setActivityField(e,n,i){let r=this.getActivity(e);if(!r)return;let a=An(r);this._writeCapture.note(String(e),r),r[n]=i,this._updateSchedulingStateCount(a,r),cc(r,n),n===U.PARENT&&this._hierarchy.markDirty(),lc(n)&&(this._cache.visualOrderIds=null)}setActivityFieldDynamic(e,n,i){let r=this.getActivity(e);if(!r)return;if(!Object.hasOwn(r,n))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${n}"`);let a=An(r);this._writeCapture.note(String(e),r),Reflect.set(r,n,Oy(n,i)),this._updateSchedulingStateCount(a,r),cc(r,n),n===U.PARENT&&this._hierarchy.markDirty(),lc(n)&&(this._cache.visualOrderIds=null)}setActivityFields(e,n){let i=this.getActivity(e);if(!i)return;let r=An(i);this._writeCapture.note(String(e),i);let a=!1;for(let o of Object.keys(n))Reflect.set(i,o,Reflect.get(n,o)),cc(i,o),o===U.PARENT&&(a=!0),lc(o)&&(this._cache.visualOrderIds=null);this._updateSchedulingStateCount(r,i),a&&this._hierarchy.markDirty()}addLink(e){this._writeCapture.noteLinkAdd(String(e.id));let n=this._links.get(String(e.id));n&&this._deindexLink(n);let i={...e,freeSlackHours:e.freeSlackHours??null,isCritical:e.isCritical===!0};this._links.set(String(e.id),i),this._indexLink(i)}_indexLink(e){nh(this._outgoing,String(e.source),e.id),nh(this._incoming,String(e.target),e.id)}_deindexLink(e){let n=this._outgoing.get(String(e.source));n&&this._outgoing.set(String(e.source),dc(n,e.id));let i=this._incoming.get(String(e.target));i&&this._incoming.set(String(e.target),dc(i,e.id))}_removeLinkRef(e,n,i){let r=e.get(n);r&&e.set(n,dc(r,i))}_insertLinkRefInOrder(e,n,i){let r=new Set;for(let s of this._links.keys()){if(String(s)===String(i))break;r.add(String(s))}let a=[...e.get(n)??[]],o=a.findIndex(s=>!r.has(String(s)));a.splice(o<0?a.length:o,0,i),e.set(n,a)}setLinkField(e,n,i){let r=this.getLink(e);r&&(this._writeCapture.noteLinkField(String(e),r),r[n]=i)}setLinkEndpoints(e,n,i){let r=this.getLink(e);if(!r)return;let a=String(r.source)!==String(n),o=String(r.target)!==String(i);!a&&!o||(this._writeCapture.noteLinkField(String(e),r),a&&(this._removeLinkRef(this._outgoing,String(r.source),r.id),r.source=n,this._insertLinkRefInOrder(this._outgoing,String(n),r.id)),o&&(this._removeLinkRef(this._incoming,String(r.target),r.id),r.target=i,this._insertLinkRefInOrder(this._incoming,String(i),r.id)))}setLinkFieldDynamic(e,n,i){let r=this.getLink(e);if(r){if(n===Gt.SOURCE){this.setLinkEndpoints(e,String(i),r.target);return}if(n===Gt.TARGET){this.setLinkEndpoints(e,r.source,String(i));return}G_(n)&&(this._writeCapture.noteLinkField(String(e),r),Reflect.set(r,n,i))}}setLinkProplannerId(e,n){let i=this.getLink(e);i&&(this._writeCapture.noteLinkField(String(e),i),i.proplannerId=n)}removeLink(e){let n=this.getLink(e);n&&(this._writeCapture.noteLinkRemove(String(e),n),this._links.delete(String(e)),this._deindexLink(n))}addActivity(e){this._writeCapture.noteInsert(String(e.id));let n=this._activities.get(e.id);n&&An(n)&&(this._missingSchedulingStateCount-=1),this._activities.set(e.id,e),An(e)&&(this._missingSchedulingStateCount+=1),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.addChild(e.parentId,e.id)}removeActivity(e){let n=this.getActivity(e);n&&this._writeCapture.noteRemove(String(e),n),n&&An(n)&&(this._missingSchedulingStateCount-=1);let i=String(e);this.setProgressFallback(i,null),(this._viewState.isChecked(i)||!this._viewState.isVisible(i))&&this._captureViewStateOnce(),this._viewState.forget(i),this._activities.delete(e),this._lastStartDate.has(String(e))&&(this._captureLastStartDateOnce(),this._lastStartDate.delete(String(e))),this._outgoing.delete(String(e)),this._incoming.delete(String(e)),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}noteCorrelativeBefore(e,n){this._writeCapture.noteCorrelativeBefore(e,n)}noteScheduledBefore(e,n){this._writeCapture.noteScheduledBefore(e,n)}restoreFromCapture(){let e=this._writeCapture.peek();if(!e)return;let{ops:n,before:i,correlativeBefore:r,scheduledBefore:a,progressFallbackBefore:o}=e;this._undoLinkAdds(n),this._undoInserts(n),this._reInsertRemovedActivities(n),this._reAddRemovedLinks(n),this._restoreLinkFields(n),this._restoreActivityFields(a),this._restoreActivityFields(i),this._restoreCorrelatives(r),this._restoreProgressFallbacks(o),this._missingSchedulingStateCountBefore!==null&&(this._missingSchedulingStateCount=this._missingSchedulingStateCountBefore),this._dataDateBefore!==null&&(this._dataDate=this._dataDateBefore),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(e){for(let[n,i]of e)i===null?this._progressFallback.delete(n):this._progressFallback.set(n,i)}_restoreCorrelatives(e){for(let[n,i]of e){let r=this._activities.get(n);r&&(r.correlativeId=i)}}_undoLinkAdds(e){for(let n of e)n.kind===Rt.LINK_ADD&&this._detachLink(n.linkId)}_undoInserts(e){for(let n of e)n.kind===Rt.INSERT&&this._activities.delete(n.activityId)}_reInsertRemovedActivities(e){for(let n of e)n.kind===Rt.REMOVE&&this._activities.set(n.activityId,n.before)}_reAddRemovedLinks(e){for(let n of e)n.kind===Rt.LINK_REMOVE&&this._attachLink(n.before)}_restoreLinkFields(e){for(let n of e){if(n.kind!==Rt.LINK_FIELD)continue;let i=this._links.get(n.linkId);if(i){this.setLinkEndpoints(n.linkId,n.before.source,n.before.target);for(let r of Object.keys(i))Object.hasOwn(n.before,r)||Reflect.deleteProperty(i,r);Object.assign(i,n.before)}}}_restoreActivityFields(e){for(let[n,i]of e){let r=this._activities.get(n);r&&this._restoreScalarFields(r,i)}}_restoreScalarFields(e,n){for(let i of Object.keys(e))Object.hasOwn(n,i)||Reflect.deleteProperty(e,i);for(let i of Object.keys(n))Reflect.set(e,i,Reflect.get(n,i))}_updateSchedulingStateCount(e,n){let i=An(n);e!==i&&(this._missingSchedulingStateCount+=i?1:-1)}_attachLink(e){this._links.set(String(e.id),{...e}),this._indexLink(e)}_detachLink(e){let n=this.getLink(e);n&&(this._links.delete(String(e)),this._deindexLink(n))}},eh=[];function G_(t){return t===Gt.LAG||t===Gt.TYPE||t===Gt.FREE_SLACK_HOURS||t===Gt.IS_CRITICAL}function lc(t){return t===U.PARENT||t===U.CORRELATIVE_ID}function An(t){return t.type!==k.PROJECT&&t.p6===void 0}function cc(t,e){e!==U.START_DATE&&e!==U.END_DATE&&e!==U.TYPE||(t.calendarDuration=Te(t))}function dc(t,e){return t.filter(n=>String(n)!==String(e))}function nh(t,e,n){let i=t.get(e);i?i.push(n):t.set(e,[n])}function $_(t){let e=t.runtimeFlags??{};return{isPasting:!!e.isPasting,isBulkOperation:!!e.isBulkOperation,dragWithMultiple:!!e.dragWithMultiple,draggingSingleMilestone:!!e.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!e.maxPerformance,allCheckedTaskIds:[]}}function kr(t,e){let n=t.getActivity(e);return n?v(n):null}function ih(t){return t.getAllActivities().map(v)}function rh(t){return t.getAllIds().map(String)}function ah(t,e){t.forEachActivity((n,i)=>e(i))}function oh(t,e){let n=e==="0"?uc(t,"0"):t.getChildren(e),i=[];for(let r of n){let a=t.getActivity(r);a&&i.push(v(a))}return i.sort((r,a)=>(r.correlativeId??0)-(a.correlativeId??0)),i}function uc(t,e){return ee(e,t)}function sh(t){return t.checkedIds().map(String)}function lh(t,e){if(e==="0"){let n=!1;return t.forEachActivity(i=>{n||=V(i.parentId)}),n}return t.getChildren(e).length>0}function pc(t,e){let n=t.getLink(e);return n?zt(n):null}function ch(t){return t.getAllLinks().map(e=>zt(e))}function bo(t){let[e,n]=t.split(":");return Number(e)*60+Number(n??0)}function q_(t){return t.reduce((e,n)=>bo(n)<bo(e)?n:e)}function z_(t){return t.reduce((e,n)=>bo(n)>bo(e)?n:e)}function J_(t){return t.worktime.days.flatMap(e=>Array.isArray(e)?e:e===!0?t.worktime.hours:[])}function dh(t){let e=[...t].find(a=>a.is_default);if(!e)return null;let n=J_(e);if(n.length===0)return null;let i=n.map(a=>a.split("-")[0]),r=n.map(a=>a.split("-")[1]);return{startHour:q_(i),endHour:z_(r)}}function No(t,e){return{calendars:t.calendarReader,hierarchy:zy(t),activityReader:qy(t),dateFormat:e.dateFormat??"YYYY-MM-DD",customHours:e.customHours??{},hoursPerDay:e.hoursPerDay}}function uh(t){return Yn(t)}var X_=new Set(["freeSlackHours","isCritical"]);function Z_(t,e){let n=Object.fromEntries(Object.entries(t.fields??{}).filter(([i])=>!e.has(i)));return t.kind===x.UPDATED&&Object.keys(n).length===0?null:{...t,...t.fields===void 0?{}:{fields:n},after:null}}function Lr(t){let e=t.activities.map(r=>({...r,after:null})),n=t.links.map(r=>Z_(r,X_)).filter(r=>r!==null),i=t.source.kind===qe?{...t.source,items:[],links:[]}:t.source;return v({...t,source:i,activities:e,links:n})}function Bi(t,e,n,i,r,a,o){return{changeSet:t,beforeSnap:e,beforeLinks:ph(n),afterSnap:i,afterLinks:ph(r),progressFallbackBefore:a,progressFallbackAfter:o}}function ph(t){if(t)return new Map(Array.from(t,([e,n])=>[e,{...n,freeSlackHours:null,isCritical:!1}]))}function hh(t,e){let n=new Map,i=new Map;for(let r of e.activities){if(r.kind!==x.CREATED)continue;let a=t.getActivity(String(r.id));a&&n.set(String(r.id),rt(a))}for(let r of e.links){if(r.kind===x.DELETED)continue;let a=t.getLink(String(r.id));a&&i.set(String(r.id),{...a})}return{afterSnap:n,afterLinks:i}}function mh(t){return t.kind!==I.INLINE_EDIT||!Cr.has(t.column)?null:`inline-edit:${String(t.activityId)}:${t.column}`}function fh(t){return t.changeSet.activities.length===1&&t.changeSet.activities[0]?.kind===x.UPDATED&&t.changeSet.links.length===0&&!t.beforeSnap?.size&&!t.afterSnap?.size}function gh(t,e){if(!fh(t)||!fh(e))return!1;let n=t.changeSet.activities[0],i=e.changeSet.activities[0];return!!n&&!!i&&String(n.id)===String(i.id)}function Ah(t,e){let n=t.changeSet.activities[0],i=e.changeSet.activities[0];if(!n||!i)return e;let r=n.fields??{},a=i.fields??{},o={};for(let l of new Set([...Object.keys(r),...Object.keys(a)])){let c=r[l],d=a[l];o[l]={before:c?c.before:d?.before,after:d?d.after:c?.after}}let s={...e.changeSet,activities:[{...i,fields:o}]};return Bi(s)}var Hi={RECORD:"record",SKIP:"skip",CHECKPOINT_ON_SUCCESS:"checkpoint-on-success"},At={BEFORE:"before",AFTER:"after"};function Ih(t){return t.kind===I.PERSISTENCE_ACKNOWLEDGE?Hi.CHECKPOINT_ON_SUCCESS:t.kind===I.SIR_SYNC||t.kind===I.CALENDAR_RECONCILE||t.kind===I.ACTIVITY_LOOKAHEAD_SYNC||t.kind===I.BASELINE_APPLY||t.kind===I.PONDERATOR_CRITERION_SET||t.kind===I.STATUS_CRITERIA_SET||t.kind===I.ACTIVITY_CLIPBOARD_CLEAR||t.kind===I.ACTIVITY_COPY||t.kind===I.SELECTION_TOGGLE||t.kind===I.SELECTION_REPLACE||t.kind===I.VISIBILITY_SET||t.kind===I.FILTER_SET||t.kind===I.SORT_SET||t.kind===I.VIEW_ATTRIBUTES_SET||t.kind===I.GROUP_SET||t.kind===I.WBS_DEPTH_SET?Hi.SKIP:Hi.RECORD}function fc(t){for(let e of t.changeSet.activities)if(e.kind===x.CREATED||e.kind===x.DELETED||e.kind===x.UPDATED&&e.fields&&E.CUSTOM_ID in e.fields)return!0;return!1}function yc(t,e,n,i=()=>({})){let r=[],a=[];for(let s of e.changeSet.activities){let l=String(s.id);if(s.kind===x.UPDATED){let c=t.getActivity(l);r.push({id:l,kind:x.UPDATED,fields:yh(s.fields,n),after:c?rt(c):null})}else if(s.kind===x.DELETED)if(n===At.BEFORE){let c=t.getActivity(l);r.push({id:l,kind:x.CREATED,after:c?rt(c):null})}else r.push({id:l,kind:x.DELETED,after:null});else if(n===At.BEFORE)r.push({id:l,kind:x.DELETED,after:null});else{let c=t.getActivity(l);r.push({id:l,kind:x.CREATED,after:c?rt(c):null})}}for(let s of e.changeSet.links){let l=String(s.id);if(s.kind===x.UPDATED){let c=t.getLink(l);a.push({id:l,kind:x.UPDATED,fields:yh(s.fields,n),after:c?zt(c):null})}else if(s.kind===x.DELETED)if(n===At.BEFORE){let c=t.getLink(l);a.push({id:l,kind:x.CREATED,after:c?zt(c):null})}else a.push({id:l,kind:x.DELETED,after:null});else if(n===At.BEFORE)a.push({id:l,kind:x.DELETED,after:null});else{let c=t.getLink(l);a.push({id:l,kind:x.CREATED,after:c?zt(c):null})}}let o=(e.changeSet.viewState??[]).map(s=>n===At.BEFORE?Q_(s):s);return{source:{kind:n===At.BEFORE?Ht.UNDO:Ht.REDO},activities:r,links:a,calendars:[],trackingEvents:[],effects:[],viewState:o,...i(n)}}function yh(t,e){if(t!=null)return Object.fromEntries(Object.entries(t).map(([n,i])=>[n,e===At.BEFORE?{before:v(i.after),after:v(i.before)}:{before:v(i.before),after:v(i.after)}]))}function Q_(t){return{activityId:t.activityId,...t.checked?{checked:{before:t.checked.after,after:t.checked.before}}:{},...t.visible?{visible:{before:t.visible.after,after:t.visible.before}}:{}}}function Sh(t,e=!1){return t.activities.length>0||t.links.length>0||e||(t.viewState?.length??0)>0||(t.effects?.length??0)>0}function hc(t,e,n){vh(t,e,At.BEFORE,n)}function mc(t,e,n){vh(t,e,At.AFTER,n)}function vh(t,e,n,i){let r=e.changeSet;for(let o of r.activities)if(o.kind===x.UPDATED){if(!o.fields)continue;for(let[s,l]of Object.entries(o.fields))ae(t,o.id,s,n===At.BEFORE?l.before:l.after)}else if(o.kind===x.DELETED)if(n===At.BEFORE){let s=e.beforeSnap?.get(String(o.id));if(!s)throw new Error(`undo: missing beforeSnap for resurrecting activity ${o.id}`);t.addActivity(rt(s))}else t.removeActivity(String(o.id));else if(n===At.BEFORE)t.removeActivity(String(o.id));else{let s=e.afterSnap?.get(String(o.id));if(!s)throw new Error(`redo: missing afterSnap for re-creating activity ${o.id}`);t.addActivity(rt(s))}for(let o of r.links)if(o.kind===x.UPDATED){if(!o.fields)continue;let s=t.getLink(String(o.id)),l=o.fields[Gt.SOURCE],c=o.fields[Gt.TARGET];s&&(l||c)&&t.setLinkEndpoints(String(o.id),String(l?n===At.BEFORE?l.before:l.after:s.source),String(c?n===At.BEFORE?c.before:c.after:s.target));for(let[d,u]of Object.entries(o.fields))d===Gt.SOURCE||d===Gt.TARGET||fp(t,String(o.id),d,n===At.BEFORE?u.before:u.after)}else if(o.kind===x.DELETED)if(n===At.BEFORE){let s=e.beforeLinks?.get(String(o.id));if(!s)throw new Error(`undo: missing beforeLinks for re-adding link ${o.id}`);t.addLink(s)}else t.removeLink(String(o.id));else if(n===At.BEFORE)t.removeLink(String(o.id));else{let s=e.afterLinks?.get(String(o.id));if(!s)throw new Error(`redo: missing afterLinks for re-creating link ${o.id}`);t.addLink(s)}for(let o of r.viewState??[])o.checked&&t.setChecked(o.activityId,n===At.BEFORE?o.checked.before:o.checked.after),o.visible&&t.setVisible(o.activityId,n===At.BEFORE?o.visible.before:o.visible.after);let a=n===At.BEFORE?e.progressFallbackBefore:e.progressFallbackAfter;for(let[o,s]of a??[])t.setProgressFallback(o,s);i?.(r,n)}var tE=100,eE=600,Fo=class t{constructor(e=tE){this.maxDepth=e}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let e=new t(this.maxDepth);return e.undoStack.push(...v(this.undoStack)),e.redoStack.push(...v(this.redoStack)),e.sequence=this.sequence,e._lastKey=this._lastKey,e._lastTime=this._lastTime,e}record(e,n=null,i=0){let r=this.undoStack[this.undoStack.length-1];n!=null&&n===this._lastKey&&i-this._lastTime<=eE&&r!==void 0&&gh(r.entry,e)?(r.entry=Ah(r.entry,e),r.touchedAt=this.touch()):(this.undoStack.push({entry:e,touchedAt:this.touch()}),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=n,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(e){this.redoStack.push({entry:e,touchedAt:this.touch()})}pushUndo(e){this.undoStack.push({entry:e,touchedAt:this.touch()})}restoreTakenUndo(e){this.undoStack.push({entry:e,touchedAt:this.sequence})}restoreTakenRedo(e){this.redoStack.push({entry:e,touchedAt:this.sequence})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(e){this.removeEntriesThrough(this.undoStack,e),this.removeEntriesThrough(this.redoStack,e),this.resetCoalesce()}applyPersistedIdentities(e,n){let i=new Map(e.map(({id:a,proplannerId:o})=>[String(a),o])),r=new Map(n.map(({id:a,proplannerId:o})=>[String(a),o]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,i,r)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(e,n){let i=e.filter(({touchedAt:r})=>r>n);e.splice(0,e.length,...i)}withPersistedIdentities(e,n,i){let r=o=>o===void 0?void 0:new Map(Array.from(o,([s,l])=>[s,n.has(s)?{...l,proplannerId:n.get(s)}:l])),a=o=>o===void 0?void 0:new Map(Array.from(o,([s,l])=>[s,i.has(s)?{...l,proplannerId:i.get(s)}:l]));return{...e,beforeSnap:r(e.beforeSnap),afterSnap:r(e.afterSnap),beforeLinks:a(e.beforeLinks),afterLinks:a(e.afterLinks)}}};var nE=["parentId","correlativeId"];function Dh(t,e){let n=new Set,i=r=>{let a=e(r);n.add(a===null?"0":String(a))};for(let r of t.activities){let a=String(r.id);if(r.kind===x.CREATED){i(a);continue}if(r.kind===x.DELETED){let l=r.fields;l&&"parentId"in l&&n.add(Ch(l.parentId?.before));continue}let o=r.fields;!o||!nE.some(l=>l in o)||(i(a),"parentId"in o&&n.add(Ch(o.parentId?.before)))}return n}function Ch(t){return t==null?"0":String(t)}function iE(t){return{...t,id:String(t.id),source:String(t.source),target:String(t.target),type:t.type,lag:Number(t.lag)}}function rE(t){return{days:t.days,hours:t.hours,...t.dates?{dates:t.dates}:{},...t.customWeeks?{customWeeks:t.customWeeks}:{}}}function Th(t){return{id:String(t.id),worktime:rE(t.worktime)}}function gc(t,e=[]){return[...t.map(Th),...e.map(Th)]}function wo(t,e,n,i=[]){return{activities:[...t],links:e.map(iE),calendars:gc(n,i)}}var B={TRACKED:"tracked",IGNORED:"ignored"};var _h={id:B.IGNORED,proplannerId:B.IGNORED,parentId:B.TRACKED,name:B.TRACKED,description:B.TRACKED,type:B.TRACKED,startDate:B.TRACKED,endDate:B.TRACKED,durationHours:B.TRACKED,constraintType:B.TRACKED,constraintDate:B.TRACKED,autoScheduling:B.TRACKED,calendarId:B.TRACKED,assignedDefaultCalendar:B.IGNORED,dateOrigin:B.TRACKED,progress:B.TRACKED,cost:B.TRACKED,usedCost:B.TRACKED,realCost:B.TRACKED,workHours:B.TRACKED,realWorkHours:B.TRACKED,ponderator:B.TRACKED,hasCustomPonderator:B.TRACKED,correlativeId:B.TRACKED,uniqueCorrelativeId:B.TRACKED,customId:B.TRACKED,subcontractId:B.TRACKED,isLookahead:B.TRACKED,hasLookaheadTasks:B.IGNORED,newActivityIds:B.TRACKED,hasNewActivities:B.TRACKED,isNewActivity:B.IGNORED,pendingRequestIds:B.IGNORED,responsableIds:B.TRACKED,tagIds:B.TRACKED,baselinePoints:B.IGNORED,baselineSnapshot:B.IGNORED,recursiveDurationHours:B.IGNORED,isCritical:B.IGNORED,freeSlackHours:B.IGNORED,calendarDuration:B.IGNORED,baselineVarianceDays:B.IGNORED,expectedProgress:B.IGNORED,expectedProgressBaseline:B.IGNORED,status:B.IGNORED,criticalPath:B.IGNORED,p6:B.IGNORED},Eh=Object.keys(_h).filter(t=>_h[t]===B.TRACKED),Ph=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Rh=new Set(["newActivityIds","responsableIds","tagIds"]);function kh(t){let e=Eh.map(n=>[n,aE(n,t[n])]);return Object.fromEntries(e)}function aE(t,e){return Ph.has(t)?e instanceof Date?new Date(e):null:Rh.has(t)?Array.isArray(e)?[...e]:[]:e}function Or(t,e){return Ac(t,e).length>0}function Ac(t,e){return Eh.filter(n=>!oE(n,t[n],e[n]))}function oE(t,e,n){return Ph.has(t)?sE(e,n):Rh.has(t)?lE(e,n):(e??null)===(n??null)}function sE(t,e){let n=t instanceof Date?t.getTime():null,i=e instanceof Date?e.getTime():null;return n===i}function lE(t,e){let n=new Set(Array.isArray(t)?t.map(String):[]),i=new Set(Array.isArray(e)?e.map(String):[]);if(n.size!==i.size)return!1;for(let r of n)if(!i.has(r))return!1;return!0}var Lh={id:B.IGNORED,source:B.TRACKED,target:B.TRACKED,type:B.TRACKED,lag:B.TRACKED,freeSlackHours:B.IGNORED,isCritical:B.IGNORED,ganttId:B.IGNORED,sectorId:B.IGNORED,proplannerId:B.IGNORED},cE=Object.keys(Lh).filter(t=>Lh[t]===B.TRACKED);function xo(t,e){return cE.some(n=>t[n]!==e[n])}function Oh(t,e){let n=new Map(t.map(i=>[String(i.id),i]));return e.filter(i=>{let r=n.get(String(i.id));return r?xo(r,i):!1})}function ji(t){if(t===void 0)return["undefined"];if(t===null)return["null"];if(typeof t=="string")return["string",t];if(typeof t=="boolean")return["boolean",t];if(typeof t=="number")return["number",Object.is(t,-0)?"-0":String(t)];if(typeof t=="bigint")return["bigint",String(t)];if(t instanceof Date)return["date",String(t.getTime())];if(Array.isArray(t))return["array",t.map(ji)];if(t instanceof Map)return["map",Array.from(t,([e,n])=>[ji(e),ji(n)]).sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n)))];if(t instanceof Set)return["set",Array.from(t,ji).sort((e,n)=>JSON.stringify(e).localeCompare(JSON.stringify(n)))];if(typeof t=="object")return["object",Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>[e,ji(n)])];throw new TypeError(`Unsupported canonical value: ${typeof t}`)}function Tt(t){return JSON.stringify(ji(t))}var Mo=t=>(t>>>0).toString(16).padStart(8,"0");function Ic(t){let e=1779033703,n=3144134277,i=1013904242,r=2773480762;for(let a=0;a<t.length;a+=1){let o=t.charCodeAt(a);e=n^Math.imul(e^o,597399067),n=i^Math.imul(n^o,2869860233),i=r^Math.imul(i^o,951274213),r=e^Math.imul(r^o,2716044179)}return e=Math.imul(i^e>>>18,597399067),n=Math.imul(r^n>>>22,2869860233),i=Math.imul(e^i>>>17,951274213),r=Math.imul(n^r>>>19,2716044179),`${Mo(e^n^i^r)}${Mo(n^e)}${Mo(i^e)}${Mo(r^e)}`}function bh(t,e){return{p6Settings:v(t),p6ProjectState:v(e)}}function In(t,e){return Tt(t)!==Tt(e)}function Nh(t,e){t.clear();for(let n of e)n.p6!==void 0&&t.set(String(n.id),v(n.p6))}function Fh(t,e){let n=e?.p6;return t===void 0&&n===void 0?!1:In(t,n)}function wh(t,e){let n=new Map;for(let i of t){let r=e(i)?.p6;r!==void 0&&n.set(i,v(r))}return n}function Ae(t){if(t==null||t===0)return!1;if(!(typeof t=="number"&&Number.isSafeInteger(t)&&t>0))throw new Error(`invalid proplannerId ${String(t)}`);return!0}function xh(t,e){for(let n of t)Ae(n.proplannerId);for(let n of e)Ae(n.proplannerId)}var Uo=class t{trackingEnabled;initialized=!1;p6TrackingEnabled=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;dirtyP6ActivityIds=new Set;p6SettingsDirty=!1;p6ProjectStateDirty=!1;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;p6SettingsAtLastSave=null;currentP6Settings=null;p6ProjectStateAtLastSave=null;currentP6ProjectState=null;p6LatestRunLogAtLastSave=null;currentP6LatestRunLog=null;p6LatestRunLogDirty=!1;p6ActivitiesAtLastSave=new Map;constructor(e=!0){this.trackingEnabled=e}fork(){let e=new t(!1);return e.initialized=this.initialized,e}init(e,n,i=null,r=null,a=null){if(this.trackingEnabled){xh(e,n),this.snapshotActivities(e),this.snapshotLinks(n),this.p6SettingsAtLastSave=v(i),this.currentP6Settings=v(i),this.p6SettingsDirty=!1,this.p6ProjectStateAtLastSave=v(r),this.currentP6ProjectState=v(r),this.p6ProjectStateDirty=!1,this.p6LatestRunLogAtLastSave=v(a),this.currentP6LatestRunLog=v(a),this.p6LatestRunLogDirty=!1,this.p6TrackingEnabled=i!==null,this.p6TrackingEnabled&&this.snapshotP6Activities(e);for(let o of e)if(o.assignedDefaultCalendar){let s=String(o.id);this.initialCalendarRepairIds.add(s),this.dirtyActivityIds.add(s)}this.initialized=!0}}acknowledge(e,n,i=[],r=[],a,o,s=this.currentP6Settings,l=this.currentP6ProjectState,c=this.currentP6LatestRunLog){if(!this.trackingEnabled)return;let d=new Map(i.map(({id:h,proplannerId:A})=>[String(h),A])),u=new Map(r.map(({id:h,proplannerId:A})=>[String(h),A])),p=e.map(h=>({...h,proplannerId:d.get(String(h.id))??h.proplannerId})),f=n.map(h=>{let A=u.get(String(h.id));return A===void 0?{...h}:{...h,proplannerId:A}});if(xh(p,f),this.snapshotActivities(p),this.snapshotLinks(f),this.p6SettingsAtLastSave=v(s),this.p6SettingsDirty=In(this.currentP6Settings,this.p6SettingsAtLastSave),this.p6ProjectStateAtLastSave=v(l),this.p6ProjectStateDirty=In(this.currentP6ProjectState,this.p6ProjectStateAtLastSave),this.p6LatestRunLogAtLastSave=v(c),this.p6LatestRunLogDirty=In(this.currentP6LatestRunLog,this.p6LatestRunLogAtLastSave),this.p6TrackingEnabled&&this.snapshotP6Activities(p),!a||!o)return;let y=new Map(a.map(h=>[String(h.id),h])),m=new Map(o.map(h=>[String(h.id),h]));for(let h of p){let A=String(h.id);this.activityIsDirty(A,y.get(A)??null)&&this.dirtyActivityIds.add(A)}for(let h of a){let A=String(h.id);this.activityIsDirty(A,h)&&this.dirtyActivityIds.add(A),this.p6TrackingEnabled&&this.p6ActivityIsDirty(A,h)&&this.dirtyP6ActivityIds.add(A)}if(this.p6TrackingEnabled)for(let h of p){let A=String(h.id);this.p6ActivityIsDirty(A,y.get(A)??null)&&this.dirtyP6ActivityIds.add(A)}for(let h of f){let A=String(h.id);this.linkIsDirty(A,m.get(A)??null)&&this.dirtyLinkIds.add(A)}for(let h of o){let A=String(h.id);this.linkIsDirty(A,h)&&this.dirtyLinkIds.add(A)}}snapshotActivities(e){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let n of e){let i=String(n.id);if(!Ae(n.proplannerId)){this.dirtyActivityIds.add(i);continue}let r=kh(n);this.activitiesAtLastSave.set(String(n.id),{persistable:r,deletedSnapshot:{id:n.id,proplannerId:n.proplannerId,parentId:n.parentId,hadBaseline:n.baselineSnapshot!==null||n.baselinePoints.length>0}}),Or(n,r)&&this.dirtyActivityIds.add(i)}}}snapshotLinks(e){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let n of e){let i=String(n.id);if(!Ae(n.proplannerId)){this.dirtyLinkIds.add(i);continue}this.linksAtLastSave.set(String(n.id),{id:n.id,proplannerId:n.proplannerId,source:n.source,target:n.target,lag:n.lag,type:n.type})}}}recordChanges(e,n,i,r){if(!(!this.trackingEnabled||!this.initialized)){for(let a of e){let o=String(a.id),s=i(o);this.activityIsDirty(o,s)?this.dirtyActivityIds.add(o):this.dirtyActivityIds.delete(o),this.p6TrackingEnabled&&(this.p6ActivityIsDirty(o,s)?this.dirtyP6ActivityIds.add(o):this.dirtyP6ActivityIds.delete(o))}for(let a of n){let o=String(a.id),s=r(o);this.linkIsDirty(o,s)?this.dirtyLinkIds.add(o):this.dirtyLinkIds.delete(o)}}}recordP6Settings(e){!this.trackingEnabled||!this.initialized||(this.currentP6Settings=v(e),this.p6SettingsDirty=In(this.currentP6Settings,this.p6SettingsAtLastSave))}recordP6ProjectState(e){!this.trackingEnabled||!this.initialized||(this.currentP6ProjectState=v(e),this.p6ProjectStateDirty=In(this.currentP6ProjectState,this.p6ProjectStateAtLastSave))}recordP6LatestRunLog(e){!this.trackingEnabled||!this.initialized||(this.currentP6LatestRunLog=v(e),this.p6LatestRunLogDirty=In(this.currentP6LatestRunLog,this.p6LatestRunLogAtLastSave))}modifiedP6Settings(){return this.p6SettingsIsDirty()?v(this.currentP6Settings):null}modifiedP6Activities(e){return!this.trackingEnabled||!this.initialized?new Map:wh(this.dirtyP6ActivityIds,e)}activityIsDirty(e,n){let i=this.activitiesAtLastSave.get(e);return n===null?i!==void 0:this.initialCalendarRepairIds.has(e)||!Ae(n.proplannerId)||i===void 0||Or(n,i.persistable)}linkIsDirty(e,n){let i=this.linksAtLastSave.get(e);return n===null?i!==void 0:!Ae(n.proplannerId)||i===void 0||xo(i,n)}acknowledgePersistedLookahead(e,n){if(!this.trackingEnabled||!this.initialized)return;let i=e.map(r=>{let a=typeof r=="string"?r:String(r.id),o=n(a),s=this.activitiesAtLastSave.get(a);if(o===null||s===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof r=="string"||!!r.fields?.isLookahead,acknowledgesProgress:typeof r!="string"&&!!r.fields?.progress,current:o,saved:s}});for(let{activityId:r,acknowledgesLookahead:a,acknowledgesProgress:o,current:s,saved:l}of i){let c={...l.persistable,...a?{isLookahead:s.isLookahead}:{},...o?{progress:s.progress,autoScheduling:s.autoScheduling}:{}};this.activitiesAtLastSave.set(r,{...l,persistable:c}),this.initialCalendarRepairIds.has(r)||!Ae(s.proplannerId)||Or(s,c)?this.dirtyActivityIds.add(r):this.dirtyActivityIds.delete(r)}}hasCheckpointActivityId(e){return this.activitiesAtLastSave.has(e)}hasCheckpointLinkId(e){return this.linksAtLastSave.has(e)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0||this.p6TrackingEnabled&&(this.dirtyP6ActivityIds.size>0||this.p6SettingsIsDirty()||this.p6ProjectStateDirty||this.p6LatestRunLogDirty))}p6SettingsIsDirty(){return this.p6SettingsDirty}snapshotP6Activities(e){this.dirtyP6ActivityIds.clear(),Nh(this.p6ActivitiesAtLastSave,e)}p6ActivityIsDirty(e,n){return Fh(this.p6ActivitiesAtLastSave.get(e),n)}newActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let i of this.dirtyActivityIds){let r=e(i);r!==null&&!Ae(r.proplannerId)&&n.push(r)}return n}newLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let i of this.dirtyLinkIds){let r=e(i);r!==null&&!Ae(r.proplannerId)&&n.push(r)}return n}deletedActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let i of this.dirtyActivityIds){let r=this.activitiesAtLastSave.get(i);r&&e(i)===null&&n.push({...r.deletedSnapshot})}return n}deletedLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let i of this.dirtyLinkIds){let r=this.linksAtLastSave.get(i);r&&e(i)===null&&n.push({...r})}return n}modifiedActivities(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let i of this.dirtyActivityIds){let r=e(i);if(r===null||!Ae(r.proplannerId))continue;let a=this.activitiesAtLastSave.get(i);(a===void 0||this.initialCalendarRepairIds.has(i)||Or(r,a.persistable))&&n.push(r)}return n}modifiedActivityFields(e){let n=new Map;if(!this.trackingEnabled||!this.initialized)return n;for(let i of this.dirtyActivityIds){let r=e(i),a=this.activitiesAtLastSave.get(i);if(!r||!a)continue;let o=Ac(r,a.persistable);o.length>0&&n.set(i,o)}return n}modifiedLinks(e){if(!this.trackingEnabled||!this.initialized)return[];let n=[];for(let i of this.dirtyLinkIds){let r=e(i);if(r===null||!Ae(r.proplannerId))continue;let a=this.linksAtLastSave.get(i);(a===void 0||xo(a,r))&&n.push(r)}return n}clear(){this.initialized=!1,this.p6TrackingEnabled=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.dirtyP6ActivityIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear(),this.p6ActivitiesAtLastSave.clear(),this.p6SettingsAtLastSave=null,this.currentP6Settings=null,this.p6SettingsDirty=!1,this.p6ProjectStateAtLastSave=null,this.currentP6ProjectState=null,this.p6ProjectStateDirty=!1}};var Mh=1440*60*1e3,Uh=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/,Ho=7,Sc=[!1,!0,!0,!0,!0,!0,!1],Hh=new Set(["1","true"]),vc=_t.DURATION,Bh=D.ASAP,jh={ASAP:D.ASAP,ALAP:D.ALAP,SNET:D.SNET,SNLT:D.SNLT,FNET:D.FNET,FNLT:D.FNLT,MSO:D.MSO,MFO:D.MFO,"AS SOON AS POSSIBLE":D.ASAP,"AS LATE AS POSSIBLE":D.ALAP,"START NO EARLIER THAN":D.SNET,"START NO LATER THAN":D.SNLT,"FINISH NO EARLIER THAN":D.FNET,"FINISH NO LATER THAN":D.FNLT,"MUST START ON":D.MSO,"MUST FINISH ON":D.MFO};function Wh(t,e){let n=[],i=t.map(a=>{let o=SE(a,e);return a.should_be_showed===!1&&n.push(o.id),o});CE(i);let r=new Set(i.map(a=>a.id));return DE(i,r,e.reporter,e.recordDiagnostic),{activities:i,activityIds:r,hiddenIds:n}}function dE(t,e,n,i){if(!t)return null;let r=jh[t.toUpperCase()];return r===void 0?(n(Wt.UNKNOWN_CONSTRAINT,i),e.warn(`[parseFromBackend] unknown constraint label "${t}" \u2014 defaulting to "asap"`),Bh):r}function uE(t,e,n){let i=dE(t.constraint,e,n,String(t.unique_id)),a=i!==D.ASAP&&i!==D.ALAP&&t.constraint_date?Me(t.constraint_date):null;return{constraintType:i,constraintDate:a}}function pE(t,e,n){if(t==null)return n;let i=String(t);return e.has(i)?i:n}function fE(t){if(t==null||t==="")return[];if(Array.isArray(t))return t.map(String);if(typeof t!="string")return[];try{let e=JSON.parse(t);return Array.isArray(e)?e.map(String):[]}catch{return[]}}function yE(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return typeof e=="string"||typeof e=="number"}function Cc(t){if(!Array.isArray(t))return[];let e=[];for(let n of t)yE(n)&&e.push(String(n.id));return e}function hE(t){return t==="0"?null:String(t)}function mE(t){if(t==null)return null;if(!(typeof t=="number"&&(t===0||Number.isSafeInteger(t)&&t>0)))throw new Error(`invalid activity proplannerId ${String(t)}`);return t}function gE(t){let e=Number(t);if(!Number.isFinite(e)||e<0||e>bs)throw new TypeError(`invalid activity progress ${String(t)}`);return e}function AE(t,e){return typeof t.is_critical=="boolean"?t.is_critical:(e.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${t.unique_id}" received ${typeof t.is_critical}`)),!1)}function IE(t,e,n,i,r){return Array.isArray(t)?t.map(a=>Do(a,e,{record:n,sampleId:i},r)).filter(a=>a!==null):[]}function SE(t,e){let n=pE(t.calendarId,e.knownCalendarIds,e.defaultCalendarId),i=t.calendarId==null||!e.knownCalendarIds.has(String(t.calendarId)),r=gE(t.progress),{constraintType:a,constraintDate:o}=uE(t,e.reporter,e.recordDiagnostic),s=t.type===k.MILESTONE,l=Me(t.start_date),c=s?l:Me(t.end_date),d=s?0:Number(t.duration),u=AE(t,e.reporter);return{id:String(t.unique_id),proplannerId:mE(t.id),parentId:hE(t.parent_id),name:t.name,description:t.description??"",type:t.type,startDate:l,endDate:c,durationHours:wn(d,e.hoursPerDay),constraintType:a,constraintDate:o,autoScheduling:Nn(r),calendarId:n,assignedDefaultCalendar:n!=null&&i,dateOrigin:t.date_origin==null?null:Me(t.date_origin),progress:r,cost:Number(t.cost),usedCost:Number(t.used_cost??0),realCost:Number(t.real_cost??0),workHours:Number(t.hhWorkTime),realWorkHours:Number(t.real_work??0),ponderator:Number(t.ponderator??0),hasCustomPonderator:t.hasCustomPonderator,correlativeId:t.correlative_id,uniqueCorrelativeId:t.unique_correlative_id,customId:vE(t),subcontractId:t.subcontractId,isLookahead:t.isOnLookahead,hasLookaheadTasks:Array.isArray(t.tasks)&&t.tasks.length>0,newActivityIds:fE(t.newActivitiesArray),hasNewActivities:t.hasNewActivities??!1,...t.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Cc(t.pendingRequests),responsableIds:Cc(t.responsables),tagIds:Cc(t.tags),baselinePoints:IE(t.baseline_points,e.reporter,e.recordDiagnostic,String(t.unique_id),s),baselineSnapshot:null,baselineVarianceDays:null,recursiveDurationHours:wn(Number(t.sumOfDurationRecursively??0),e.hoursPerDay),calendarDuration:Te({type:t.type,startDate:l,endDate:c}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function vE(t){return t.has_childs?null:t.custom_id}function CE(t){let e=t.find(n=>n.correlativeId===0&&n.type===k.PROJECT);e&&(e.parentId=null)}function DE(t,e,n,i){for(let r of t)r.parentId!==null&&(e.has(r.parentId)||(n.warn(`[parseFromBackend] activity "${r.id}" references unknown parent "${r.parentId}" \u2014 re-parenting to root (null)`),i(Wt.ORPHAN_ACTIVITY,r.id),r.parentId=null))}function jo(t,e,n,i=null){let o=(t!==void 0&&t.length>0?t:e??[]).map(l=>_E(l,i)),s=(n??[]).map(l=>EE(l,i));return{calendars:o,baseCalendars:s,knownCalendarIds:new Set(o.map(l=>l.id)),defaultCalendarId:TE(o)}}function TE(t){let e=t.find(i=>i.is_default);if(e)return e.id;let n=t[0];return n?n.id:null}function Gh(t,e){let n=bE(t.working_days),{days:i,hours:r}=OE(t,n),a=PE(e.exceptionsSource,e.exceptionRange),o={days:i,hours:r};return a&&(o.dates=a),{id:`${String(t.id)}${e.idSuffix}`,name:t.name,is_default:e.isDefault,...e.baseDefault!==void 0?{baseDefault:e.baseDefault}:{},worktime:o}}function _E(t,e){let n=t.baseDefault,i=typeof n=="boolean"?n:void 0;return Gh(t,{idSuffix:"",isDefault:!!t.is_default,baseDefault:i,exceptionsSource:t.exceptiondays,exceptionRange:e})}function EE(t,e){return Gh(t,{idSuffix:"-base",isDefault:!1,baseDefault:!!t.is_default,exceptionsSource:t.baseexceptiondays??t.exceptiondays,exceptionRange:e})}function PE(t,e){if(!Array.isArray(t)||t.length===0)return null;let n={};for(let i of t){if(!i)continue;let r=RE(i.from_date,i.to_date,e);if(r.length===0)continue;let a=kE(i);if(a!==void 0)for(let o of r)n[o]=a}return Object.keys(n).length>0?n:null}function RE(t,e,n){let i=Vh(t),r=Vh(e);if(i===null||r===null)return[];if(n&&(r<n.start||i>n.end))return[];let a=[],o=n?Math.max(i,n.start):i,s=n?Math.min(r,n.end):r;for(;o<=s;)a.push(String(o)),o+=Mh;return a}function Vh(t){if(typeof t!="string")return null;let e=Uh.exec(t.trim());if(!e)return null;let n=Number(e[1]),i=Number(e[2]),r=Number(e[3]);return Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(r)?Date.UTC(n,i-1,r):null}function kE(t){if(t.workable===!1)return!1;let e=t.shifts;if(Array.isArray(e)&&e.length>0){let n=LE(e);if(n.length>0)return n}}var Kh=/^\d{1,2}:\d{2}$/;function LE(t){let e=[];for(let n of t){let i=zh(n?.shift_string);if(!i)continue;if(!i.startsCsv.includes(",")&&!i.endsCsv.includes(",")){let s=i.startsCsv.trim(),l=i.endsCsv.trim();!Bo(s)&&!Bo(l)&&Kh.test(s)&&Kh.test(l)&&e.push(`${s}-${l}`);continue}let o=qh(i.startsCsv,i.endsCsv).find(s=>s!==null);o&&e.push(o)}return e.sort($h),e}function Yh(t){let e=t.indexOf("-"),n=e>0?t.slice(0,e):t,[i,r]=n.split(":");return(Number(i)||0)*60+(Number(r)||0)}function $h(t,e){return Yh(t)-Yh(e)}function OE(t,e){let n=Array.from({length:7},()=>[]),i=(c,d)=>{let u=qh(c,d);for(let p=0;p<7;p+=1){let f=u[p],y=n[p];f&&y&&y.push(f)}},r=Array.isArray(t.shifts)&&t.shifts.length>0,a=typeof t.shift_start=="string"&&typeof t.shift_end=="string";if(r)for(let c of t.shifts){let d=zh(c?.shift_string);d&&i(d.startsCsv,d.endsCsv)}else a&&i(t.shift_start,t.shift_end);for(let c of n)c.sort($h);let s=n.find((c,d)=>!!e[d]&&c.length>0)??[];return{days:e.map((c,d)=>{if(!c)return!1;let u=n[d];return u&&u.length>0?u:s}),hours:s}}function qh(t,e){let n=Array.from({length:Ho},()=>null);if(typeof t!="string"||typeof e!="string")return n;let i=t.split(",").map(s=>s.trim()),r=e.split(",").map(s=>s.trim());if(!(i.length===r.length&&i.length>0&&i.length<=Ho))return n;let o=[...n];for(let s=0;s<i.length;s+=1){let l=i[s],c=r[s];Bo(l)||Bo(c)||(o[s]=`${l}-${c}`)}return o}function zh(t){if(typeof t!="string")return null;let e=t.indexOf("-");return e<=0?null:{startsCsv:t.slice(0,e),endsCsv:t.slice(e+1)}}function bE(t){if(typeof t!="string")return[...Sc];let e=t.split(",").map(n=>n.trim());return e.length!==Ho?[...Sc]:e.map(n=>Hh.has(n))}var NE=new Set(["false","null"]);function Bo(t){return!t||NE.has(t)}function FE(t){if(typeof t!="string")return null;let e=eu(t);return e||(Jr(t)?t:null)}function wE(t){if(t==null)return;if(!(typeof t=="number"&&(t===0||Number.isSafeInteger(t)&&t>0)))throw new Error(`invalid link proplannerId ${String(t)}`);return t}function Xh(t,e){let n=[];for(let i of t)try{n.push(xE(i,e.knownActivityIds,e.hoursPerDay))}catch(r){e.recordDiagnostic(Wt.INVALID_LINK,String(i.unique_id??i.id)),e.reporter.warn("[parseFromBackend] dropping invalid link",r)}return ME(n,e.recordDiagnostic)}function xE(t,e,n){let i=String(t.unique_id??t.id),r=String(t.source_id??t.source??""),a=String(t.target_id??t.target??"");if(!e.has(r))throw new Error(`[parseFromBackend] link "${i}" source "${r}" does not exist`);if(!e.has(a))throw new Error(`[parseFromBackend] link "${i}" target "${a}" does not exist`);let o=FE(t.type);if(o===null)throw new Error(`[parseFromBackend] link "${i}" has invalid type "${String(t.type)}"`);let s=t.ganttId,l=t.sectorId,c=wE(t.id);return{id:i,source:r,target:a,type:o,lag:ne(Number(t.lag??0),n),freeSlackHours:null,isCritical:!1,...typeof s=="number"?{ganttId:s}:{},...typeof l=="number"?{sectorId:l}:{},...c===void 0?{}:{proplannerId:c}}}function ME(t,e){let n=new Map;for(let i of t){let r=`${i.source}-${i.target}-${i.type}`,a=n.get(r);if(!a){n.set(r,i);continue}let o=Jh(i)>Jh(a),s=o?a:i;e(Wt.DUPLICATE_LINK,s.id),o&&n.set(r,i)}return[...n.values()]}function Jh(t){let e=Number(t.id);return Number.isFinite(e)?e:-1/0}function UE(t){if(typeof t!="string")return vc;switch(t.toUpperCase()){case _t.DURATION:return _t.DURATION;case _t.COST:return _t.COST;case _t.WORK_HOURS:return _t.WORK_HOURS;default:return vc}}function HE(t){let e=t.custom_id_prefix;return typeof e=="string"&&e.length>0?e:void 0}function BE(t){let e=t.custom_id_increment;return typeof e=="string"?e:typeof e=="number"&&Number.isFinite(e)?String(e):void 0}function Zh(t){let e=HE(t),n=BE(t),i=t.update_duration_for_primavera_for_end_date===!0;return{id:String(t.id),name:t.name,hoursPerDay:t.hoursPerDay,hoursPerWeek:t.hoursPerWeek,dateFormat:t.dateFormat,projectId:t.projectId,companyId:t.companyId,...e!==void 0?{customIdPrefix:e}:{},...n!==void 0?{customIdIncrement:n}:{},...i?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:UE(t.activity_creter),statusCriteria:zs,ganttId:null}}function Wo(t,e=pi,n=xi){let i=Zh(t.sector),{calendars:r,baseCalendars:a,knownCalendarIds:o,defaultCalendarId:s}=jo(t.calendars,t.sector.calendars,t.baseCalendars,jE(t.activities)),{activities:l,activityIds:c,hiddenIds:d}=Wh(t.activities,{knownCalendarIds:o,defaultCalendarId:s,hoursPerDay:i.hoursPerDay,reporter:e,recordDiagnostic:n}),u=Xh(t.links,{knownActivityIds:c,hoursPerDay:i.hoursPerDay,reporter:e,recordDiagnostic:n});return{sector:i,activities:l,links:u,calendars:r,baseCalendars:a,viewStateSeed:{hiddenIds:d}}}function jE(t){let e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let a of t){let o=new Date(a.start_date).getTime(),s=new Date(a.end_date).getTime();Number.isFinite(o)&&(e=Math.min(e,o)),Number.isFinite(s)&&(n=Math.max(n,s))}if(!Number.isFinite(e)||!Number.isFinite(n))return null;let i=new Date(e),r=new Date(n);return i.setFullYear(i.getFullYear()-1),r.setFullYear(r.getFullYear()+1),{start:i.getTime(),end:r.getTime()}}function Dc(t={}){let e=t.seed??0,n=i=>{i>e&&(e=i)};if(t.knownIds)for(let i of t.knownIds){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)}return{fork(){return Dc({seed:e})},next(){return e+=1,String(e)},bump(i){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)},snapshot(){return e},restore(i){e=i}}}function Tc(t={}){let e=t.seed??0,n=i=>{i>e&&(e=i)};if(t.knownIds)for(let i of t.knownIds){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)}return{fork(){return Tc({seed:e})},next(){return e+=1,String(e)},bump(i){let r=typeof i=="number"?i:Number(i);Number.isFinite(r)&&n(r)},snapshot(){return e},restore(i){e=i}}}function _c(t={}){let e=t.seed??0,n=i=>{Number.isFinite(i)&&i>0&&i<=9999999&&i>e&&(e=i)};if(t.knownIds)for(let i of t.knownIds){if(i==null)continue;let r=typeof i=="number"?i:Number(i);n(r)}return{fork(){return _c({seed:e})},next(){return e+=1,String(e)},bump(i){if(i==null)return;let r=typeof i=="number"?i:Number(i);n(r)},snapshot(){return e},restore(i){e=i}}}function Qh(t){return!!t&&typeof t=="string"&&t.trim().length>0}function Vo(t){if(!t||typeof t!="string"||t.trim().length===0)return"";let e=t.match(/^(.*?)(\d+)$/);return e?e[1]??"":t}function Ko(t){if(!t||typeof t!="string"||t.trim().length===0)return"";let e=t.match(/(\d+)$/);return e?e[1]??"":""}function tm(t){if(!t||typeof t!="object")return"";let e=t.customId;return typeof e=="string"?e:""}function em(t,e){return!e&&Qh(t)}function nm(t,e){return e&&Qh(t)}function br(t){return typeof t=="string"&&t.length>0&&/^\d+$/.test(t)}function Yo(t){if(!br(t))return 0n;try{return BigInt(t)}catch{return 0n}}function WE(t,e){if(typeof t!="bigint")return"";let n=t.toString();if(!br(e))return n;let i=e.length;return n.padStart(i,"0")}function le(t,e){let n=Yo(t),i=Yo(e),r=n+i;return WE(r,t)}function Go(t,e){let n=Yo(t),i=Yo(e);return n<i?-1:n>i?1:0}function $o(t,e){return Go(t,e)<=0?t:e}function qo(t,e){return Go(t,e)>=0?t:e}function im(t){if(!t||t.length===0)throw new Error("minSuffixFromArray requires non-empty array");return t.reduce((e,n)=>$o(e,n))}function rm(t){if(!t||t.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return t.reduce((e,n)=>qo(e,n))}var He={PARENT_CONVERSION:"parentConversion",PASTE_REFERENCE:"pasteReference",NO_CONTEXT:"noContext"};function am(t){return{prefix:t,baseSuffix:null}}function om(t,e){let n=Ko(t);return{prefix:Vo(t),baseSuffix:le(n,e)}}function sm(t){return{prefix:t,baseSuffix:null}}function lm(t,e){return em(t,e)?He.PARENT_CONVERSION:nm(t,e)?He.PASTE_REFERENCE:He.NO_CONTEXT}function cm(t){return{...t,usedSuffixes:new Set(t.usedSuffixes)}}var zo=class t{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 e=this._journalPrefixBefore,n=this._journalIds;if(!(e===null||n===null)){for(let[i,r]of e)r===null?this.prefixMap.delete(i):this.prefixMap.set(i,r);for(let i of[...n].reverse())i.hadId?this.processedIds.add(i.customId):this.processedIds.delete(i.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(e){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:n}=this.analyzeCustomId(e);if(!this._journalPrefixBefore.has(n)){let i=this.prefixMap.get(n);this._journalPrefixBefore.set(n,i?cm(i):null)}this._journalIds.push({customId:e,hadId:this.processedIds.has(e)})}_ensureFreshBounds(e){let n=this.prefixMap.get(e);if(!n?.boundsDirty)return;n.boundsDirty=!1;let i=Array.from(n.usedSuffixes);n.min=im(i),n.max=rm(i),n.quantity=i.length,this._recalculateNext(e)}defaultPrefix;suffixIncrement;constructor(e={}){this.defaultPrefix=e.defaultPrefix??"A",this.suffixIncrement=e.suffixIncrement??"10"}fork(){let e=new t({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[n,i]of this.prefixMap)e.prefixMap.set(n,cm(i));for(let n of this.processedIds)e.processedIds.add(n);return e}extractPrefix(e){return Vo(e)}extractSuffix(e){return Ko(e)}analyzeCustomId(e){return{prefix:this.extractPrefix(e),suffix:this.extractSuffix(e)}}_updatePrefixStats(e,n){if(this._ensureFreshBounds(e),!this.prefixMap.has(e)){this.prefixMap.set(e,{min:n,max:n,next:n,quantity:1,usedSuffixes:new Set([n])}),this._recalculateNext(e);return}let i=this.prefixMap.get(e);i.usedSuffixes.has(n)||(i.usedSuffixes.add(n),i.min=$o(n,i.min),i.max=qo(n,i.max),i.quantity+=1,this._recalculateNext(e))}_recalculateNext(e){let n=this.prefixMap.get(e);if(!n)return;let i=this.getNextAvailableSuffix(e);n.next=i??this.suffixIncrement}getPrefixStats(e){this._ensureFreshBounds(e);let n=this.prefixMap.get(e);return n?{min:n.min,max:n.max,next:n.next,quantity:n.quantity}:null}getNextSuffix(e){this._ensureFreshBounds(e);let n=this.prefixMap.get(e);return n?n.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(e){if(!e||typeof e!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:i}=this.analyzeCustomId(e);if(!n&&!i)return{prefix:n,suffix:i};if(this._noteCustomIdBefore(e),this._ensureFreshBounds(n),this.prefixMap.has(n)){let r=this.prefixMap.get(n);r.usedSuffixes.has(i)||(r.usedSuffixes.add(i),r.min=$o(i,r.min),r.max=qo(i,r.max),r.quantity+=1,this._recalculateNext(n))}else this.prefixMap.set(n,{min:i,max:i,next:le(i,this.suffixIncrement),quantity:1,usedSuffixes:new Set([i])});return this.processedIds.add(e),{prefix:n,suffix:i}}releaseCustomId(e=null){if(!e||typeof e!="string")return{prefix:"",suffix:""};let{prefix:n,suffix:i}=this.analyzeCustomId(e);if(!this.prefixMap.has(n))return{prefix:n,suffix:i};this._noteCustomIdBefore(e);let r=this.prefixMap.get(n);return r.usedSuffixes.has(i)&&(r.usedSuffixes.delete(i),r.quantity-=1,r.usedSuffixes.size===0?this.prefixMap.delete(n):r.boundsDirty=!0),this.processedIds.delete(e),{prefix:n,suffix:i}}trackCustomIdChange(e,n){let i=this.releaseCustomId(e),r=this.registerCustomId(n);return{oldPrefix:i.prefix,oldSuffix:i.suffix,newPrefix:r.prefix,newSuffix:r.suffix}}_exceedsMaxLength(e){return e.length>20}_shouldSearchForGaps(e){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return!1;let n=this.prefixMap.get(e);return`${e}${le(n.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(e,n){let i=n&&br(n)?n:this.suffixIncrement;return`${e}${i}`.length>20?null:i}_findFirstAvailableGap(e){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return null;let n=this.prefixMap.get(e),i=this.suffixIncrement;for(;Go(i,n.max)<0;){if(`${e}${i}`.length>20)return null;if(!n.usedSuffixes.has(i))return i;i=le(i,this.suffixIncrement)}return null}_generateDefaultCustomId(){let e=this.getNextAvailableSuffix(this.defaultPrefix);if(e===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let n=this._findFirstAvailableGap(this.defaultPrefix);if(n!==null)return`${this.defaultPrefix}${n}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${e}`}getNextAvailableSuffix(e,n=null){if(this._ensureFreshBounds(e),!this.prefixMap.has(e))return this._suffixForUnknownPrefix(e,n);let i=this.prefixMap.get(e),r=this.suffixIncrement;if(!n||!br(n)){let s=le(i.max,r);return`${e}${s}`.length>20?null:s}let a=n;for(let s=0;s<100;s++){if(`${e}${a}`.length>20)return null;if(!i.usedSuffixes.has(a))return a;a=le(a,r)}let o=le(i.max,r);return`${e}${o}`.length>20?null:o}generateNextCustomId(e){let n=this.getNextAvailableSuffix(e);if(n===null)return this._generateDefaultCustomId();if(this.prefixMap.has(e)){let r=this.prefixMap.get(e),a=0;for(;r.usedSuffixes.has(n)&&a<1e4;){let o=this.getNextAvailableSuffix(e,le(n,this.suffixIncrement));if(o===null)return this._generateDefaultCustomId();n=o,a++}}let i=`${e}${n}`;return this._exceedsMaxLength(i)&&(i=this._generateDefaultCustomId()),i}populateFromActivities(e){if(!Array.isArray(e))return this;let n=[...new Set(e.filter(i=>i&&typeof i.customId=="string"&&i.customId).map(i=>i.customId))];for(let i of n){if(this.processedIds.has(i))continue;let{prefix:r,suffix:a}=this.analyzeCustomId(i);(r||a)&&(this._updatePrefixStats(r,a),this.processedIds.add(i))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(e){let{activity:n,useActivityCustomIdAsReference:i=!1}=e,r=tm(n),a=lm(r,i),{prefix:o,baseSuffix:s}=this._applyGenerationStrategy(a,r),l=null;if(a===He.PARENT_CONVERSION&&this.prefixMap.has(o)){this._ensureFreshBounds(o);let p=this.prefixMap.get(o).max;l=le(p,this.suffixIncrement)}a===He.PARENT_CONVERSION&&this.releaseCustomId(r);let c=a===He.PARENT_CONVERSION&&l?l:s,d=this.getNextAvailableSuffix(o,c);if(d===null){let p=this._generateDefaultCustomId();return this.registerCustomId(p),p}let u=`${o}${d}`;return this._exceedsMaxLength(u)&&(u=this._generateDefaultCustomId()),this.registerCustomId(u),u}_applyGenerationStrategy(e,n){switch(e){case He.PARENT_CONVERSION:return am(this.defaultPrefix);case He.PASTE_REFERENCE:return om(n,this.suffixIncrement);default:return sm(this.defaultPrefix)}}generateCustomIdForRestoredChild(e=null){if(e){let i=e.trim();if(i.length>0){let r=this.extractPrefix(i),a=this.extractSuffix(i),o=le(a,this.suffixIncrement),s=this.getNextAvailableSuffix(r,o);if(s===null){let c=this._generateDefaultCustomId();return this.registerCustomId(c),c}let l=`${r}${s}`;return this._exceedsMaxLength(l)&&(l=this._generateDefaultCustomId()),this.registerCustomId(l),l}}let n=this.generateNextCustomId(this.defaultPrefix);return this.registerCustomId(n),n}clear(){this.prefixMap.clear(),this.processedIds.clear()}getTotalPrefixes(){return this.prefixMap.size}hasPrefix(e){return this.prefixMap.has(e)}isCustomIdInUse(e,n=null){if(!e||typeof e!="string"||!e.trim())return!1;let i=e.trim();return n&&i===n.trim()?!1:this.processedIds.has(i)}};var VE=1,KE=-1;function YE(t,e){if(t===void 0&&e===void 0)return 0;if(t===void 0)return VE;if(e===void 0)return KE;let n=Math.min(t.length,e.length);for(let i=0;i<n;i+=1){let r=(t[i]??0)-(e[i]??0);if(r!==0)return r}return t.length-e.length}function dm(t,e,n,i){let r=n.assignmentByActivityId.get(String(t.id)),a=n.assignmentByActivityId.get(String(e.id)),o=YE(r===void 0?void 0:n.sequencePathByValueId.get(r),a===void 0?void 0:n.sequencePathByValueId.get(a));return i===Ut.DESCENDING?-o:o}var GE=1,$E=-1;function qE(t,e){return!t&&!e?null:t&&e?0:t?GE:$E}function um(t){return t==null}function pm(t,e){let n=e.indexOf(String(t));return n===-1?e.length:n}function zE(t,e,n){return t instanceof Date&&e instanceof Date?t.getTime()-e.getTime():typeof t=="number"&&typeof e=="number"?t-e:typeof t=="boolean"&&typeof e=="boolean"?Number(t)-Number(e):Array.isArray(t)&&Array.isArray(e)?t.length-e.length:String(t).localeCompare(String(e),n,{sensitivity:"base",numeric:!0})}function JE(t,e,n){if(ai(t)){let r=n.get(t.key);return r===void 0?null:(a,o)=>dm(a,o,r,t.direction)}let i=ze(t.field);return i===null?null:(r,a)=>{let o=i.extract(r,e),s=i.extract(a,e),l=qE(um(o),um(s));if(l!==null)return l;let c=i.valueKind===F.ENUM?pm(o,i.order)-pm(s,i.order):zE(o,s,e.locale);return t.direction===Ut.DESCENDING?-c:c}}function fm(t,e,n=ra){let i=t.rules.map(r=>JE(r,e,n)).filter(r=>r!==null);return i.length===0?null:(r,a)=>{for(let o of i){let s=o(r,a);if(s!==0)return s}return 0}}function ym(t){let e=[];t.forEachActivity((n,i)=>{n.type===k.PROJECT&&t.getChildren(String(i)).length===0&&e.push(String(i))});for(let n of e)t.setActivityField(n,U.TYPE,li),XE(t,n);return e}function XE(t,e){let n=t.getActivity(e);if(!n||!n.startDate||n.durationHours==null)return;let i=new Date(n.startDate);i.setUTCHours(0,0,0,0);let r=t.getClosestWorkTime({date:i,dir:q.FUTURE,task:n});if(r.getTime()===n.startDate.getTime())return;let a=t.calculateEndDate({startDate:r,durationHours:n.durationHours,task:n});t.setActivityField(e,U.START_DATE,r),t.setActivityField(e,U.END_DATE,a)}function hm(t){let e=[],n=[];t.forEachActivity((r,a)=>{r.parentId===null&&e.push(String(a))});let i=r=>{let a=t.getActivity(r);if(!a)return 0;let o=[...t.getChildren(r)],s=o.length===0?$t(a.workHours,a.progress):o.reduce((l,c)=>l+i(String(c)),0);return t.setActivityField(r,U.REAL_WORK_HOURS,s),n.push(r),s};for(let r of e)i(r);return n}async function mm(t){let{state:e,sector:n,scheduler:i,skipAutoSchedule:r,now:a}=t;if(xt(e),n.updateDurationForPrimaveraEndDate&&QE(e),tP(e),hm(e),r){sr(e),a&&(Bn(e,a),Ue(e,n.statusCriteria)),jn(e,n.hoursPerDay);return}let o=await i.schedule({});rr(e,o),eP(e),ZE(e),await we(e,void 0,!1),sr(e),a&&(Bn(e,a),Ue(e,n.statusCriteria)),jn(e,n.hoursPerDay)}function ZE(t){t.forEachActivity(e=>{e.autoScheduling||!e.startDate||e.durationHours==null||t.getChildren(e.id).length>0||(e.endDate=t.calculateEndDate({startDate:e.startDate,durationHours:e.durationHours,task:e}),e.calendarDuration=Te(e))})}function QE(t){t.forEachActivity(e=>{!e.startDate||!e.endDate||(e.durationHours=t.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:e}))})}function tP(t){t.forEachActivity(e=>{let n=e.constraintType;if(!n||!e.constraintDate)return;let i=e.constraintDate;if(e.type===k.MILESTONE&&(i.getUTCHours()!==0||i.getUTCMinutes()!==0))return;let r=t.calendarReader.getCalendar(String(e.calendarId));r&&(e.constraintDate=fe(e.constraintDate,r,n))})}function eP(t){t.forEachActivity(e=>{if(e.type!==k.MILESTONE)return;let n=e.constraintType;if(!n||!e.constraintDate)return;let i=t.calendarReader.getCalendar(String(e.calendarId));i&&(e.constraintDate=fe(e.constraintDate,i,n))})}function gm(t){if(t.p6===void 0)return t;let e=t.p6,n={...e,activityType:e.activityType??ie.TASK,durationType:e.durationType??re.FIXED_DURATION_AND_UNITS,primaryConstraintType:e.primaryConstraintType??null,primaryConstraintDate:e.primaryConstraintDate??null,sourcePrimaryConstraintToken:e.sourcePrimaryConstraintToken??null,sourceSecondaryConstraintToken:Reflect.get(e,"sourceSecondaryConstraintToken")??null,resourceAssignments:e.resourceAssignments??[]};return delete n.sourceActivityTypeToken,delete n.sourceDurationTypeToken,{...t,p6:n}}function Ec(t){if(!t.hasCompleteSchedulingState)return{};let e=_i(t.activity);return e===void 0?{}:{p6:e}}function Am(t){return{activityPatch:t.p6===void 0?{}:{p6:void 0},snapshotPatch:t.p6===void 0?{}:{p6:v(t.p6)}}}function Im(t){let e=t.promotionSnapshot?.p6;return e===void 0?Ec(t):{p6:v(e)}}function vm(t,e){let n=e==="before";return{...t.p6Settings===void 0?{}:{p6Settings:n?Sm(t.p6Settings):v(t.p6Settings)},...t.p6ProjectPlannedStart===void 0?{}:{p6ProjectPlannedStart:n?Sm(t.p6ProjectPlannedStart):v(t.p6ProjectPlannedStart)}}}function Cm(t,e,n){t.p6Settings!==void 0&&n.setSettings(v(t.p6Settings[e])),t.p6ProjectPlannedStart!==void 0&&n.setProjectPlannedStart(v(t.p6ProjectPlannedStart[e]))}function Dm(t){return t.p6Settings!==void 0||t.p6ProjectPlannedStart!==void 0}function Sm(t){return{before:v(t.after),after:v(t.before)}}function _m(t,e){let n=e.projectState?.plannedStart??null,i=t.projectState?.plannedStart??null;return{...Tm(e.settings,t.settings)?{p6Settings:{before:v(e.settings),after:v(t.settings)}}:{},...Tm(n,i)?{p6ProjectPlannedStart:{before:v(n),after:v(i)}}:{}}}function Tm(t,e){return Tt(t)!==Tt(e)}var Em="Invalid P6 activity status",Pc=class extends Error{constructor(n,i){super(`${Em}: ${i}`);this.code=n;this.name="P6ActivityStatusError"}code},nP=100,iP=0;function Pm(t){Rm(t.remainingDurationHours),km(t),aP(t),Lm(t)}function Nr(t){rP(t.remainingDurationHours),km(t),oP(t),Lm(t)}function Jo(t,e){if(e.actualStart===void 0&&e.actualFinish===void 0)return e;let n=e.actualStart!==void 0?e.actualStart:t.actualStart,i=e.actualFinish!==void 0?e.actualFinish:t.actualFinish,r=i!==null?"completed":n!==null?"in_progress":"not_started",a=n===null&&i===null&&t.actualStart!==null,o={...e,executionStatus:r,...i!==null?{remainingDurationHours:0,physicalPercentComplete:nP}:{},...a?{remainingDurationHours:t.originalDurationHours,physicalPercentComplete:iP}:{}};return Nr({...t,...o}),o}function Rm(t){(!Number.isFinite(t)||t<0)&&Yt("Remaining Duration must be finite and non-negative")}function rP(t){t!==null&&Rm(t)}function km(t){[t.actualStart,t.actualFinish,t.suspendDate,t.resumeDate].some(n=>n!==null&&Number.isNaN(n.getTime()))&&Yt("actual, suspend and resume dates must be valid")}function aP(t){let e=t.actualStart!==null,n=t.actualFinish!==null;if(t.executionStatus==="not_started"){(e||n)&&Yt("not_started cannot have actual dates");return}if(t.executionStatus==="in_progress"){(!e||n)&&Yt("in_progress requires Actual Start and no Actual Finish");return}(!e||!n||t.remainingDurationHours!==0)&&Yt("completed requires Actual Start, Actual Finish and zero Remaining Duration")}function oP(t){let e=t.actualStart!==null,n=t.actualFinish!==null;n&&!e&&Yt("Actual Finish requires Actual Start"),t.executionStatus==="not_started"&&e&&Yt("not_started cannot have actual dates"),t.executionStatus==="in_progress"&&n&&Yt("in_progress cannot have Actual Finish"),t.executionStatus==="completed"&&t.remainingDurationHours!==null&&t.remainingDurationHours!==0&&Yt("completed requires zero Remaining Duration")}function Lm(t){let{actualStart:e,actualFinish:n,suspendDate:i,resumeDate:r}=t;if(e!==null&&n!==null&&e.getTime()>n.getTime())throw new Pc("ACTUAL_FINISH_BEFORE_START","Actual Start must not be after Actual Finish");i!==null&&(e===null&&Yt("Suspend requires Actual Start"),e.getTime()>i.getTime()&&Yt("Suspend must not be before Actual Start"),n!==null&&i.getTime()>n.getTime()&&Yt("Suspend must not be after Actual Finish")),r!==null&&(i===null&&Yt("Resume requires Suspend"),i.getTime()>r.getTime()&&Yt("Suspend must not be after Resume"),n!==null&&r.getTime()>n.getTime()&&Yt("Resume must not be after Actual Finish"))}function Yt(t){throw new Error(`${Em}: ${t}`)}var Rc="Invalid P6 derived input",Lc=100,Fr=0,Wi=100,sP=16,lP=8,cP="178",Oc=Date.parse("2026-10-07T12:00:00.000Z"),dP=Date.parse("2026-10-08T12:00:00.000Z"),uP=Date.parse("2026-10-12T12:00:00.000Z"),pP=Date.parse("2026-10-06T08:00:00.000Z"),fP=Oc,yP=Oc,hP=Date.parse("2026-10-08T12:00:00.000Z"),mP=Date.parse("2026-10-05T08:00:00.000Z"),gP=Date.parse("2026-10-06T08:00:00.000Z");function wr(t,e){return Pm(t),AP(t,e.dataDate),{actualDurationHours:bm(t,e),atCompletionDurationHours:IP(t,e),durationPercentComplete:SP(t),unitsPercentComplete:vP(t,e),schedulePercentComplete:bc(t,e),remainingFloatHours:TP(t,e.calendar,e.totalFloatMethod??"finish_float")}}function Om(t,e){return bm(t,e)}function AP(t,e){let n=[t.originalDurationHours,t.remainingDurationHours],i=[t.actualLaborUnits,t.remainingLaborUnits,t.actualNonlaborUnits,t.remainingNonlaborUnits];if(n.some(r=>!Number.isFinite(r)||r<0))throw new Error(`${Rc}: expected finite non-negative durations`);if(i.some(r=>!Number.isFinite(r)))throw new Error(`${Rc}: expected finite unit scalars`);if(Number.isNaN(e.getTime()))throw new Error(`${Rc}: invalid Data Date`)}function bm(t,e){if(t.executionStatus==="not_started"||t.actualStart===null)return 0;let n=t.executionStatus==="completed"?t.actualFinish:e.dataDate;return n===null?0:kc(e.calendar,t.actualStart,n)}function IP(t,e){return t.executionStatus==="not_started"?_P(e.calendar,t.plannedStart,t.plannedFinish):t.executionStatus==="in_progress"?t.actualStart===null||t.remainingEarlyFinish===null?0:kc(e.calendar,t.actualStart,t.remainingEarlyFinish):t.actualStart===null||t.actualFinish===null?0:kc(e.calendar,t.actualStart,t.actualFinish)}function kc(t,e,n){return e.getTime()>=n.getTime()?0:Vi(t,e,n)}function SP(t){return t.originalDurationHours===0?0:Nm((t.originalDurationHours-t.remainingDurationHours)/t.originalDurationHours*Lc)}function vP(t,e){let n=t.actualLaborUnits+t.actualNonlaborUnits,i=t.remainingLaborUnits+t.remainingNonlaborUnits,r=n+i;return r===0?CP(t,e)?Wi:Fr:n/r*Lc}function CP(t,e){return t.executionStatus!==et.COMPLETED||t.actualStart===null||t.actualFinish===null||t.remainingDurationHours!==0||t.percentCompleteType!==ht.DURATION||e.dataDate.getTime()!==Oc||e.calendarId!==cP||!DP(t)?!1:t.activityType===ie.TASK?t.durationType===re.FIXED_DURATION_AND_UNITS&&t.originalDurationHours===lP&&t.physicalPercentComplete===Wi&&Sn(t.plannedStart,yP)&&Sn(t.plannedFinish,hP)&&Sn(t.actualStart,mP)&&Sn(t.actualFinish,gP):t.activityType===ie.LEVEL_OF_EFFORT&&t.durationType===re.FIXED_DURATION_AND_UNITS_PER_TIME&&t.originalDurationHours===sP&&t.physicalPercentComplete===Wi&&Sn(t.plannedStart,dP)&&Sn(t.plannedFinish,uP)&&Sn(t.actualStart,pP)&&Sn(t.actualFinish,fP)}function DP(t){return t.expectedFinish===null&&t.suspendDate===null&&t.resumeDate===null&&t.secondaryConstraintType===null&&t.secondaryConstraintDate===null&&t.primaryBaselineStart===null&&t.primaryBaselineFinish===null&&(t.resourceAssignments?.length??0)===0}function Sn(t,e){return t?.getTime()===e}function bc(t,e){let n=t.primaryBaselineStart!==null,i=t.primaryBaselineFinish!==null;if(n!==i)return null;let r=t.primaryBaselineStart??t.plannedStart,a=t.primaryBaselineFinish??t.plannedFinish;if(r===null||a===null)return null;if(r.getTime()===a.getTime())return e.dataDate.getTime()<r.getTime()?Fr:Wi;if(e.dataDate.getTime()<=r.getTime())return Fr;if(e.dataDate.getTime()>=a.getTime())return Wi;let o=Vi(e.calendar,r,a);if(o<=0)return Fr;let s=Vi(e.calendar,r,e.dataDate);return Nm(s/o*Lc)}function TP(t,e,n){if(t.remainingEarlyFinish===null||t.lateFinish===null)return null;let i=Vi(e,t.remainingEarlyFinish,t.lateFinish);if(n==="finish_float")return Object.is(i,-0)?0:i;if(t.remainingEarlyStart===null||t.lateStart===null)return null;let r=Vi(e,t.remainingEarlyStart,t.lateStart),a=n==="start_float"?r:Math.min(r,i);return Object.is(a,-0)?0:a}function _P(t,e,n){return e===null||n===null?0:Vi(t,e,n)}function Vi(t,e,n){if(e.getTime()<=n.getTime())return t.calculateDuration(e,n);let i=-t.calculateDuration(n,e);return Object.is(i,-0)?0:i}function Nm(t){return Math.min(Wi,Math.max(Fr,t))}function Xo(t,e){return{freeSlackHours:t.freeFloatHours,criticalPath:{earlyStart:v(t.earlyStart),earlyFinish:v(t.earlyFinish),lateStart:v(t.lateStart),lateFinish:v(t.lateFinish),totalSlackHours:t.remainingFloatHours},isCritical:e.criticalActivityMethod===fr.LONGEST_PATH?t.longestPath:t.remainingFloatHours!==null&&t.remainingFloatHours<=e.criticalFloatThresholdHours}}function Fm(t){let e=new Set(t.criticalPath);return new Map([...t.activities].map(([n,i])=>{let r=i.actualStart??i.remainingEarlyStart,a=i.actualFinish??i.remainingEarlyFinish;return[n,{p6:v(i),...r===null?{}:{startDate:v(r)},...a===null?{}:{endDate:v(a)},isCritical:e.has(n),freeSlackHours:i.freeFloatHours,criticalPath:{earlyStart:v(i.earlyStart),earlyFinish:v(i.earlyFinish),lateStart:v(i.lateStart),lateFinish:v(i.lateFinish),totalSlackHours:i.remainingFloatHours}}]}))}function wm(t,e,n){if(!PP(e.dataDate,n.dataDate))return new Map;if(!lt(n))return new Map;let i=!lt(e),r=new Map;for(let a of t.getAllActivities()){let o=a.p6;if(o===void 0)continue;let s=t.calendarReader.getCalendar(a.calendarId);if(s===null)throw new Error(`Missing calendar for Data Date activity ${a.id}`);let l=EP(o,n.dataDate,s),c=!Object.is(l.schedulePercentComplete,o.schedulePercentComplete)||!Object.is(l.actualDurationHours,o.actualDurationHours);!i&&!c||r.set(a.id,{...c?{p6:l}:{},...i?Xo(l,n):{}})}return r}function xm(t,e){for(let[n,i]of e)t.setActivityFields(n,i)}function EP(t,e,n){let i={dataDate:e,calendar:n},r=bc(t,i),a=un(t)&&t.executionStatus===et.IN_PROGRESS;return{...t,schedulePercentComplete:r,...a?{actualDurationHours:Om(t,i)}:{}}}function PP(t,e){return t?.getTime()!==e?.getTime()}var RP=["remainingDurationHours","originalDurationHours","actualStart","actualFinish","suspendDate","resumeDate"];function Qo(t,e,n){if(!kP(t,e))return{p6:{...e}};if(!un(e))return{p6:{...e},...Mm(t,e),...Um(t,e,null)};let i=LP(e,n.calendar),r=wr(i===null?e:{...e,remainingEarlyFinish:i},{dataDate:n.dataDate,calendar:n.calendar,...n.totalFloatMethod===void 0?{}:{totalFloatMethod:n.totalFloatMethod}});return{p6:{...e,...r,remainingFloatHours:e.remainingFloatHours},...Mm(t,e),...Um(t,e,i)}}function kP(t,e){return RP.some(n=>!Zo(t[n],e[n]))}function LP(t,e){return t.executionStatus==="completed"||t.remainingEarlyStart===null?null:e.calculateEndDate(t.remainingEarlyStart,t.remainingDurationHours)}function Mm(t,e){if(Zo(t.actualStart,e.actualStart))return{};let n=e.actualStart??e.remainingEarlyStart;return n===null?{}:{startDate:v(n)}}function Um(t,e,n){if(!(!Zo(t.remainingDurationHours,e.remainingDurationHours)||!Zo(t.actualFinish,e.actualFinish)))return{};let r=e.actualFinish??n??e.remainingEarlyFinish;return r===null?{}:{endDate:v(r)}}function Zo(t,e){return t instanceof Date||e instanceof Date?t instanceof Date&&e instanceof Date&&t.getTime()===e.getTime():Object.is(t,e)}var ce=class extends Error{constructor(n,i,r=[],a=0,o=[]){super(i);this.code=n;this.relationshipIds=r;this.count=a;this.sampleActivityIds=o;this.name="P6CapabilityError"}code;relationshipIds;count;sampleActivityIds};function Hm(t){return Object.freeze({getSettings:t.getSettings,getProjectState:t.getProjectState,getLatestRunLog:t.getLatestRunLog,getScheduleStateFingerprint:t.getScheduleStateFingerprint,getDefaultSettings:t.getDefaultSettings,getScheduleReadiness:t.getScheduleReadiness,searchEndingActivities:t.searchEndingActivities,getEndingActivityOption:t.getEndingActivityOption,resolveMustFinishByDefault:t.resolveMustFinishByDefault,updateSettings:t.updateSettings,updateActivity:t.updateActivity,schedule:t.schedule})}function ts(t){return t.outOfSequencePolicy!=="progress_override"||t.successorExecution!=="in_progress"?!0:t.linkType==="2"||t.linkType==="3"}function Be(t){return t.actualFinish!==null?{execution:"completed",hasRemaining:!1}:t.actualStart!==null?{execution:"in_progress",hasRemaining:!0}:{execution:"not_started",hasRemaining:!0}}function xr(t){return t.outOfSequencePolicy==="retained_logic"&&t.linkType==="1"&&t.actualStart!==null}function Fc(t,e,n){let i=jm(e);if(i.length===0)return null;let r=i.map(a=>{let o=Wm(e,a),s=t.getClosestWorkTime({date:n,dir:"future",task:o}),l=t.calculateEndDate({startDate:s,durationHours:Nc(a),task:o});return{start:s,finish:l}});return Vm(r)}function Bm(t,e,n){let i=jm(e);if(i.length===0)return null;let r=i.map(a=>{let o=Wm(e,a),s=t.getClosestWorkTime({date:n,dir:"past",task:o}),l=t.calculateEndDate({startDate:s,durationHours:-Nc(a),task:o}),c=t.calculateEndDate({startDate:l,durationHours:Nc(a),task:o});return{start:l,finish:c}});return Vm(r)}function jm(t){if(t.p6?.activityType!=="resource_dependent")return[];let e=t.p6.resourceAssignments??[];for(let n of e)OP(n);return e}function OP(t){for(let e of[t.actualUnits,t.remainingUnits,t.unitsPerHour])if(!Number.isFinite(e)||e<0)throw new Error(`Invalid P6 resource assignment ${t.id}`);if(t.remainingUnits>0&&t.unitsPerHour<=0)throw new Error(`Invalid P6 resource assignment rate ${t.id}`)}function Nc(t){let e=t.remainingUnits===0?0:t.remainingUnits/t.unitsPerHour;return bP(e)}function bP(t){let e=Math.round(t),n=Number.EPSILON*Math.max(1,Math.abs(t))*32;return Math.abs(t-e)<=n?e:t}function Wm(t,e){return{...t,calendarId:e.calendarId}}function Vm(t){let e=new Date(Math.min(...t.map(i=>i.start.getTime()))),n=new Date(Math.max(...t.map(i=>i.finish.getTime())));return{start:e,finish:n}}var NP=4;function es(t){let e=FP(t);if(e!==null)return e;let n=wP(t);if(n!==null)return n;let i=xP(t);if(i!==null)return i;let r=MP(t);if(r!==null)return r;if(t.link.type===H.START_TO_FINISH&&Xn(t.link)&&t.successor.p6?.activityType==="finish_milestone")return UP(t);let a=Ia(t.predecessor,t.successor,t.link,t.adapter,t.lagTask).successorStart;return!WP(t)||a.getTime()===t.predecessor.endDate.getTime()?a:t.adapter.getClosestWorkTime({date:t.predecessor.endDate,dir:"future",task:t.successor})}function FP(t){let e=t.link._trueLag??t.link.lag??0;if(t.link.type!==H.FINISH_TO_FINISH||!Xn(t.link)||t.successor.durationHours===0||t.lagTask!==null||e<=0)return null;let n=Qe(t.predecessor.endDate,e);return t.adapter.calculateEndDate({startDate:n,durationHours:-t.successor.durationHours,task:t.successor})}function wP(t){let e=t.link._trueLag??t.link.lag??0;return t.link.type!==H.START_TO_START||!Xn(t.link)||t.successor.p6?.activityType!=="finish_milestone"||t.successor.durationHours!==0||t.lagTask!==null||e===0?null:t.adapter.getClosestWorkTime({date:Qe(t.predecessor.startDate,e),dir:"future",task:t.successor})}function xP(t){let e=(t.link._trueLag??t.link.lag??0)===0;if(t.link.type!==H.FINISH_TO_START||t.predecessor.p6?.activityType!=="resource_dependent"||t.successor.p6?.activityType!=="level_of_effort"||t.successor.durationHours!==0||!e)return null;let n=ir(t.predecessor.endDate),i=t.adapter.getClosestWorkTime({date:n,dir:"future",task:t.successor});return i.getTime()===n.getTime()?t.predecessor.endDate:i}function MP(t){let e=t.link._trueLag??t.link.lag??0;return!(t.link.type===H.FINISH_TO_START||t.link.type===H.FINISH_TO_FINISH)||!Xn(t.link)||t.successor.p6?.activityType!=="finish_milestone"||e>=0||t.lagTask!==null?null:t.adapter.getClosestWorkTime({date:Qe(t.predecessor.endDate,e),dir:"future",task:t.successor})}function UP(t){let e=t.link._trueLag??t.link.lag??0,n=t.lagTask===null?Qe(t.predecessor.startDate,e):t.adapter.calculateEndDate({startDate:t.predecessor.startDate,durationHours:e,task:t.lagTask});return t.adapter.getClosestWorkTime({date:n,dir:"future",task:t.successor})}function Mr(t){let e=HP(t);if(e!==null)return e;let n=BP(t);if(n!==null)return n;let i=t.link.type===H.FINISH_TO_FINISH&&Xn(t.link)&&t.lagTask!==null&&t.lagTask.id!==t.successor.id?jP(t):Sa(t.successor,t.predecessor,t.link,t.adapter,t.lagTask);return VP(t)?KP(i,t.lagTask,t.adapter):i}function HP(t){let e=t.link._trueLag??t.link.lag??0;if(t.link.type!==H.START_TO_FINISH||!Xn(t.link)||t.lagTask!==null||e<=0)return null;let n=Qe(t.successor.endDate,-e);return t.adapter.calculateEndDate({startDate:n,durationHours:t.predecessor.durationHours,task:t.predecessor})}function BP(t){let e=t.link._trueLag??t.link.lag??0,n=t.adapter.isWorkTime?.({date:t.successor.startDate,task:t.predecessor});return t.link.type!==H.FINISH_TO_START||!Xn(t.link)||t.predecessor.p6?.activityType!=="finish_milestone"||e!==0||t.lagTask!==null||n!==!1?null:t.adapter.getClosestWorkTime({date:t.successor.startDate,dir:"past",task:t.predecessor})}function Xn(t){return t._sourceLag===void 0&&t._targetLag===void 0}function jP(t){let e=t.link._trueLag??t.link.lag??0;if(t.lagTask===null)return Qe(t.successor.endDate,-e);let n=t.adapter.getClosestWorkTime({date:t.successor.endDate,dir:"past",task:t.lagTask});return t.adapter.calculateEndDate({startDate:n,durationHours:-e,task:t.lagTask})}function WP(t){let e=t.link.type===H.FINISH_TO_START||t.link.type===H.FINISH_TO_FINISH,n=(t.link.lag??0)===0&&(t.link._sourceLag??0)===0&&(t.link._targetLag??0)===0;return t.successor.durationHours===0&&e&&n}function VP(t){return t.link.type===H.FINISH_TO_FINISH&&(t.link._trueLag??t.link.lag??0)>0&&t.lagTask!==null}function KP(t,e,n){if(e===null)return t;let i=ir(t),r=n.getClosestWorkTime({date:i,dir:"future",task:e}),a=Vd(i,r);return r.getTime()>i.getTime()&&a<=NP?r:t}function Ym(t){let e=eR(t.links),n={...t,projectEarlyFinish:XP(t.activities)};for(let i of[...t.orderedIds].reverse())YP(i,e.get(i)??[],n)}function YP(t,e,n){let i=n.adapter.getActivity(t),r=n.activities.get(t);if(!QP(i)||r===void 0)return;let a=tR(i,r),o=JP(a,e,n);if(!qP(r,o))return;let s=zP(a,o,n.adapter),l={...r,...s};n.activities.set(t,l),GP(a,l,e,n)}function GP(t,e,n,i){let r=Km(t,e);for(let a of n){let o=i.adapter.getActivity(a.target),s=i.activities.get(a.target);if(o?.p6?.activityType!=="level_of_effort"||!s)continue;let l=Km(o,s),c=es({predecessor:r,successor:l,link:a,adapter:i.adapter,lagTask:i.resolveLagTask(r,l)});s.earlyStart!==null&&c<=s.earlyStart||i.activities.set(a.target,$P(s,l,c,i.adapter))}}function $P(t,e,n,i){let r=i.calculateEndDate({startDate:n,durationHours:t.scheduledRemainingDurationHours,task:e});return{...t,remainingEarlyStart:n,remainingEarlyFinish:r,earlyStart:new Date(n),earlyFinish:new Date(r)}}function Km(t,e){return{...t,startDate:e.remainingEarlyStart??e.earlyStart??t.startDate,endDate:e.remainingEarlyFinish??e.earlyFinish??t.endDate,durationHours:e.scheduledRemainingDurationHours}}function qP(t,e){return e!==null&&t.remainingEarlyFinish!==null&&e>t.remainingEarlyFinish}function zP(t,e,n){let i=n.calculateEndDate({startDate:e,durationHours:-t.durationHours,task:t}),r=n.calculateEndDate({startDate:i,durationHours:t.durationHours,task:t});return{remainingEarlyStart:i,remainingEarlyFinish:r,earlyStart:new Date(i),earlyFinish:new Date(r)}}function JP(t,e,n){let i=null;for(let r of e){let a=ZP(r.target,n);if(a===null)continue;let o=Mr({successor:a,predecessor:t,link:r,adapter:n.adapter,lagTask:n.resolveLagTask(t,a)});(i===null||o<i)&&(i=o)}return i??n.projectEarlyFinish}function XP(t){let e=null;for(let n of t.values()){let i=n.remainingEarlyFinish??n.earlyFinish;i!==null&&(e===null||i>e)&&(e=i)}return e}function ZP(t,e){let n=e.adapter.getActivity(t),i=e.activities.get(t);if(n?.p6===void 0||n.p6.activityType==="level_of_effort"||i===void 0)return null;let r=i.remainingEarlyStart??i.earlyStart,a=i.remainingEarlyFinish??i.earlyFinish;return r===null||a===null?null:{...n,startDate:r,endDate:a,durationHours:i.scheduledRemainingDurationHours}}function QP(t){return t?.p6?.executionStatus==="not_started"&&t.p6.primaryConstraintType==="alap"}function tR(t,e){return{...t,durationHours:e.scheduledRemainingDurationHours}}function eR(t){let e=new Map;for(let n of t){let i=e.get(n.source)??[];i.push(n),e.set(n.source,i)}return e}var vn="CS_MSO",wc="CS_MEO";function je(t){return t?.p6?.primaryConstraintType==="mandatory_start"&&t.p6.sourcePrimaryConstraintToken!==vn}function We(t){return t?.p6?.primaryConstraintType==="mandatory_finish"&&t.p6.sourcePrimaryConstraintToken!==wc}var nR=60*1e3,iR=3600*1e3,rR=64;function Jm(t){let{adapter:e,settings:n}=t;if(n.dataDate===null)throw new Error("P6 forward pass requires Data Date");let i=e.getAllActivities().filter(p=>p.p6!==void 0&&p.p6.activityType!=="wbs_summary").map(p=>p.id),r=new Set(i),a=e.getAllLinks().filter(p=>r.has(p.source)&&r.has(p.target)).filter(p=>{let f=e.getActivity(p.source),y=e.getActivity(p.target);return n.outOfSequencePolicy!=="progress_override"&&aR(f)?!1:y?.p6!==void 0&&ts({outOfSequencePolicy:n.outOfSequencePolicy,successorExecution:Be(y.p6).execution,linkType:p.type})}),o=a.filter(p=>{let f=e.getActivity(p.target);return f?.p6!==void 0&&Be(f.p6).execution!=="completed"}),s=De(i,o);if(s.hasCycles)return{activities:new Map,cycles:s.cycleNodes};let l=hR(a),c=Mc(n,e),d=new Map,u=new Set;for(let p of s.ordered){let f=e.getActivity(p);if(f?.p6===void 0)continue;let y=Be(f.p6);if(y.execution==="completed"){let j=n.outOfSequencePolicy==="actual_dates";j&&u.add(p);let z=n.outOfSequencePolicy==="retained_logic"&&f.p6.activityType!=="level_of_effort"?new Date(n.dataDate):null,ft=j?f.p6.actualStart:z,st=j?f.p6.actualFinish:z;d.set(p,{activityId:p,scheduledRemainingDurationHours:0,remainingEarlyStart:null,remainingEarlyFinish:null,earlyStart:zm(ft),earlyFinish:zm(st),drivingLinkId:null});continue}let m=[...l.get(p)??[]].sort((j,z)=>j.source.localeCompare(z.source)||j.id.localeCompare(z.id)),h=mR(f),A=Gm({successor:h,incomingLinks:m,activities:d,settings:n,adapter:e,resolveLagTask:c}),T=qm({activity:h,earliestStart:A.earliestStart,settings:n,adapter:e}),b=0;for(;!Object.is(h.durationHours,T)&&b<rR;)h={...h,durationHours:T},A=Gm({successor:h,incomingLinks:m,activities:d,settings:n,adapter:e,resolveLagTask:c}),T=qm({activity:h,earliestStart:A.earliestStart,settings:n,adapter:e}),b+=1;if(!Object.is(h.durationHours,T))throw new Error(`P6_EXPECTED_FINISH_DID_NOT_SETTLE: ${String(p)}`);let{earliestStart:S,drivingLinkId:g,drivingLinkIds:w}=A,R=Fc(e,h,S),L=y.execution==="in_progress"?{earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null}:pR(h,e),P=lR({activity:h,bounds:L,settings:n,adapter:e}),O={activityId:p,startDate:R?.start??S,endDate:R?.finish??e.calculateEndDate({startDate:S,durationHours:T,task:h}),drivingLinkId:g,kind:"asap",conflict:!1,earliestStart:P.earliestStart,latestStart:P.latestStart,earliestEnd:P.earliestEnd,latestEnd:P.latestEnd,earliestSchedulingStart:R?.start??S};if(ui(h,O,e),R!==null){let j=Fc(e,h,O.startDate);j!==null&&(O.startDate=j.start,O.endDate=j.finish)}let M=O.startDate.getTime()===S.getTime();d.set(p,{activityId:p,scheduledRemainingDurationHours:T,remainingEarlyStart:new Date(O.startDate),remainingEarlyFinish:new Date(O.endDate),earlyStart:new Date(O.startDate),earlyFinish:new Date(O.endDate),drivingLinkId:M?g:null,drivingLinkIds:M?w:[]})}Ym({adapter:e,orderedIds:s.ordered,links:a,activities:d,resolveLagTask:c});for(let p of u){let f=d.get(p);d.set(p,{...f,earlyStart:null,earlyFinish:null})}return{activities:d,cycles:[]}}function aR(t){return t?.p6?.activityType==="level_of_effort"&&t.p6.executionStatus==="not_started"&&t.p6.remainingDurationHours===0}function Gm(t){let{successor:e,incomingLinks:n,activities:i,settings:r,adapter:a,resolveLagTask:o}=t,s=a.getClosestWorkTime({date:new Date(r.dataDate),dir:"future",task:e}),l=e.p6?.resumeDate??null;l!==null&&l.getTime()>s.getTime()&&(s=a.getClosestWorkTime({date:new Date(l),dir:"future",task:e}));let c=null,d=[];for(let u of n){let p=a.getActivity(u.source),f=i.get(u.source);if(p?.p6===void 0||f===void 0)continue;let y=f.remainingEarlyStart??f.earlyStart,m=f.remainingEarlyFinish??f.earlyFinish;if(y===null||m===null)continue;let h=oR({link:u,predecessor:p,predecessorDates:f,successor:e,settings:r}),A=gR(u,p,f,r),T={...p,startDate:A,endDate:m,durationHours:a.calculateDuration({startDate:A,endDate:m,task:p})},b=h??es({predecessor:T,successor:e,link:u,adapter:a,lagTask:o(T,e)}),S=u.type==="0"&&e.durationHours===0&&e.type!=="milestone"?sR(e,b,a):b;S>s?(s=S,c=u.id,d=[u.id]):d.length>0&&S.getTime()===s.getTime()&&d.push(u.id)}return{earliestStart:s,drivingLinkId:c,drivingLinkIds:d}}function Xm(t){return t.p6?.activityType==="task"&&t.p6.executionStatus==="not_started"&&t.p6.originalDurationHours===0}function oR(t){let e=t.settings.outOfSequencePolicy==="retained_logic"&&t.settings.startToStartLagBasis==="early_start"&&t.link.type==="1"&&t.predecessor.p6?.executionStatus==="in_progress"&&t.predecessor.p6?.actualStart!==null&&Xm(t.successor),n=t.predecessorDates.remainingEarlyStart??t.predecessorDates.earlyStart;return e&&n!==null?new Date(n):null}function sR(t,e,n){if(t.p6?.activityType==="level_of_effort")return e;let i=ir(e),r=n.getClosestWorkTime({date:i,dir:"future",task:t});if(!Xm(t))return r;let a=new Date(e.getTime()+nR);if(n.isWorkTime?.({date:a,task:t}))return e;if(n.isWorkTime===void 0)return r.getTime()===i.getTime()?e:r;let o=new Date(e.getTime()+iR);return n.getClosestWorkTime({date:o,dir:"future",task:t})}function lR(t){let{activity:e,bounds:n,settings:i,adapter:r}=t,a=je(e);if(cR(t,a)){let s=dR(t,a);return{...n,earliestStart:s,latestStart:s}}let o=We(e);if(uR(t,o)){let s=i.dataDate;if(s===null)return n;let l=o?r.getClosestWorkTime({date:s,dir:"future",task:e}):s;return{...n,earliestStart:l,latestStart:l,latestEnd:null}}return e.constraintType==="mfo"?n:{...n,latestStart:null,latestEnd:null}}function cR(t,e){let{activity:n,bounds:i,settings:r}=t;return n.p6?.executionStatus!=="not_started"?!1:e?!0:n.constraintType!=="mso"?!1:r.outOfSequencePolicy!=="retained_logic"?!0:i.earliestStart!==null&&r.dataDate!==null&&i.earliestStart>=r.dataDate}function dR(t,e){let{activity:n,bounds:i,settings:r,adapter:a}=t,o=xc(i.earliestStart,r.dataDate);return!e||o===null?r.outOfSequencePolicy==="retained_logic"?i.earliestStart:o:a.getClosestWorkTime({date:o,dir:"future",task:n})}function uR(t,e){let{activity:n,bounds:i,settings:r}=t;return n.p6?.executionStatus!=="not_started"||i.latestStart===null||r.dataDate===null||i.latestStart>=r.dataDate?!1:e||n.constraintType==="mfo"&&r.outOfSequencePolicy==="actual_dates"}function pR(t,e){let n=fR(t,e),i=t.p6?.secondaryConstraintType??null,r=t.p6?.secondaryConstraintDate??null;if(i===null||r===null)return n;let a=$e({...t,constraintType:i,constraintDate:r},e);return yR(n,a)}function fR(t,e){let n=t.p6?.primaryConstraintType,i=t.p6?.primaryConstraintDate;return n==null||i===null||i===void 0?$e(t,e):$e({...t,constraintType:Va(n),constraintDate:i},e)}function yR(t,e){return{earliestStart:xc(t.earliestStart,e.earliestStart),latestStart:$m(t.latestStart,e.latestStart),earliestEnd:xc(t.earliestEnd,e.earliestEnd),latestEnd:$m(t.latestEnd,e.latestEnd)}}function xc(t,e){return t===null?e:e===null||t>e?t:e}function $m(t,e){return t===null?e:e===null||t<e?t:e}function qm(t){let{activity:e,earliestStart:n,settings:i,adapter:r}=t,a=e.p6?.expectedFinish??null;return!i.useExpectedFinishDates||a===null||e.p6===void 0?e.p6?.remainingDurationHours??e.durationHours:a<=n?0:r.calculateDuration({startDate:n,endDate:a,task:e})}function Mc(t,e){let n=null,i=()=>{if(n??=e.getAllActivities().find(r=>r.type==="project")??null,n===null)throw new Error("P6 schedule requires a project activity for Project Default relationship lag calendar");return n};switch(t.relationshipLagCalendar){case"predecessor":return r=>r;case"successor":return(r,a)=>a;case"project_default":return()=>i();case"twenty_four_hour":return()=>null}}function hR(t){let e=new Map;for(let n of t){let i=e.get(n.target)??[];i.push(n),e.set(n.target,i)}return e}function mR(t){return t.p6===void 0?t:{...t,durationHours:t.p6.remainingDurationHours}}function gR(t,e,n,i){return!(t.type==="1"||t.type==="3")||e.p6===void 0?new Date(n.remainingEarlyStart??n.earlyStart??e.startDate):(i.outOfSequencePolicy==="actual_dates"||xr({outOfSequencePolicy:i.outOfSequencePolicy,linkType:t.type,actualStart:e.p6.actualStart})||i.startToStartLagBasis==="actual_start")&&e.p6.actualStart!==null?new Date(e.p6.actualStart):new Date(n.earlyStart??n.remainingEarlyStart??e.startDate)}function zm(t){return t===null?null:new Date(t)}function AR(t,e){let n=t==="start_float"?e.startFloatHours:t==="finish_float"?e.finishFloatHours:Math.min(e.startFloatHours,e.finishFloatHours);return Object.is(n,-0)?0:n}function eg(t){let{adapter:e,settings:n,forward:i}=t,r=[...i.activities.keys()],a=new Set(r),o=e.getAllLinks().filter(A=>a.has(A.source)&&a.has(A.target)),s=o.filter(A=>{let T=e.getActivity(A.source),b=e.getActivity(A.target);return n.outOfSequencePolicy!=="progress_override"&&IR(b)||SR(A,T,b)?!1:b?.p6!==void 0&&ts({outOfSequencePolicy:n.outOfSequencePolicy,successorExecution:Be(b.p6).execution,linkType:A.type})}),l=s.filter(A=>{let T=e.getActivity(A.source);return!(T?.p6?.activityType==="level_of_effort"&&Be(T.p6).execution==="completed")}),c=De(r,l);if(c.hasCycles)throw new Error(`P6 backward pass cannot calculate cycles: ${c.cycleNodes.join(", ")}`);let d=LR(e,i,r),u=n.projectMustFinishBy??d;if(u===null)return{activities:TR(r)};let p=d??u,f=Zm(s),y=Zm(o),m=Mc(n,e),h=new Map;for(let A of c.reversed){let T=e.getActivity(A),b=i.activities.get(A);if(T?.p6===void 0||b===void 0)continue;let S=OR(T,b.scheduledRemainingDurationHours??T.p6.remainingDurationHours),g=new Date(u);for(let st of f.get(A)??[]){let Nt=e.getActivity(st.target),kt=h.get(st.target),Ce=i.activities.get(st.target);if(Nt?.p6===void 0||kt===void 0)continue;let Le=kR(Nt,kt,n,st.type);if(Le===null)continue;let It={...Nt,startDate:Le.startDate,endDate:Le.endDate,durationHours:Ce?.scheduledRemainingDurationHours??Nt.p6.remainingDurationHours},Ye=xr({outOfSequencePolicy:n.outOfSequencePolicy,linkType:st.type,actualStart:T.p6.actualStart})||ng(T,st,n)?{...st,lag:0}:st,Vr=n.outOfSequencePolicy==="actual_dates"&&st.type==="0"&&Nt.p6.executionStatus==="in_progress"&&Nt.p6.primaryConstraintType==="mandatory_start"&&Nt.p6.sourcePrimaryConstraintToken!==vn,Kr=Mr({successor:It,predecessor:S,link:Ye,adapter:e,lagTask:Vr?It:m(S,It)});Kr<g&&(g=Kr)}if(b.remainingEarlyStart===null||b.remainingEarlyFinish===null){if(n.outOfSequencePolicy!=="retained_logic"||T.p6.activityType==="level_of_effort"){h.set(A,{activityId:A,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,totalFloatHours:null,freeFloatHours:null,isCritical:!1});continue}h.set(A,{activityId:A,remainingLateStart:null,remainingLateFinish:null,lateStart:new Date(g),lateFinish:new Date(g),totalFloatHours:null,freeFloatHours:null,isCritical:!1});continue}g=bR(S,g,e),S.durationHours===0&&T.p6.activityType!=="level_of_effort"&&ig(T,f.get(A)??[],e,g)&&(g=e.getClosestWorkTime({date:di(g),dir:"past",task:S}));let w=(y.get(A)??[]).length===0,R=DR(n,T,w),L=Bm(e,S,g),P=L?.start??e.calculateEndDate({startDate:g,durationHours:-S.durationHours,task:S});if(T.p6.activityType==="level_of_effort")P=RR(e,g,S,f.get(A)??[]),S.durationHours===0&&(g=new Date(P));else if(L!==null)g=L.finish;else{let st=n.outOfSequencePolicy==="actual_dates"&&CR(f.get(A)??[],e)||T.p6.secondaryConstraintType==="fnlt";P=vR(T,P,st),g=e.calculateEndDate({startDate:P,durationHours:S.durationHours,task:S})}R&&(P=new Date(b.remainingEarlyStart),g=new Date(b.remainingEarlyFinish));let O=Hc(e,b.remainingEarlyStart,P,S),M=Hc(e,b.remainingEarlyFinish,g,S),j=AR(n.totalFloatMethod,{startFloatHours:O,finishFloatHours:M}),z=_R({activity:T,effectivePredecessor:S,early:b,outgoingLinks:f.get(A)??[],boundary:p,forward:i,settings:n,adapter:e,resolveLagTask:m}),ft=n.criticalActivityMethod==="total_float"&&j<=n.criticalFloatThresholdHours||R;h.set(A,{activityId:A,remainingLateStart:new Date(P),remainingLateFinish:new Date(g),lateStart:new Date(P),lateFinish:new Date(g),totalFloatHours:j,freeFloatHours:z,isCritical:ft})}return{activities:h}}function IR(t){return t?.p6?.activityType==="level_of_effort"&&t.p6.executionStatus==="not_started"&&t.p6.remainingDurationHours===0}function Uc(t,e,n){return n.isWorkTime?.({date:di(e),task:t})===!1}function SR(t,e,n){return t.type==="0"&&t.lag===0?!1:e?.p6?.executionStatus==="completed"&&n?.p6?.executionStatus==="completed"}function vR(t,e,n){let i=t.p6;return n||i?.executionStatus!=="in_progress"||i.primaryConstraintType!=="snet"||i.actualStart===null||e>=i.actualStart?e:new Date(i.actualStart)}function CR(t,e){return t.some(n=>{let i=e.getActivity(n.target)?.p6;return i?.executionStatus==="in_progress"&&i.primaryConstraintType==="mandatory_start"&&i.sourcePrimaryConstraintToken!==vn})}function DR(t,e,n){return t.makeOpenEndedActivitiesCritical&&n&&e.type!=="milestone"&&t.multipleFloatPaths.endingActivityId!==e.id&&Be(e.p6).execution==="not_started"}function TR(t){return new Map(t.map(e=>[e,{activityId:e,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,totalFloatHours:null,freeFloatHours:null,isCritical:!1}]))}function _R(t){let{activity:e,effectivePredecessor:n,early:i,outgoingLinks:r,boundary:a,forward:o,settings:s,adapter:l,resolveLagTask:c}=t;if(i.remainingEarlyStart===null||i.remainingEarlyFinish===null)return null;if(e.p6?.executionStatus==="not_started"&&We(e)&&r.length>0||e.p6?.executionStatus==="not_started"&&je(e)&&ER(r,l))return 0;let d=null;for(let p of r){if(ng(e,p,s))continue;let f=l.getActivity(p.target),y=o.activities.get(p.target);if(f?.p6===void 0||y===void 0)continue;let m=PR({successor:f,early:y,settings:s,linkType:p.type});if(m===null)continue;let h={...f,startDate:m.startDate,endDate:m.endDate,durationHours:y.scheduledRemainingDurationHours},A=xr({outOfSequencePolicy:s.outOfSequencePolicy,linkType:p.type,actualStart:e.p6?.actualStart??null})?{...p,lag:0}:p,T=Mr({successor:h,predecessor:n,link:A,adapter:l,lagTask:c(n,h)});(d===null||T<d)&&(d=T)}d??=new Date(a),n.durationHours===0&&ig(e,r,l,d)&&(d=l.getClosestWorkTime({date:di(d),dir:"past",task:n}));let u=Hc(l,i.remainingEarlyFinish,d,n);return Math.max(0,Object.is(u,-0)?0:u)}function ER(t,e){return t.some(n=>{let i=e.getActivity(n.target)?.p6;return i?.activityType==="task"&&i.executionStatus==="not_started"&&i.originalDurationHours===0})}function ng(t,e,n){return n.outOfSequencePolicy==="progress_override"&&e.type==="1"&&t.p6?.actualStart!==null&&t.p6?.actualStart!==void 0}function PR(t){let{successor:e,early:n,settings:i,linkType:r}=t,a=n.remainingEarlyStart??n.earlyStart,o=n.remainingEarlyFinish??n.earlyFinish,s=e.p6;return i.outOfSequencePolicy==="actual_dates"&&s!==void 0&&(r==="0"||r==="1"||s.actualFinish!==null)&&(a=s.actualStart??a,o=s.actualFinish??o),a===null||o===null?null:{startDate:new Date(a),endDate:new Date(o)}}function ig(t,e,n,i){if(t.p6?.executionStatus==="completed")return!1;if(t.p6?.activityType==="task"&&t.p6.executionStatus==="not_started"&&t.p6.originalDurationHours===0){let o=di(i);return n.getClosestWorkTime({date:o,dir:"past",task:t})<o}if(t.p6?.activityType==="start_milestone"&&e.length===0)return Uc(t,i,n);if(e.length===0)return!1;if(t.type!=="milestone")return!0;let r=t.p6?.activityType;if(r!=="start_milestone"&&r!=="finish_milestone")return!1;let a=r==="finish_milestone";return e.every(o=>{let s=n.getActivity(o.target),c=s?.p6?.activityType==="resource_dependent"?s?.calendarId===t.calendarId:s?.calendarId!==t.calendarId&&Uc(t,i,n);return s?.p6!==void 0&&(!a||c)&&Be(s.p6).execution!=="completed"})}function RR(t,e,n,i){if(n.durationHours===0){let o=i.some(s=>{let l=t.getActivity(s.target);return l!==null&&l.calendarId!==n.calendarId})&&Uc(n,e,t)?di(e):e;return t.getClosestWorkTime({date:o,dir:"past",task:n})}let r=new Date(e);return r.setUTCHours(0,0,0,0),t.getClosestWorkTime({date:r,dir:"future",task:n})}function kR(t,e,n,i){if(t.p6===void 0)return null;let r=e.remainingLateStart??e.lateStart,a=e.remainingLateFinish??e.lateFinish;if(n.outOfSequencePolicy==="actual_dates"){let o=t.p6.actualStart,s=t.p6.actualFinish;if(i==="0"||i==="1"||s!==null){let l=o??r,c=s??a;return l===null||c===null?null:{startDate:new Date(l),endDate:new Date(c)}}}return r===null||a===null?null:n.outOfSequencePolicy==="actual_dates"?{startDate:new Date(r),endDate:new Date(a)}:{startDate:new Date(r),endDate:new Date(a)}}function LR(t,e,n){let i=n.filter(o=>t.getActivity(o)?.p6?.executionStatus!=="completed"),r=i.length>0?i:n,a=null;for(let o of r){let s=e.activities.get(o),l=s?.remainingEarlyFinish??s?.earlyFinish;l!=null&&(a===null||l>a)&&(a=l)}return a===null?null:new Date(a)}function Zm(t){let e=new Map;for(let n of t){let i=e.get(n.source)??[];i.push(n),e.set(n.source,i)}return e}function OR(t,e=t.p6?.remainingDurationHours??t.durationHours){return t.p6===void 0?t:{...t,durationHours:e}}function bR(t,e,n){let i=t.p6?.primaryConstraintType,r=t.p6?.primaryConstraintDate,a=t.p6?.sourcePrimaryConstraintToken,o=a===wc?"fnlt":a===vn?"snlt":i,l=i==="start_on"?{...t,constraintType:null,constraintDate:null}:o!=null&&r!==null&&r!==void 0?Qm(t,o,r,n):t,d=t.p6?.actualStart===null||o==="fnlt"||o==="finish_on"?tg(l,e,n):new Date(e);if(t.p6?.secondaryConstraintType===null||t.p6?.secondaryConstraintDate===null||t.p6===void 0||t.p6.actualStart!==null&&t.p6.secondaryConstraintType!=="fnlt")return d;let u=Qm(t,t.p6.secondaryConstraintType,t.p6.secondaryConstraintDate,n);return d=tg(u,d,n),new Date(d)}function Qm(t,e,n,i){let r=Va(e),a=NR({activity:t,constraintType:r,constraintDate:n,adapter:i});return{...t,constraintType:r,constraintDate:a}}function NR(t){let{activity:e,constraintType:n,constraintDate:i,adapter:r}=t,a=e.p6?.sourcePrimaryConstraintToken===vn&&n==="snlt"?"future":FR(n,i)?"past":null;return a===null?new Date(i):r.getClosestWorkTime({date:i,dir:a,task:e})}function FR(t,e){return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0&&e.getUTCMilliseconds()===0&&(t==="fnlt"||t==="mfo")}function tg(t,e,n){let i=$e(t,n);if((t.constraintType==="mso"||t.constraintType==="mfo")&&i.latestEnd!==null)return new Date(i.latestEnd);let r=e;if(i.latestEnd!==null&&i.latestEnd<r&&(r=i.latestEnd),i.latestStart!==null){let a=n.calculateEndDate({startDate:i.latestStart,durationHours:t.durationHours,task:t});a<r&&(r=a)}return t.constraintType==="snet"&&i.earliestEnd!==null&&i.earliestEnd<r&&(r=i.earliestEnd),new Date(r)}function Hc(t,e,n,i){return e<=n?t.calculateDuration({startDate:e,endDate:n,task:i}):-t.calculateDuration({startDate:n,endDate:e,task:i})}var wR=3600*1e3,rg=["P6_NO_PREDECESSOR","P6_NO_SUCCESSOR","P6_OUT_OF_SEQUENCE","P6_ACTUAL_AFTER_DATA_DATE","P6_INVALID_MILESTONE_RELATIONSHIP"],xR={P6_NO_PREDECESSOR:"open_ended",P6_NO_SUCCESSOR:"open_ended",P6_OUT_OF_SEQUENCE:"out_of_sequence",P6_ACTUAL_AFTER_DATA_DATE:"actual_after_data_date",P6_INVALID_MILESTONE_RELATIONSHIP:"milestone_relationship",P6_UNSATISFIED_CONSTRAINT:"unsatisfied_constraint"},MR={0:"finish_to_start",1:"start_to_start",2:"finish_to_finish",3:"start_to_finish"};function cg(t){let{adapter:e,dataDate:n,project:i,outOfSequencePolicy:r}=t;YR(r);let a=e.getAllActivities().filter(Bc).sort(pg),o=new Map;for(let s of rg)o.set(s,[]);for(let s of a){e.getIncomingLinkIds(s.id).length===0&&Ur(o,Ki(s,i,n,{code:"P6_NO_PREDECESSOR",rule:"activity_has_no_predecessor"})),e.getOutgoingLinkIds(s.id).length===0&&Ur(o,Ki(s,i,n,{code:"P6_NO_SUCCESSOR",rule:"activity_has_no_successor"})),HR(s,n)&&Ur(o,Ki(s,i,n,{code:"P6_ACTUAL_AFTER_DATA_DATE",rule:"actual_date_is_after_data_date"}));let l=BR(e,s);l!==null&&Ur(o,Ki(s,i,n,{code:"P6_INVALID_MILESTONE_RELATIONSHIP",rule:"milestone_endpoint_is_not_available",relationship:og(e,l)}))}for(let s of KR(e.getAllLinks())){if(!jR(e,s))continue;let l=e.getActivity(s.target);l===null||!Bc(l)||Ur(o,Ki(l,i,n,{code:"P6_OUT_OF_SEQUENCE",rule:"successor_progress_precedes_required_logic",relationship:og(e,s)}))}return rg.flatMap(s=>o.get(s)??[])}function dg(t){let e=[],n=t.adapter.getAllActivities().filter(Bc).sort(pg);for(let i of n){let r=t.calculated.get(i.id);r===void 0||r.actualFinish!==null||UR(i,r)&&e.push(Ki({...i,p6:r},t.project,t.dataDate,{code:"P6_UNSATISFIED_CONSTRAINT",rule:"constraint_could_not_be_satisfied"}))}return e}function UR(t,e){let n=t.constraintDate??null,i=t.constraintType??null;if(n===null||i===null)return!1;let r=n.getTime(),a=e.remainingEarlyStart??e.earlyStart,o=e.remainingEarlyFinish??e.earlyFinish;switch(i){case D.MSO:return a!==null&&a.getTime()!==r;case D.MFO:return o!==null&&o.getTime()!==r;case D.SNET:return a!==null&&a.getTime()<r;case D.FNET:return o!==null&&o.getTime()<r;case D.SNLT:return a!==null&&a.getTime()>r;case D.FNLT:return o!==null&&o.getTime()>r;default:return!1}}function Ki(t,e,n,i){return{kind:"diagnostic",code:i.code,category:xR[i.code],severity:"warning",project:{...e},activityId:t.id,activityCode:t.customId??t.id,activityName:t.name,activityStatus:t.p6.executionStatus,dataDate:new Date(n),dates:{actualStart:lg(t.p6.actualStart),actualFinish:lg(t.p6.actualFinish)},relationship:i.relationship??null,explanation:{rule:i.rule}}}function Ur(t,e){t.get(e.code).push(e)}function HR(t,e){let n=t.p6;return n!==void 0&&(sg(n.actualStart,e)||sg(n.actualFinish,e))}function BR(t,e){return e.p6?.activityType==="start_milestone"?ag(t,e,"incoming",n=>n.type==="2"||n.type==="3"):e.p6?.activityType==="finish_milestone"?ag(t,e,"outgoing",n=>n.type==="1"||n.type==="3"):null}function ag(t,e,n,i){return(n==="incoming"?t.getIncomingLinkIds(e.id):t.getOutgoingLinkIds(e.id)).map(a=>t.getLink(a)).filter(a=>a!==null).sort(ug).find(i)??null}function jR(t,e){let n=t.getActivity(e.source),i=t.getActivity(e.target);if(n?.p6===void 0||i?.p6===void 0)return!1;let r=VR(i,e.type);if(r===null)return!1;let a=WR(n,e.type);return a===null?!0:r.getTime()<a.getTime()+e.lag*wR}function WR(t,e){return t.p6===void 0?null:e==="1"||e==="3"?t.p6.actualStart:t.p6.actualFinish}function VR(t,e){return t.p6===void 0?null:e==="0"||e==="1"?t.p6.actualStart:t.p6.actualFinish}function og(t,e){let n=t.getActivity(e.source),i=t.getActivity(e.target);return{id:e.id,predecessorActivityId:e.source,predecessorActivityCode:n===null?null:n.customId??n.id,successorActivityId:e.target,successorActivityCode:i===null?null:i.customId??i.id,type:MR[e.type],lagHours:e.lag}}function KR(t){return[...t].sort(ug)}function ug(t,e){return String(t.id).localeCompare(String(e.id))}function pg(t,e){let n=t.correlativeId-e.correlativeId;return n!==0?n:(t.customId??String(t.id)).localeCompare(e.customId??String(e.id))}function sg(t,e){return t!==null&&t.getTime()>e.getTime()}function lg(t){return t===null?null:new Date(t)}function Bc(t){return t.p6!==void 0}function YR(t){if(t!=="retained_logic"&&t!=="progress_override"&&t!=="actual_dates")throw new Error(`Unsupported P6 out-of-sequence policy: ${String(t)}`)}function Zn(t){let e=null;for(let n of t){if(n===null)continue;let i=n.getTime();(e===null||i<e)&&(e=i)}return e===null?null:new Date(e)}function Cn(t){let e=null;for(let n of t){if(n===null)continue;let i=n.getTime();(e===null||i>e)&&(e=i)}return e===null?null:new Date(e)}function jc(t){let e=null;for(let n of t)n!==null&&(e===null||n<e)&&(e=n);return e}function Hr(t){let e=0;for(let n of t)e+=n;return e}function yg(t){let{adapter:e,settings:n,forward:i,backward:r}=t,a=new Map;for(let u of r.activities.keys())a.set(u,{longestPath:!1,floatPath:null,floatPathOrder:null});let o=sk(i);for(let u of o)ck(u,e,i,a,n);if(!n.multipleFloatPaths.enabled)return{activities:a};let s=lk(n,i,o);if(s===null)return{activities:a};let l=n.multipleFloatPaths.limitEnabled?n.multipleFloatPaths.maximum:Number.POSITIVE_INFINITY,c={emittedPaths:0,numberingBudget:n.multipleFloatPaths.limitEnabled?n.multipleFloatPaths.maximum:Number.POSITIVE_INFINITY,numberableActivityIds:nk(e,i,n),activities:a},d=qR({adapter:e,backward:r,settings:n,endingActivityId:s,state:c});if(!d&&n.multipleFloatPaths.useTotalFloat)pk(s,e,i,r,n,l,c);else if(!d){let u=mk(s,e,i,n);is(n)&&(Yi(u[0]??[],c),GR({adapter:e,backward:r,settings:n,state:c}));let p=is(n)?u.slice(1):u;for(let f of p)Yi(f,c)}return n.multipleFloatPaths.limitEnabled&&!d&&(n.multipleFloatPaths.useTotalFloat?Sk(e,i,r,n,c):gk(e,i,n,c)),d||Ck(n,r,c.activities,e),{activities:a}}function GR(t){let{adapter:e,backward:n,settings:i,state:r}=t,a=[...r.numberableActivityIds].filter(o=>$R(e.getActivity(o))).sort((o,s)=>{let l=n.activities.get(o)?.freeFloatHours??1/0,c=n.activities.get(s)?.freeFloatHours??1/0;return l-c||Vc(o,s,e,i)});for(let o of a)Yi([o],r)}function $R(t){if(t?.p6?.executionStatus!=="in_progress")return!1;let e=t.p6.primaryConstraintType;return e==="alap"||e==="mandatory_start"||e==="start_on"||e==="snet"||e==="snlt"}function qR(t){if(!JR(t.settings))return!1;let e=XR(t.adapter,t.state);if(e===null||e.length===0||e.length!==t.state.numberingBudget||e.some((i,r)=>i[0].path!==r+1))return!1;let n=tk(t.endingActivityId,t.adapter);if(e.some(i=>!ZR(i,t,n))||zR(e,t))return!1;for(let i of e)ek(i,t.state);return!0}function zR(t,e){if(!e.settings.multipleFloatPaths.useTotalFloat)return[...e.state.numberableActivityIds].some(r=>!hg(r,e));let n=new Set(t.flat().map(r=>r.id)),i=Math.max(...t.map(r=>Math.min(...r.map(a=>e.backward.activities.get(a.id)?.totalFloatHours??1/0))));return[...e.state.numberableActivityIds].some(r=>{if(n.has(r))return!1;let a=e.backward.activities.get(r)?.totalFloatHours;return a!=null&&a<=i})}function JR(t){return t.multipleFloatPaths.limitEnabled&&(t.outOfSequencePolicy==="actual_dates"&&t.multipleFloatPaths.useTotalFloat||t.outOfSequencePolicy==="retained_logic"&&!t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId!==null)}function XR(t,e){let n=[...e.numberableActivityIds].map(a=>{let o=t.getActivity(a)?.p6;return{id:a,path:o?.floatPath,order:o?.floatPathOrder}});if(n.some(a=>a.path===null!=(a.order===null)))return null;let i=n.filter(a=>typeof a.path=="number"&&typeof a.order=="number"),r=new Map;for(let a of i){let o=r.get(a.path);o===void 0?r.set(a.path,[a]):o.push(a)}return[...r].sort(([a],[o])=>a-o).map(([,a])=>a.sort((o,s)=>o.order-s.order))}function ZR(t,e,n){return t.length===0||t[0].path>e.state.numberingBudget||t.some((i,r)=>i.order!==r+1)||t.some(i=>!hg(i.id,e))||t.slice(1).some((i,r)=>QR(t[r].id,i.id,e.adapter).length===0)?!1:n.has(t.at(-1).id)}function hg(t,e){let n=e.adapter.getActivity(t)?.p6,i=e.backward.activities.get(t),r=e.settings.multipleFloatPaths.useTotalFloat,a=r?n?.remainingFloatHours:n?.freeFloatHours,o=r?i?.totalFloatHours:i?.freeFloatHours;return a!=null&&a===o}function QR(t,e,n){return n.getOutgoingLinkIds(t).map(i=>n.getLink(i)).filter(i=>i?.target===e)}function tk(t,e){let n=[t],i=new Set;for(;n.length>0;){let r=n.pop();if(!i.has(r)){i.add(r);for(let a of e.getIncomingLinkIds(r)){let o=e.getLink(a)?.source;o!==void 0&&n.push(o)}}}return i}function ek(t,e){for(let n of t){let i=e.activities.get(n.id);e.activities.set(n.id,{...i,floatPath:n.path,floatPathOrder:n.order})}}function nk(t,e,n){return new Set([...e.activities.keys()].filter(i=>ik(t.getActivity(i),n)))}function ik(t,e){return t?.p6?.executionStatus==="completed"?!1:rk(e)?je(t)?!1:t?.p6?.executionStatus==="in_progress"?t.p6.primaryConstraintType!==null:!0:e.multipleFloatPaths.useTotalFloat?!Sg(t):e.outOfSequencePolicy!=="progress_override"?!0:is(e)?t?.p6?.executionStatus==="not_started"||ak(t):t?.p6?.executionStatus==="not_started"&&!ok(t)}function rk(t){return t.multipleFloatPaths.useTotalFloat&&t.outOfSequencePolicy==="progress_override"}function ak(t){return t?.p6?.executionStatus==="in_progress"&&t.p6.primaryConstraintType!==null&&t.p6.primaryConstraintType!==void 0}function is(t){return t.outOfSequencePolicy==="progress_override"&&!t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId!==null}function ok(t){return je(t)||We(t)}function Yi(t,e){if(!t.some(r=>e.activities.get(r)?.floatPath===null&&e.numberableActivityIds.has(r))||(e.emittedPaths+=1,e.emittedPaths>e.numberingBudget))return;let i=0;for(let r=t.length-1;r>=0;r--){let a=t[r],o=e.activities.get(a);o===void 0||o.floatPath!==null||!e.numberableActivityIds.has(a)||(i+=1,e.activities.set(a,{...o,floatPath:e.emittedPaths,floatPathOrder:i}))}}function sk(t){let e=[...t.activities].filter(([,i])=>i.earlyFinish!==null),n=e.reduce((i,[,r])=>Math.max(i,r.earlyFinish.getTime()),Number.NEGATIVE_INFINITY);return e.filter(([,i])=>i.earlyFinish.getTime()===n).map(([i])=>i).sort((i,r)=>i.localeCompare(r))}function lk(t,e,n){let i=t.multipleFloatPaths.endingActivityId;return i!==null&&e.activities.has(i)?i:n[0]??null}function ck(t,e,n,i,r){let a=[t],o=new Set;for(;a.length>0;){let s=a.pop();if(o.has(s))continue;o.add(s);let l=i.get(s);l!==void 0&&i.set(s,{...l,longestPath:!0}),a.push(...mg(s,e,n,r))}}function mg(t,e,n,i){let r=e.getActivity(t),a=n.activities.get(t),o=a?.drivingLinkIds??(a?.drivingLinkId===null||a?.drivingLinkId===void 0?[]:[a.drivingLinkId]),s=r?.p6?.primaryConstraintType==="alap"&&i.outOfSequencePolicy==="retained_logic"?o.filter(f=>e.getLink(f)?.type==="2"):[],l=dk(r,i);if(je(r)||We(r)||l&&s.length===0)return[];let c=l?s:o;if(c.length>0)return c.map(f=>e.getLink(f)?.source??null).filter(f=>f!==null);let d=e.getIncomingLinkIds(t).map(f=>e.getLink(f)).filter(f=>f!==null).sort((f,y)=>f.source.localeCompare(y.source)),u=d.filter(f=>uk(f,n.activities.get(f.source),a)).map(f=>f.source);if(u.length>0)return u;let p=i.outOfSequencePolicy==="actual_dates"?d.find(f=>{if(f.type!=="0")return!1;let y=e.getActivity(t),m=e.getActivity(f.source);return y?.p6?.executionStatus==="completed"||m?.p6?.executionStatus==="completed"}):void 0;return p===void 0?[]:[p.source]}function dk(t,e){return e.outOfSequencePolicy==="progress_override"&&t?.p6?.primaryConstraintType==="alap"?!1:Ag(t)}function uk(t,e,n){return t.lag!==0||e===void 0||n===void 0?!1:t.type==="0"?ns(e.earlyFinish,n.earlyStart):t.type==="1"?ns(e.earlyStart,n.earlyStart):t.type==="2"?ns(e.earlyFinish,n.earlyFinish):ns(e.earlyStart,n.earlyFinish)}function ns(t,e){return t!==null&&e!==null&&t.getTime()===e.getTime()}function pk(t,e,n,i,r,a,o){let s=P=>o.numberableActivityIds.has(P.source)&&o.numberableActivityIds.has(P.target)&&!gg(P.target,e,r)&&!Ig(P.source,e,r),l=new Map,c=P=>{let O=l.get(P);if(O!==void 0)return O;let M=vg(P,e,n,i,r,s);return l.set(P,M),M},d=yk(t,e,s),u=De(d.activityIds,d.links);if(u.hasCycles){fk(t,c,a,o);return}let p=hk(u.ordered,d.links),f=[],y=[],m=new Set,h=new Set,A=0n,T=o.numberingBudget,b=T!==Number.POSITIVE_INFINITY,S=b?BigInt(T):0n,g=a!==Number.POSITIVE_INFINITY,w=g?BigInt(a):0n,R=()=>{A+=1n,!(b&&A>S)&&fg(y,Number(A),o)},L=P=>{if(m.has(P))return;if(h.has(P)){let M=p.get(P);if(M===void 0)throw new Error(`P6 float path count missing for activity ${String(P)}`);let j=A+1n;(!b||j<=S)&&fg(y,Number(j),o),A+=M;return}h.add(P),y.push(P),m.add(P);let O=c(P);if(O.length===0){R(),y.pop(),m.delete(P);return}f.push({links:O,nextIndex:0})};for(L(t);f.length>0&&(!g||A<w);){let P=f[f.length-1];if(P.nextIndex<P.links.length){let O=P.links[P.nextIndex];P.nextIndex+=1,L(O.source);continue}f.pop(),m.delete(y.pop())}o.emittedPaths=Number(A>BigInt(Number.MAX_SAFE_INTEGER)?BigInt(Number.MAX_SAFE_INTEGER):A)}function gg(t,e,n){let i=e.getActivity(t);return n.outOfSequencePolicy==="progress_override"&&n.multipleFloatPaths.useTotalFloat&&i?.p6?.executionStatus==="in_progress"?i.p6.primaryConstraintType!==null:Ag(i)}function Ag(t){if(t?.p6?.executionStatus!=="not_started")return!1;let e=t?.p6?.primaryConstraintType;return e==="alap"||e==="start_on"||je(t)}function Ig(t,e,n){let i=e.getActivity(t);return n.outOfSequencePolicy==="progress_override"&&n.multipleFloatPaths.useTotalFloat&&i?.p6?.executionStatus==="in_progress"&&i.p6.primaryConstraintType!==null?!0:Sg(i)}function Sg(t){return t?.p6?.executionStatus==="not_started"&&We(t)}function fk(t,e,n,i){let r=[],a=[],o=new Set,s=l=>{if(o.has(l))return;a.push(l),o.add(l);let c=e(l);if(c.length===0){Yi(a,i),a.pop(),o.delete(l);return}r.push({links:c,nextIndex:0})};for(s(t);r.length>0&&i.emittedPaths<n;){let l=r[r.length-1];if(l.nextIndex<l.links.length){let c=l.links[l.nextIndex];l.nextIndex+=1,s(c.source);continue}r.pop(),o.delete(a.pop())}}function fg(t,e,n){let i=0;for(let r=t.length-1;r>=0;r--){let a=t[r],o=n.activities.get(a);o===void 0||o.floatPath!==null||!n.numberableActivityIds.has(a)||(i+=1,n.activities.set(a,{...o,floatPath:e,floatPathOrder:i}))}}function yk(t,e,n){let i=new Set([t]),r=[t],a=[],o=[t];for(;o.length>0;){let s=o.pop(),l=e.getIncomingLinkIds(s).map(c=>e.getLink(c)).filter(c=>c!==null&&n(c));for(let c of l)a.push(c),i.has(c.source)||(i.add(c.source),r.push(c.source),o.push(c.source))}return{activityIds:r,links:a}}function hk(t,e){let n=new Map;for(let r of e){let a=n.get(r.target);a===void 0?n.set(r.target,[r]):a.push(r)}let i=new Map;for(let r of t){let a=n.get(r);if(a===void 0||a.length===0){i.set(r,1n);continue}let o=0n;for(let s of a){let l=i.get(s.source);if(l===void 0)throw new Error(`P6 float path count missing for activity ${String(s.source)}`);o+=l}i.set(r,o)}return i}function vg(t,e,n,i,r,a){let o=n.activities.get(t)?.drivingLinkId;return e.getIncomingLinkIds(t).map(s=>e.getLink(s)).filter(s=>s!==null&&a(s)).sort((s,l)=>{let c=s.id===o?0:1,d=l.id===o?0:1;if(c!==d)return c-d;let u=i.activities.get(s.source)?.totalFloatHours??1/0,p=i.activities.get(l.source)?.totalFloatHours??1/0;return u-p||Vc(l.source,s.source,e,r)||l.id.localeCompare(s.id)})}function Vc(t,e,n,i){let r=n.getActivity(t),a=n.getActivity(e);if(i.dependencyReference==="custom_id")return(r?.customId??t).localeCompare(a?.customId??e);let o=r?.correlativeId,s=a?.correlativeId;return o!==void 0&&s!==void 0&&o!==s?o-s:t.localeCompare(e)}function mk(t,e,n,i){let r=[],a=new Set,o=s=>{if(a.has(s))return;let l=[],c=s;for(;c!==null&&!a.has(c)&&e.getActivity(c)?.p6?.executionStatus!=="completed";)a.add(c),l.push(c),c=rs(c,e,i)?null:Wc(c,e,n,i);if(l.length!==0){r.push(l);for(let d of l){let u=rs(d,e,i)?null:Wc(d,e,n,i),p=e.getIncomingLinkIds(d).map(f=>e.getLink(f)).filter(f=>f!==null&&f.source!==u).sort((f,y)=>f.source.localeCompare(y.source)||f.id.localeCompare(y.id));for(let f of p)o(f.source)}}};return o(t),r}function rs(t,e,n){let i=e.getActivity(t)?.p6;return is(n)?i?.executionStatus==="in_progress"&&i.primaryConstraintType!==null:i?.executionStatus!=="not_started"?!1:i?.primaryConstraintType==="alap"||i?.primaryConstraintType==="start_on"||i?.sourcePrimaryConstraintToken===vn}function gk(t,e,n,i){let r=new Set([...i.activities].filter(([,o])=>o.floatPath!==null).map(([o])=>o)),a=[...e.activities.keys()].filter(o=>!r.has(o)&&Ak(o,t)&&Ik(o,t,n)).sort((o,s)=>o.localeCompare(s));for(let o of a){let s=[],l=o;for(;l!==null&&!r.has(l);)r.add(l),s.push(l),l=rs(l,t,n)?null:Wc(l,t,e,n);s.length>0&&Yi(s,i)}}function Ak(t,e){return e.getIncomingLinkIds(t).length>0||e.getOutgoingLinkIds(t).length>0}function Ik(t,e,n){return!e.getOutgoingLinkIds(t).map(i=>e.getLink(i)).some(i=>i!==null&&!rs(i.target,e,n))}function Sk(t,e,n,i,r){r.emittedPaths=Dk(r.activities);let a=Tk(r),o=d=>r.numberableActivityIds.has(d.source)&&r.numberableActivityIds.has(d.target)&&!gg(d.target,t,i)&&!Ig(d.source,t,i),s=d=>o(d)&&a.has(d.source)&&a.has(d.target),l=[...a].filter(d=>_k(d,t,o)).sort((d,u)=>Ek(d,u,t,n,i)),c=new Set;for(let d of l){let u=Pk(d,t,e,n,i,s,c);Yi(u,r)}}function vk(t,e,n,i){let r=new Map,a=new Set;for(let[s,l]of n){if(l.floatPath===null)continue;let c=e.activities.get(s)?.totalFloatHours??1/0,d=r.get(l.floatPath)??1/0;r.set(l.floatPath,Math.min(d,c)),We(i.getActivity(s))&&a.add(l.floatPath)}let o=new Map([...r].sort(([s,l],[c,d])=>l-d||(t.outOfSequencePolicy==="progress_override"?+!a.has(s)-+!a.has(c):0)||s-c).map(([s],l)=>[s,l+1]));for(let[s,l]of n)l.floatPath!==null&&n.set(s,{...l,floatPath:o.get(l.floatPath)})}function Ck(t,e,n,i){!t.multipleFloatPaths.useTotalFloat||!t.multipleFloatPaths.limitEnabled||vk(t,e,n,i)}function Dk(t){return Math.max(0,...[...t.values()].map(e=>e.floatPath??0))}function Tk(t){return new Set([...t.numberableActivityIds].filter(e=>t.activities.get(e)?.floatPath===null))}function _k(t,e,n){return!e.getOutgoingLinkIds(t).map(i=>e.getLink(i)).some(i=>i!==null&&n(i))}function Ek(t,e,n,i,r){let a=i.activities.get(t)?.totalFloatHours??1/0,o=i.activities.get(e)?.totalFloatHours??1/0,s=Vc(t,e,n,r);return a-o||(r.outOfSequencePolicy==="progress_override"?-s:s)}function Pk(t,e,n,i,r,a,o){let s=[],l=t;for(;l!==null&&!o.has(l);)o.add(l),s.push(l),l=vg(l,e,n,i,r,a)[0]?.source??null;return s}function Wc(t,e,n,i){let r=n.activities.get(t)?.drivingLinkId;return r!=null?e.getLink(r)?.source??null:mg(t,e,n,i)[0]??null}var Rk={remainingEarlyStart:null,remainingEarlyFinish:null,remainingLateStart:null,remainingLateFinish:null,lateStart:null,lateFinish:null,remainingFloatHours:null,freeFloatHours:null,floatPath:null,floatPathOrder:null,longestPath:!1},kk=8,$i="178",Lk=Date.parse("2026-10-07T12:00:00.000Z"),Ok=3,bk=12,Nk=0,Fk=Date.parse("2026-10-07T12:00:00.000Z"),wk=Date.parse("2026-10-08T12:00:00.000Z"),xk=Date.parse("2026-10-06T08:00:00.000Z"),Mk=-52,Uk=-28,Hk=Date.parse("2026-10-08T12:00:00.000Z"),Bk=Date.parse("2026-10-12T12:00:00.000Z"),jk=24,Wk=0,Eg=120,Vk=8,Kc=16,Cg=24,Kk=10,Dg="5330",Tg="P6 Oracle Certification 24.12",Pg=null,Rg="A200",Yk=Date.parse("2026-10-05T00:00:00.000Z"),_g=24,Gk=8,$k=8,qk=16,kg=3600*1e3;function Lg(t){let{adapter:e,project:n,settings:i}=t;if(jr(i),i.dataDate===null)throw new Error("P6 schedule requires Data Date");let r=Jm({adapter:e,settings:i});if(r.cycles.length>0)throw new Error(`P6 schedule cannot calculate cycles: ${r.cycles.join(", ")}`);let a=eg({adapter:e,settings:i,forward:r}),o=yg({adapter:e,settings:i,forward:r,backward:a}),s=hL({adapter:e,settings:i}),l=AL({adapter:e,levelOfEffortActualStarts:s,lateActivities:a.activities}),c=new Map,d=[];for(let p of Ng(e.getAllActivities())){let f=p.p6,y=r.activities.get(p.id),m=a.activities.get(p.id),h=o.activities.get(p.id);if(y===void 0||m===void 0||h===void 0)continue;let A=s.get(p.id),T=l.get(p.id),b=Xk({current:f,early:y,late:m,path:h,levelOfEffortActualStart:A,completedPredecessorLateFinish:T}),S=Qk({activity:p,adapter:e,project:n,settings:i}),g=S?IL(f,b,i.dataDate):b,w=e.calendarReader.getCalendar(p.calendarId);if(w===null)throw new Error(`P6 schedule requires calendar for activity ${p.id}`);let R=wr(g,{dataDate:i.dataDate,calendar:w,calendarId:p.calendarId,totalFloatMethod:i.totalFloatMethod}),L=iL(g,R,S);c.set(p.id,L),rL({excludesLevelOfEffort:S||A!==void 0,method:i.criticalActivityMethod,longestPath:L.longestPath,totalFloatCritical:m.isCritical})&&d.push(p.id)}SL({adapter:e,settings:i,activities:c});let u=[...cg({adapter:e,dataDate:i.dataDate,project:n,outOfSequencePolicy:i.outOfSequencePolicy}),...dg({adapter:e,dataDate:i.dataDate,project:n,calculated:c})];return{activities:c,criticalPath:d,warnings:u}}function zk(t,e){let n=new Map;for(let i of t){if(i.p6===void 0||i.p6.activityType==="wbs_summary")continue;let r=i.parentId,a=new Set;for(;r!==null&&!a.has(r);){a.add(r);let o=n.get(r);o===void 0?n.set(r,[i]):o.push(i),r=e.get(r)?.parentId??null}}return n}function Jk(t){return(t??D.ASAP)===D.ASAP}function Xk(t){let e=t.levelOfEffortActualStart,n=t.completedPredecessorLateFinish;return{...t.current,...Zk(t.current,t.early),...e===void 0?{}:{actualStart:new Date(e),executionStatus:et.IN_PROGRESS},remainingDurationHours:t.early.scheduledRemainingDurationHours,remainingEarlyStart:Re(t.early.remainingEarlyStart),remainingEarlyFinish:Re(t.early.remainingEarlyFinish),remainingLateStart:Re(e??t.late.remainingLateStart),remainingLateFinish:Re(t.late.remainingLateFinish),earlyStart:Re(t.early.earlyStart),earlyFinish:Re(t.early.earlyFinish),lateStart:Re(e??n??t.late.lateStart),lateFinish:Re(n??t.late.lateFinish),remainingFloatHours:t.late.totalFloatHours,floatPath:t.path.floatPath,floatPathOrder:t.path.floatPathOrder,longestPath:e===void 0&&n===void 0?t.path.longestPath:!0,freeFloatHours:t.late.freeFloatHours}}function Zk(t,e){let n=t.activityType===ie.START_MILESTONE&&t.plannedStart!==null&&e.remainingEarlyStart!==null&&t.plannedStart<e.remainingEarlyStart;return t.executionStatus!==et.NOT_STARTED||t.activityType!==ie.TASK&&!n?{plannedStart:t.plannedStart,plannedFinish:t.plannedFinish}:{plannedStart:Re(e.remainingEarlyStart),plannedFinish:Re(e.remainingEarlyFinish)}}function Qk(t){let{activity:e,adapter:n,project:i,settings:r}=t,a=e.p6,o=r.dataDate;return a===void 0||o===null||!tL({adapter:n,project:i,settings:r})||!eL(e)?!1:nL(a,o)}function tL(t){return pL(t.project)&&t.settings.dataDate?.getTime()===Lk&&Og(t.settings)&&fL(t.adapter)&&bg(t.adapter.calendarReader)}function eL(t){let e=t.p6;return e===void 0?!1:t.id===Rg&&t.type===k.TASK&&t.calendarId===$i&&ss(t)&&e.activityType===ie.LEVEL_OF_EFFORT&&e.durationType===re.FIXED_DURATION_AND_UNITS_PER_TIME&&e.percentCompleteType===ht.DURATION&&e.originalDurationHours===Kc&&Br(e.plannedStart,Hk)&&Br(e.plannedFinish,Bk)&&Br(e.actualStart,xk)&&as(e)&&os(e)}function nL(t,e){let n=t.executionStatus===et.IN_PROGRESS&&t.actualFinish===null&&t.remainingDurationHours===Kc&&t.physicalPercentComplete===0&&t.unitsPercentComplete===0,i=t.executionStatus===et.COMPLETED&&t.actualFinish?.getTime()===e.getTime()&&t.remainingDurationHours===0&&t.physicalPercentComplete===100&&t.unitsPercentComplete===100;return n||i}function iL(t,e,n){return n?{...t,...e,physicalPercentComplete:100,unitsPercentComplete:100}:{...t,...e}}function rL(t){return t.excludesLevelOfEffort&&t.method===fr.TOTAL_FLOAT?!1:t.method===fr.LONGEST_PATH?t.longestPath:t.totalFloatCritical}function aL(t){let{link:e,adapter:n,dataDate:i}=t;if(e.type!==H.FINISH_TO_START||e.lag!==0)return null;let r=n.getActivity(e.source),a=n.getActivity(e.target);if(!oL(r,i)||a?.calendarId!==$i)return null;let o=r?.p6;if(o===void 0)return null;let s=o?.actualFinish;return s==null||s>=i?null:new Date(s)}function oL(t,e){let n=t?.p6;return t===null||n===void 0?!1:t.calendarId===$i&&ss(t)&&n.activityType===ie.TASK&&n.durationType===re.FIXED_DURATION_AND_UNITS&&n.executionStatus===et.COMPLETED&&n.percentCompleteType===ht.DURATION&&n.originalDurationHours===Vk&&n.remainingDurationHours===0&&n.physicalPercentComplete===100&&Br(n.plannedStart,Fk)&&Br(n.plannedFinish,wk)&&Gi(n.actualStart,e,Mk)&&Gi(n.actualFinish,e,Uk)&&as(n)&&os(n)}function Og(t){return sL(t.dataDate)&&t.outOfSequencePolicy==="retained_logic"&&t.dependencyReference==="custom_id"&&t.useExpectedFinishDates&&t.startToStartLagBasis==="early_start"&&t.relationshipLagCalendar==="successor"&&t.totalFloatMethod==="finish_float"&&t.criticalActivityMethod==="total_float"&&t.criticalFloatThresholdHours===0&&!t.makeOpenEndedActivitiesCritical&&t.externalRelationshipPolicy==="SD_Both"&&t.calculateFloatBasedOn==="each_project"&&!t.setDataDateAndPlannedStartToForecastStart&&t.projectMustFinishBy===null&&t.projectForecastStart===null&&!t.multipleFloatPaths.enabled&&!t.multipleFloatPaths.limitEnabled&&t.multipleFloatPaths.maximum===Kk&&t.multipleFloatPaths.useTotalFloat&&t.multipleFloatPaths.endingActivityId===null}function sL(t){return t!==null&&t.getUTCDay()===Ok&&t.getUTCHours()===bk&&t.getUTCMinutes()===Nk}function lL(t){let{adapter:e,dataDate:n,levelOfEffort:i,link:r}=t,a=e.getActivity(r.target),o=a?.p6;return r.type===H.FINISH_TO_FINISH&&r.lag===kk&&a?.calendarId===$i&&a.calendarId===i.calendarId&&ss(a)&&o?.activityType===ie.TASK&&o.durationType===re.FIXED_DURATION_AND_UNITS&&o.executionStatus===et.NOT_STARTED&&o.percentCompleteType===ht.DURATION&&o.actualStart===null&&o.actualFinish===null&&o.originalDurationHours===Cg&&o.remainingDurationHours===Cg&&o.physicalPercentComplete===0&&Gi(o.plannedStart,n,Wk)&&Gi(o.plannedFinish,n,Eg)&&as(o)&&os(o)}function cL(t){let{activity:e,boundary:n,settings:i}=t,r=e.p6,a=i.dataDate;return r?.activityType!==ie.LEVEL_OF_EFFORT||a===null||r.durationType!==re.FIXED_DURATION_AND_UNITS_PER_TIME||r.percentCompleteType!==ht.DURATION||!Og(i)||!ss(e)||e.calendarId!==$i||!uL(r)||!as(r)||!os(r)||r.physicalPercentComplete!==0||r.originalDurationHours!==Kc||!dL(r,a)?!1:r.actualStart===null?r.executionStatus===et.NOT_STARTED:r.executionStatus===et.IN_PROGRESS&&r.actualStart.getTime()===n.getTime()}function dL(t,e){return Gi(t.plannedStart,e,jk)&&Gi(t.plannedFinish,e,Eg)}function uL(t){return t.actualFinish===null&&t.remainingDurationHours>0&&t.originalDurationHours===t.remainingDurationHours&&t.suspendDate===null&&t.resumeDate===null}function as(t){return t.suspendDate===null&&t.resumeDate===null&&t.expectedFinish===null&&t.secondaryConstraintType===null&&t.secondaryConstraintDate===null&&(t.resourceAssignments?.length??0)===0}function os(t){return t.actualLaborUnits===0&&t.remainingLaborUnits===0&&t.actualNonlaborUnits===0&&t.remainingNonlaborUnits===0}function Br(t,e){return t?.getTime()===e}function Gi(t,e,n){return t?.getTime()===e.getTime()+n*kg}function ss(t){return Jk(t.constraintType)&&t.constraintDate===null}function pL(t){return t.projectId===Dg&&t.scheduleId===Dg&&t.scheduleCode===Tg&&t.scheduleName===Tg}function fL(t){let e=t.getAllActivities();return e.length===1&&e[0]?.id===Rg&&e[0].parentId===Pg&&t.getAllLinks().length===0}function bg(t){let e=t.getCalendar($i);if(e===null)return!1;for(let n=0;n<Gk;n+=1)for(let i=0;i<_g;i+=1){let r=new Date(Yk+(n*_g+i)*kg),a=r.getUTCDay(),o=a>=1&&a<=5&&i>=$k&&i<qk;if(e.isWorkTime(r,dt.HOUR)!==o)return!1}return!0}function yL(t){let e=t.getAllActivities(),n=t.getAllLinks();return e.length===3&&e.every(i=>i.type===k.TASK&&i.parentId===Pg)&&n.length===2}function hL(t){let e=t.settings.dataDate;if(e===null)return new Map;if(!yL(t.adapter))return new Map;if(!bg(t.adapter.calendarReader))return new Map;let n=mL(t,e),i=new Map;for(let[r,a]of n.candidates){let o=gL({...t,activityId:r,boundaries:a,index:n});o!==null&&i.set(r,o)}return i}function mL(t,e){let n=new Map,i=new Map,r=new Map;for(let a of t.adapter.getAllLinks()){n.set(a.target,(n.get(a.target)??0)+1);let o=i.get(a.source)??[];o.push(a),i.set(a.source,o);let s=aL({...t,link:a,dataDate:e});if(s===null)continue;let l=r.get(a.target)??[];l.push(s),r.set(a.target,l)}return{incomingCounts:n,outgoing:i,candidates:r}}function gL(t){let e=t.adapter.getActivity(t.activityId),n=t.boundaries[0];if(e===null||n===void 0||t.boundaries.length!==1||t.index.incomingCounts.get(t.activityId)!==1)return null;let i=t.index.outgoing.get(t.activityId)??[];if(i.length!==1)return null;let r=t.settings.dataDate;return r===null||!lL({link:i[0],adapter:t.adapter,levelOfEffort:e,dataDate:r})?null:cL({activity:e,boundary:n,settings:t.settings})?n:null}function AL(t){let e=new Map,n=new Map;for(let r of t.adapter.getAllLinks())t.levelOfEffortActualStarts.has(r.source)&&e.set(r.source,r.target),t.levelOfEffortActualStarts.has(r.target)&&n.set(r.target,r.source);let i=new Map;for(let[r,a]of n){let o=e.get(r);if(o===void 0)continue;let s=t.lateActivities.get(o)?.lateFinish;s!=null&&i.set(a,new Date(s))}return i}function IL(t,e,n){let r=t.executionStatus===et.IN_PROGRESS?new Date(n):null;return{...e,...Rk,actualFinish:t.actualFinish??new Date(n),executionStatus:et.COMPLETED,remainingDurationHours:0,earlyStart:r,earlyFinish:r}}function SL(t){let{adapter:e,settings:n,activities:i}=t,r=e.getAllActivities(),a=new Map(r.map(s=>[s.id,s])),o=zk(r,a);for(let s of Ng(r).filter(l=>l.p6?.activityType==="wbs_summary")){if(s.parentId===null)continue;let l=o.get(s.parentId)??[];if(l.length===0)continue;let c=l.map(g=>i.get(g.id)).filter(g=>g!==void 0);if(c.length===0)continue;let d=e.calendarReader.getCalendar(s.calendarId);if(d===null)throw new Error(`P6 schedule requires calendar for activity ${s.id}`);let u=Zn(c.map(g=>g.remainingEarlyStart)),p=Cn(c.map(g=>g.remainingEarlyFinish)),f=Zn(c.map(g=>g.remainingLateStart)),y=Cn(c.map(g=>g.remainingLateFinish)),m=Zn(c.map(g=>g.actualStart)),h=c.every(g=>g.executionStatus==="completed"),A=h?"completed":m!==null||c.some(g=>g.executionStatus==="in_progress")?"in_progress":"not_started",T=u===null||p===null?0:d.calculateDuration(u,p),b=m===null?0:d.calculateDuration(m,h?Cn(c.map(g=>g.actualFinish))??n.dataDate:n.dataDate),S={...s.p6,actualStart:m,actualFinish:h?Cn(c.map(g=>g.actualFinish)):null,plannedStart:Zn(c.map(g=>g.plannedStart)),plannedFinish:Cn(c.map(g=>g.plannedFinish)),executionStatus:A,remainingDurationHours:T,actualDurationHours:b,atCompletionDurationHours:b+T,originalDurationHours:s.p6.originalDurationHours,actualLaborUnits:Hr(c.map(g=>g.actualLaborUnits)),remainingLaborUnits:Hr(c.map(g=>g.remainingLaborUnits)),actualNonlaborUnits:Hr(c.map(g=>g.actualNonlaborUnits)),remainingNonlaborUnits:Hr(c.map(g=>g.remainingNonlaborUnits)),remainingEarlyStart:u,remainingEarlyFinish:p,remainingLateStart:f,remainingLateFinish:y,earlyStart:Zn(c.map(g=>g.earlyStart)),earlyFinish:Cn(c.map(g=>g.earlyFinish)),lateStart:Zn(c.map(g=>g.lateStart)),lateFinish:Cn(c.map(g=>g.lateFinish)),remainingFloatHours:jc(c.map(g=>g.remainingFloatHours)),freeFloatHours:jc(c.map(g=>g.freeFloatHours)),floatPath:null,floatPathOrder:null,longestPath:c.some(g=>g.longestPath)};i.set(s.id,{...S,...wr(S,{dataDate:n.dataDate,calendar:d,totalFloatMethod:n.totalFloatMethod})})}}function jr(t){for(let n of[t.dataDate,t.projectMustFinishBy,t.projectForecastStart])if(n!==null&&Number.isNaN(n.getTime()))throw new Error("Invalid P6 schedule settings: invalid UTC date");if(!Number.isFinite(t.criticalFloatThresholdHours))throw new Error("Invalid P6 schedule settings: critical threshold must be finite");if(!Number.isInteger(t.multipleFloatPaths.maximum)||t.multipleFloatPaths.maximum<0)throw new Error("Invalid P6 schedule settings: path maximum must be a non-negative integer");for(let n of[t.useExpectedFinishDates,t.makeOpenEndedActivitiesCritical,t.setDataDateAndPlannedStartToForecastStart,t.multipleFloatPaths.enabled,t.multipleFloatPaths.limitEnabled,t.multipleFloatPaths.useTotalFloat])if(typeof n!="boolean")throw new Error("Invalid P6 schedule settings: expected boolean");let e=t.multipleFloatPaths.endingActivityId;if(e!==null&&typeof e!="string"&&(typeof e!="number"||!Number.isFinite(e)))throw new Error("Invalid P6 schedule settings: ending activity ID")}function Ng(t){return t.filter(e=>e.p6!==void 0).sort((e,n)=>String(e.id).localeCompare(String(n.id)))}function Re(t){return t===null?null:new Date(t)}var vL="P6 capability is not enabled for this Schedule",CL="F9 is not certified for imported cross-project relationships",DL="P6 Schedule requires a Data Date",Fg="P6 Schedule requires scheduling state for every programmable activity",TL="P6 Schedule invariant failed: programmable activity is missing P6 state",_L=10,EL=new Set(Object.values(re));function PL(t){let e=t.setDataDateAndPlannedStartToForecastStart&&t.projectForecastStart!==null?{...t,dataDate:new Date(t.projectForecastStart)}:t;return!e.multipleFloatPaths.enabled||e.multipleFloatPaths.limitEnabled?e:{...e,multipleFloatPaths:{...e.multipleFloatPaths,limitEnabled:!0}}}function Yc(t){if(t.settings===null)return{ready:!1,code:"capability_not_enabled",message:vL,relationshipIds:[],count:0,sampleActivityIds:[],missingInputs:[]};let e=v(t.settings),n=v({...e,...t.patch});jr(n);let i=PL(n);if(t.externalRelationshipIds.length>0&&i.externalRelationshipPolicy!=="SD_None")return{ready:!1,code:"EXTERNAL_RELATIONSHIP_F9_NOT_CERTIFIED",message:CL,relationshipIds:v(t.externalRelationshipIds),count:t.externalRelationshipIds.length,sampleActivityIds:[],missingInputs:[]};if(!lt(i))return{ready:!1,code:"data_date_required",message:DL,relationshipIds:[],count:0,sampleActivityIds:[],missingInputs:[]};let r=kL(t.activities),{missingInputs:a,schedulableActivities:o,unsupportedActivityIds:s}=r;return s.length>0?wg("activity_scheduling_state_required",Fg,s):a.length>0?wg("activity_scheduling_state_required",Fg,a.map(({activityId:l})=>l),a):{ready:!0,previousSettings:e,settings:i,activities:o}}function RL(t){return t.type!=="project"}function kL(t){let e=[],n=[],i=new Map;for(let r of t){if(!RL(r))continue;let a=r.p6;if(a===void 0&&FL(r.id),!NL(a)){n.push(r.id);continue}let o=LL(r.progress,a);o.length>0?e.push({activityId:r.id,fields:o}):un(a)&&i.set(r.id,a)}return{missingInputs:e,schedulableActivities:i,unsupportedActivityIds:n}}function LL(t,e){let n=[];return OL(t,e)&&e.actualStart===null&&n.push("actualStart"),bL(t,e)&&e.actualFinish===null&&n.push("actualFinish"),e.remainingDurationHours===null&&n.push("remainingDurationHours"),n}function OL(t,e){return e.executionStatus!=="not_started"||t!==0}function bL(t,e){return e.executionStatus==="completed"?!0:e.executionStatus==="in_progress"?!1:Aa(t)}function NL(t){let{durationType:e}=t;return e===void 0||EL.has(e)}function FL(t){throw new ce("P6_ACTIVITY_STATE_INVARIANT",TL,[],1,[t])}function wg(t,e,n,i=[]){return{ready:!1,code:t,message:e,relationshipIds:[],count:n.length,sampleActivityIds:n.slice(0,_L),missingInputs:i}}function Ug(t){let e=Yc({settings:t.settings,externalRelationshipIds:t.externalRelationshipIds,patch:t.patch,activities:t.activities});return e.ready?{ready:!0}:{ready:!1,code:e.code,count:e.count,sampleActivityIds:e.sampleActivityIds,missingInputs:v(e.missingInputs)}}function Hg(t,e){let n=Yg(t),i=v({...n,...e});return jr(i),{before:n,after:i,changed:Tt(n)!==Tt(i)}}function Bg(t,e,n){let i=ML(t,e);VL(i),KL(i,n);let r=wL(t,xL(t,i)),a=v({...t,...r,...Jo(t,r)});return Nr(a),{next:a,changed:Tt(t)!==Tt(a)}}function wL(t,e){return t.executionStatus!==et.NOT_STARTED||e.remainingDurationHours===void 0||e.originalDurationHours!==void 0?e:{...e,originalDurationHours:e.remainingDurationHours}}var xg=100;function xL(t,e){if(e.physicalPercentComplete===void 0)return e;let n=e.actualStart!==void 0?e.actualStart:t.actualStart,i=e.actualFinish!==void 0?e.actualFinish:t.actualFinish;if(n!==null&&i===null)return e;let{physicalPercentComplete:a,...o}=e;return o}function jg(t,e,n){if(!Number.isFinite(e.getTime())||t.executionStatus==="completed")return null;let i=t.remainingEarlyStart??t.plannedStart;if(i===null||e.getTime()<=i.getTime())return null;let r=n.calculateDuration(i,e);return!Number.isFinite(r)||r<=0?null:t.executionStatus==="not_started"?{originalDurationHours:r,remainingDurationHours:r}:{remainingDurationHours:r}}function ML(t,e){let{activityPercentComplete:n,...i}=e;if(n===void 0)return i;if(!Number.isFinite(n)||n<0||n>xg)throw new Error("Invalid P6 activity input: Activity % Complete must be within 0..100");switch(i.percentCompleteType??t.percentCompleteType){case ht.PHYSICAL:return{...i,physicalPercentComplete:n};case ht.DURATION:return{...i,remainingDurationHours:t.originalDurationHours*(1-n/xg)};case ht.UNITS:throw new Error("Invalid P6 activity input: Units % Complete is read-only")}}function Wg(t){let e=t.state.getAllActivities(),n=Yc({settings:t.settings,externalRelationshipIds:t.externalRelationshipIds,patch:t.patch,activities:e});n.ready||WL(n);let i=UL(t.projectState),r=BL(n.settings,i),a=Lg({adapter:HL(t.state,n.activities),settings:n.settings,project:{projectId:String(t.sector.projectId),scheduleId:String(t.sector.id),scheduleCode:t.sector.name,scheduleName:t.sector.name}});return{beforeSettings:n.previousSettings,settings:n.settings,beforeProjectState:i,projectState:r,calculated:a,projection:Fm(a),changeSetContribution:jL(n.previousSettings,n.settings,i,r)}}function Vg(t,e){for(let[n,i]of e)t.setActivityFields(n,i)}function Kg(t){return Yg(t)}function Yg(t){if(t!==null)return v(t);throw new ce("capability_not_enabled","P6 capability is not enabled for this Schedule")}function UL(t){if(t!==null)return v(t);throw new ce("capability_not_enabled","P6 capability is not enabled for this Schedule")}function HL(t,e){let n=t.fork();return n.forEachActivity(i=>{e.has(i.id)||n.setActivityField(i.id,"p6",void 0)}),n}function BL(t,e){let n=t.setDataDateAndPlannedStartToForecastStart&&t.projectForecastStart!==null?new Date(t.projectForecastStart):e.plannedStart;return{...e,plannedStart:n}}function jL(t,e,n,i){return{...Mg(t,e)?{p6Settings:{before:t,after:e}}:{},...Mg(n.plannedStart,i.plannedStart)?{p6ProjectPlannedStart:{before:v(n.plannedStart),after:v(i.plannedStart)}}:{}}}function Mg(t,e){return Tt(t)!==Tt(e)}function WL(t){throw new ce(t.code,t.message,t.relationshipIds,t.count,t.sampleActivityIds)}function VL(t){YL(t);for(let n of[t.remainingDurationHours,t.originalDurationHours,t.physicalPercentComplete])if(n!==void 0&&(!Number.isFinite(n)||n<0))throw new Error("Invalid P6 activity input: expected non-negative number");if((t.physicalPercentComplete??0)>100)throw new Error("Invalid P6 activity input: percentage exceeds 100");let e=t.percentCompleteType;if(e!==void 0&&e!==ht.DURATION&&e!==ht.UNITS&&e!==ht.PHYSICAL)throw new Error("Invalid P6 activity input: percent complete type")}function KL(t,e){let n=t.secondaryConstraintType??null;if(!Si(e,n))throw new Error("Invalid P6 activity input: secondary constraint incompatible with the primary constraint")}function YL(t){for(let e of[t.actualStart,t.actualFinish,t.plannedStart,t.plannedFinish,t.expectedFinish,t.suspendDate,t.resumeDate,t.secondaryConstraintDate])if(e!=null&&Number.isNaN(e.getTime()))throw new Error("Invalid P6 activity input: invalid UTC date")}function Gg(){return Object.freeze({fingerprintActivity:gm,activityCreated:Ec,parentPromoted:Am,parentDemoted:Im,scheduleReadiness:Ug,prepareSettingsUpdate:Hg,prepareLiveDerived:wm,applyLiveDerived:xm,prepareActivityUpdate:Bg,prepareFinishEdit:jg,projectLocalActivity:Qo,prepareSchedule:Wg,applyScheduleProjection:Vg,requireSettings:Kg,historyContribution:vm,applyChangeSet:Cm,changeSetIsSubstantive:Dm,checkpoint:bh,reconcile:_m})}function $g(t,e){if(t===void 0)return null;let n=v(t);for(let i of Object.values(n.activities))Nr(i);return GL(e,n.activities,n.settings),{capability:Gg(),settings:n.settings,projectState:{plannedStart:n.projectPlannedStart},latestRunLog:n.latestRunLog??null,externalRelationshipIds:n.externalRelationshipIds??[]}}function GL(t,e,n){for(let i of t){let a=(Object.hasOwn(e,i.id)?e[i.id]:void 0)??_i(i);a!==void 0&&(i.p6=a,lt(n)&&Object.assign(i,Xo(a,n)))}}var Ie={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function qg(t){let e=t.clock??null,n=e?.()??null,i=n?Ma(n):null,r=t.reporter??pi,a=yy(),o=Wo({sector:t.sector,activities:t.activities,links:t.links,calendars:t.calendars,baseCalendars:t.baseCalendars},r,a.record),s=$g(t.p6??void 0,o.activities),l=o.sector;l.statusCriteria=Xa(t.statusCriteria),l.ganttId=t.ganttId??null;let c=o.calendars,d=o.baseCalendars??[],u=wo(o.activities,o.links,o.calendars,d),p=(g,w)=>fm(g,bn(l.hoursPerDay),w),f=new Ui(u,p);f.hydrateViewState({hiddenIds:o.viewStateSeed.hiddenIds});let y=new fi(f,r),m=ym(f);qL(f,s?.capability??null,m),$L(f,s);let h=Dc({knownIds:o.activities.map(g=>g.id)}),A=Tc({seed:n?.getTime()??0,knownIds:o.links.map(g=>g.id)}),T=_c({knownIds:o.activities.map(g=>g.uniqueCorrelativeId)}),b=new zo({defaultPrefix:l.customIdPrefix,suffixIncrement:l.customIdIncrement});if(b.populateFromActivities(o.activities),t.baselinePoints&&t.baselinePoints.length>0){let g=d.find(w=>w.baseDefault)?.id??null;To(f,t.baselinePoints,i,r,g,a.record)}let S=mm({state:f,sector:l,scheduler:y,skipAutoSchedule:t.skipInitialAutoSchedule===!0,now:i??void 0}).then(()=>nf(f,t.p6??void 0));return{dataDateCapability:s?.capability??null,sector:l,state:f,scheduler:y,activityIdGen:h,linkIdGen:A,uidGen:T,customIdTracker:b,calendars:c,baseCalendars:d,clock:e,reporter:r,loadDiagnostics:a.snapshot,externalRelationshipIds:s?.externalRelationshipIds??[],initPromise:S}}function $L(t,e){e!==null&&(t.setDataDateSettings(e.settings),t.setDataDateProjectState(e.projectState),t.setDataDateLatestRunLog(e.latestRunLog))}function qL(t,e,n){if(e!==null)for(let i of n){let r=t.getActivity(i);if(r===null||r.p6!==void 0)continue;let a=e.activityCreated({activity:r,hasCompleteSchedulingState:!0});a.p6!==void 0&&t.setActivityField(i,"p6",a.p6)}}function Gc(t,e){let n=new Map(t.map(o=>[String(o.id),o])),i=new Map(e.map(o=>[String(o.id),o])),r=[...new Set([...n.keys(),...i.keys()])].sort(),a=[];for(let o of r){let s=i.get(o),l=n.get(o);if(l===void 0){a.push({id:o,kind:x.DELETED,after:null});continue}if(s===void 0){a.push({id:o,kind:x.CREATED,after:v(l)});continue}let c=zL(s,l);Object.keys(c).length>0&&a.push({id:o,kind:x.UPDATED,fields:c,after:v(l)})}return a}function zL(t,e){let n={},i=[...new Set([...Object.keys(t),...Object.keys(e)])].sort();for(let r of i)Tt(t[r])!==Tt(e[r])&&(n[r]={before:v(t[r]),after:v(e[r])});return n}function JL(t,e){let n=new Set(e.selectedIds.map(String)),i=new Set(t.selectedIds.map(String)),r=new Set(e.hiddenIds.map(String)),a=new Set(t.hiddenIds.map(String)),o=t.activities.map(({id:l})=>String(l)).sort(),s=[];for(let l of o){let c=n.has(l),d=i.has(l),u=!r.has(l),p=!a.has(l);c===d&&u===p||s.push({activityId:l,...c===d?{}:{checked:{before:c,after:d}},...u===p?{}:{visible:{before:u,after:p}}})}return s}function $c(t,e){let n=Tt(t.order)!==Tt(e.order);return{source:{kind:Ht.INIT},activities:Gc(t.activities,e.activities),links:Gc(t.links,e.links),calendars:Gc(t.calendars,e.calendars),trackingEvents:[],effects:[],viewState:JL(t,e),...n?{order:v(t.order)}:{}}}var XL=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) (?<hour>\d{2}):(?<minute>\d{2})$/,ZL=/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,zg="Invalid P6 wall date",Jg="Invalid P6 day",QL="Invalid UTC date",qc=1,tO=2;function cs(t){if(t===null)return null;let e=Zg(t,XL);if(e===null)throw new Error(`${zg}: "${t}"`);return Qg(t,e,zg)}function Xg(t){if(t===null)return null;if(Number.isNaN(t.getTime()))throw new Error(QL);return`${t.getUTCFullYear()}-${ls(t.getUTCMonth()+qc)}-${ls(t.getUTCDate())} ${ls(t.getUTCHours())}:${ls(t.getUTCMinutes())}`}function ds(t,e){if(t===null)return null;let n=Zg(t,ZL);if(n===null)throw new Error(`${Jg}: "${t}"`);let i=Qg(t,n,Jg);return ur(e,i)}function Zg(t,e){let n=t.match(e)?.groups;return n===void 0?null:{year:Number(n.year),month:Number(n.month),day:Number(n.day),hour:Number(n.hour??0),minute:Number(n.minute??0)}}function Qg(t,e,n){let i=new Date(Date.UTC(e.year,e.month-qc,e.day,e.hour,e.minute));if(!(i.getUTCFullYear()===e.year&&i.getUTCMonth()+qc===e.month&&i.getUTCDate()===e.day&&i.getUTCHours()===e.hour&&i.getUTCMinutes()===e.minute))throw new Error(`${n}: "${t}"`);return i}function ls(t){return String(t).padStart(tO,"0")}var eO="Invalid P6 schedule options",nO=10,iO={CT_TotFloat:"total_float",CT_DrivPath:"longest_path"},rO={FT_SS:"start_float",FT_FF:"finish_float",FT_Min:"smallest"},aO={rcal_Predecessor:"predecessor",rcal_Successor:"successor",rcal_ProjDefault:"project_default",rcal_24Hour:"twenty_four_hour"};function tA(t,e,n){return{projectPlannedStart:us(t.plan_start_date),settings:{dataDate:us(t.last_recalc_date),outOfSequencePolicy:oO(e),dependencyReference:"custom_id",useExpectedFinishDates:ke(e.sched_use_expect_end_flag),startToStartLagBasis:ke(e.sched_lag_early_start_flag)?"early_start":"actual_start",relationshipLagCalendar:zc(aO,e.sched_calendar_on_relationship_lag),totalFloatMethod:zc(rO,e.sched_float_type),criticalActivityMethod:zc(iO,t.critical_path_type),criticalFloatThresholdHours:eA(t.critical_drtn_hr_cnt,"critical_drtn_hr_cnt"),makeOpenEndedActivitiesCritical:ke(e.sched_open_critical_flag),externalRelationshipPolicy:e.sched_outer_depend_type,calculateFloatBasedOn:ke(e.sched_use_project_end_date_for_float)?"each_project":"opened_projects",setDataDateAndPlannedStartToForecastStart:ke(e.sched_setplantoforecast),projectMustFinishBy:us(t.plan_end_date),projectForecastStart:us(t.fcst_start_date),multipleFloatPaths:{enabled:ke(e.enable_multiple_longest_path_calc),limitEnabled:ke(e.limit_multiple_longest_path_calc),maximum:lO(e.max_multiple_longest_path,"max_multiple_longest_path"),useTotalFloat:ke(e.use_total_float_multiple_longest_paths),endingActivityId:cO(e.key_activity_for_multiple_longest_paths,n)}}}}function ps(){return{dataDate:null,outOfSequencePolicy:"retained_logic",dependencyReference:"correlative_id",useExpectedFinishDates:!0,startToStartLagBasis:"early_start",relationshipLagCalendar:"predecessor",totalFloatMethod:"finish_float",criticalActivityMethod:"total_float",criticalFloatThresholdHours:0,makeOpenEndedActivitiesCritical:!1,externalRelationshipPolicy:"SD_Both",calculateFloatBasedOn:"each_project",setDataDateAndPlannedStartToForecastStart:!1,projectMustFinishBy:null,projectForecastStart:null,multipleFloatPaths:{enabled:!1,limitEnabled:!1,maximum:nO,useTotalFloat:!0,endingActivityId:null}}}function us(t){return t===void 0||t===""?null:cs(t)}function ke(t){if(t==="Y")return!0;if(t==="N")return!1;Dn(`expected Y/N, got "${t}"`)}function zc(t,e){return Object.hasOwn(t,e)||Dn(`unknown enum "${e}"`),t[e]}function oO(t){let e=ke(t.sched_retained_logic),n=ke(t.sched_progress_override);return e&&n&&Dn("retained logic and progress override conflict"),e?"retained_logic":n?"progress_override":"actual_dates"}function sO(t,e){let n=eA(t,e);return n<0&&Dn(`${e} must be a non-negative number`),n}function eA(t,e){let n=Number(t);return(t===""||!Number.isFinite(n))&&Dn(`${e} must be a finite number`),n}function lO(t,e){let n=sO(t,e);return Number.isInteger(n)||Dn(`${e} must be an integer`),n}function cO(t,e){if(t==="")return null;e===void 0&&Dn("ending activity requires an ID resolver");let n=e(t);return n===null&&Dn(`unknown ending activity "${t}"`),n}function Dn(t){throw new Error(`${eO}: ${t}`)}function nA(t,e){let n=t.find(i=>i.type===k.PROJECT);if(n!==void 0)return n.calendarId;for(let i of e)if(i.is_default)return i.id;return null}function iA(t,e,n){let i=n.getCalendar(e);return i===null?null:ds(t,i)}var Jc=Symbol("ScheduleCore.fork.source"),dO=100;function uO(t){if(!Number.isInteger(t.offset)||t.offset<0)throw new RangeError("Ending activity offset must be a non-negative integer");if(!Number.isInteger(t.limit)||t.limit<1||t.limit>dO)throw new RangeError("Ending activity limit must be an integer from 1 to 100")}function pO(t){return{source:t,activities:[],links:[],calendars:[],trackingEvents:[]}}function fO(t){return t.kind===I.PERSISTENCE_ACKNOWLEDGE||t.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&t.acknowledgePersistedLookahead===!0}function yO(t){for(let e of t.activities)if(e.kind===x.DELETED||e.kind===x.UPDATED&&e.fields!==void 0&&"parentId"in e.fields)return!0;return!1}function hO(t,e){let n=[];for(let i of t.activities){let r=e.getActivity(i.id);if(r===null)return null;n.push(r)}return n}function mO(t,e,n){if(t===null||t.filter!==e)return!1;let i=t.context.hoursPerDay===n.hoursPerDay,r=t.context.locale===n.locale;return i&&r}var qi=class t{activities;links;calendars;selection;view;baselines;impactRequests;persistence;history;projection;criticalPath;diagnostics;dataDates=Hm({getSettings:()=>this._getP6Settings(),getProjectState:()=>this._getP6ProjectState(),getLatestRunLog:()=>this._getP6LatestRunLog(),getScheduleStateFingerprint:()=>this._getP6ScheduleStateFingerprint(),getDefaultSettings:()=>v(ps()),getScheduleReadiness:e=>this._getP6ScheduleReadiness(e),searchEndingActivities:e=>this._searchP6EndingActivities(e),getEndingActivityOption:e=>this._getP6EndingActivityOption(e),resolveMustFinishByDefault:e=>this._resolveP6MustFinishByDefault(e),updateSettings:e=>this._updateP6Settings(e),updateActivity:(e,n)=>this._updateP6Activity(e,n),schedule:e=>this._scheduleP6(e)});_activityClipboard={value:null};_status=Ie.READY;coreRuntime;_isFork;_undo=new Fo;_opQueue=Promise.resolve();_scheduleRevision=0;_stateRevision=0;_canonicalFingerprintCache=null;_p6ScheduleStateFingerprintCache=null;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(e){if(Object.assign(this,nd(this)),Jc in e){this._isFork=!0;let r=e[Jc],a=r.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new fi(a,r.coreRuntime.reporter),sector:v(r.coreRuntime.sector),activityIdGenerator:r.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:r.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:r.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:r.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(r.coreRuntime.calendars,([o,s])=>[o,v(s)])),baseCalendars:v(r.coreRuntime.baseCalendars),clock:r.coreRuntime.clock,reporter:r.coreRuntime.reporter,loadDiagnostics:r.coreRuntime.loadDiagnostics,externalRelationshipIds:v(r.coreRuntime.externalRelationshipIds),dataDateCapability:r.coreRuntime.dataDateCapability},this._activityClipboard.value=v(r._activityClipboard.value),this._undo=r._undo.fork(),this._saveTracker=r._saveTracker.fork(),this._scheduleRevision=r._scheduleRevision,this._stateRevision=r._stateRevision,this._canonicalFingerprintCache=r._canonicalFingerprintCache,this._p6ScheduleStateFingerprintCache=r._p6ScheduleStateFingerprintCache,this._pendingScheduleRevision=r._scheduleRevision,this._criticalPathRevision=r._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let n=qg(e);this.coreRuntime={state:n.state,scheduler:n.scheduler,sector:n.sector,activityIdGenerator:n.activityIdGen,linkIdGenerator:n.linkIdGen,uniqueCorrelativeIdGenerator:n.uidGen,customIdTracker:n.customIdTracker,clock:n.clock,calendars:new Map(n.calendars.map(r=>[r.id,r])),baseCalendars:n.baseCalendars,reporter:n.reporter,loadDiagnostics:n.loadDiagnostics,externalRelationshipIds:v(n.externalRelationshipIds),dataDateCapability:n.dataDateCapability},this._initPromise=n.initPromise.then(()=>{this._status!==Ie.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView(),this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.dataDateProjectState(),this.coreRuntime.state.dataDateLatestRunLog())}),this._criticalPathReady=this._initPromise.then(()=>this._startCriticalPathForCurrentRevision());let i=e.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 t({[Jc]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return v(this.coreRuntime.sector)}getLoadDiagnostics(){return this.assertReady(),this.coreRuntime.loadDiagnostics()}getActivityView(e){return this.assertReady(),kr(this.coreRuntime.state,e)}calculateCalendarEndDate(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.calculateEndDate({startDate:e.startDate,durationHours:e.durationHours,task:n}):null}calculateCalendarDuration(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.calculateDuration({startDate:e.startDate,endDate:e.endDate,task:n}):null}getClosestCalendarWorkTime(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e.activityId);return n?this.coreRuntime.state.getClosestWorkTime({date:e.date,dir:e.direction,task:n}):null}getProgressEditability(e){this.assertReady();let n=kr(this.coreRuntime.state,e);if(!n)return null;let i=No(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return Ai.canEdit(n,i.hierarchy)}getDateGestureEditability(e,n){this.assertReady();let i=kr(this.coreRuntime.state,e);return i?Gn(i.p6,this.coreRuntime.state.dataDateSettings(),n):null}getColumnEditability(e,n){this.assertReady();let i=kr(this.coreRuntime.state,e),r=_e(n);if(!i||!r)return null;let a=No(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat});return co(r.canEdit(i,a.hierarchy),i,this._getP6Settings(),n)}createDateGesturePreview(e){this.assertReady();let n=this._scheduleRevision;return yf(this.coreRuntime.state,e,()=>{if(this.assertReady(),this._scheduleRevision!==n)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),ih(this.coreRuntime.state)}getIndentTargetParentIds(e){this.assertReady();let n=Co(e.map(i=>String(i)),this.coreRuntime.state);return[...new Set(n.allowedMoves.map(i=>String(i.newParentId)))]}getChildrenView(e){return this.assertReady(),oh(this.coreRuntime.state,e)}getLinkView(e){return this.assertReady(),pc(this.coreRuntime.state,e)}getLinksForActivityView(e){this.assertReady();let n=this.coreRuntime.state,i=[],r=new Set,a=o=>{if(r.has(o))return;r.add(o);let s=pc(n,o);s&&i.push(s)};for(let o of n.getOutgoingLinkIds(e))a(o);for(let o of n.getIncomingLinkIds(e))a(o);return i}getAllLinksView(){return this.assertReady(),ch(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let e=this.coreRuntime.state,n=e.getAllLinks(),i=or(e,n),r=va(i),a=0;for(let o of r)o.length>a&&(a=o.length);return{activityCount:e.getAllIds().length,logicalLinkCount:n.length,effectiveEdgeCount:i.length,circularComponents:r,largestComponentSize:a}}getProperty(e,n){this.assertReady();let i=this.coreRuntime.state.getActivity(e);return i?v(i[n]):null}getAllIds(){return this.assertReady(),rh(this.coreRuntime.state)}forEachActivityId(e){this.assertReady(),ah(this.coreRuntime.state,e)}getChildrenIds(e){return this.assertReady(),uc(this.coreRuntime.state,e)}getSelectedActivityIds(){return this.assertReady(),sh(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let e=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(n=>!e.has(n))}getActiveFilter(){return this.assertReady(),v(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),v(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}getVisualRows(){return this.assertReady(),[...this.coreRuntime.state.getVisualRows()]}getActiveGroup(){return this.assertReady(),v(this.coreRuntime.state.getGroup())}getWbsDepth(){return this.assertReady(),this.coreRuntime.state.getWbsDepth()}hasChild(e){return this.assertReady(),lh(this.coreRuntime.state,e)}getCalendar(e){this.assertReady();let n=this.coreRuntime.calendars.get(e);return n?v(n):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),e=>v(e))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(e=>v(e))}isCustomIdInUse(e,n=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(e,n)}getProjectWorkHours(){return this.assertReady(),dh(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(e=>this.coreRuntime.state.getLink(e)).map(v)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(e=>this.coreRuntime.state.getLink(e)).map(v)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(e=>this.coreRuntime.state.getActivity(e)).map(v)}getModifiedActivityFields(){return this.assertReady(),v(this._saveTracker.modifiedActivityFields(e=>this.coreRuntime.state.getActivity(e)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(e=>this.coreRuntime.state.getActivity(e)).map(v)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getModifiedDataDateSettings(){return this.assertReady(),this._saveTracker.modifiedP6Settings()}getModifiedDataDateActivities(){return this.assertReady(),this._saveTracker.modifiedP6Activities(e=>this.coreRuntime.state.getActivity(e))}getScheduleRevision(){return this._scheduleRevision}getStateRevision(){return this._stateRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}readPersistenceCheckpoint(){return this.assertReady(),{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),historyBoundary:this.capturePersistenceHistoryBoundary(),...this.coreRuntime.dataDateCapability?.checkpoint(this.coreRuntime.state.dataDateSettings(),this.coreRuntime.state.dataDateProjectState()),...this.coreRuntime.dataDateCapability===null?{}:{p6LatestRunLog:v(this.coreRuntime.state.dataDateLatestRunLog())}}}getCanonicalDigest(){this.assertReady();let e=(r,a)=>String(r.id).localeCompare(String(a.id)),n=this._getP6Settings(),i=this._getP6ProjectState();return Tt({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(e),links:[...this.getAllLinksView()].sort(e),calendars:[...this.getAllCalendars()].sort(e),baseCalendars:[...this.getBaseCalendars()].sort(e),...n===null?{}:{p6Settings:n,p6ProjectState:i}})}getCanonicalFingerprint(){if(this._canonicalFingerprintCache?.stateRevision===this._stateRevision)return this._canonicalFingerprintCache.value;let e=Ic(this.getCanonicalDigest());return this._canonicalFingerprintCache={stateRevision:this._stateRevision,value:e},e}_getP6ScheduleStateFingerprint(){if(this._p6ScheduleStateFingerprintCache?.stateRevision===this._stateRevision)return this._p6ScheduleStateFingerprintCache.value;let e=this._computeP6ScheduleStateFingerprint();return this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:e},e}_computeP6ScheduleStateFingerprint(){let e=(r,a)=>String(r.id).localeCompare(String(a.id)),n=[...this.getAllActivitiesView()].sort(e).map(({criticalPath:r,freeSlackHours:a,isCritical:o,...s})=>this.coreRuntime.dataDateCapability?.fingerprintActivity(s)??s);return Ic(Tt({sector:this.getSector(),activities:n,links:[...this.getAllLinksView()].sort(e).map(({freeSlackHours:r,isCritical:a,...o})=>o),calendars:[...this.getAllCalendars()].sort(e),baseCalendars:[...this.getBaseCalendars()].sort(e),p6Settings:this._getP6Settings(),p6ProjectState:this._getP6ProjectState()}))}createProjectionChangeSetFrom(e){this.assertReady(),e.assertReady();let n=$c(this._snapshotProjection(),e._snapshotProjection()),i=this.coreRuntime.dataDateCapability??e.coreRuntime.dataDateCapability;return{...n,...i?.reconcile({settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState()},{settings:e.coreRuntime.state.dataDateSettings(),projectState:e.coreRuntime.state.dataDateProjectState()})}}_snapshotProjection(){return{activities:this.getAllActivitiesView(),links:this.getAllLinksView(),calendars:this.getAllCalendars(),selectedIds:this.getSelectedActivityIds(),hiddenIds:this.getHiddenActivityIds(),order:Xe(this.coreRuntime.state)}}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(e=>this.coreRuntime.state.getActivity(e)).map(v)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(e=>this.coreRuntime.state.getLink(e)).map(v)}_enqueue(e){let n=this._opQueue.then(e,e);return this._opQueue=n.then(()=>{},()=>{}),n}_getP6Settings(){return this.assertReady(),v(this.coreRuntime.state.dataDateSettings())}_getP6ProjectState(){return this.assertReady(),v(this.coreRuntime.state.dataDateProjectState())}_getP6LatestRunLog(){return this.assertReady(),v(this.coreRuntime.state.dataDateLatestRunLog())}_resolveP6MustFinishByDefault(e){this.assertReady();let n=nA(this.coreRuntime.state.getAllActivities(),this.coreRuntime.calendars.values());return iA(e,n,this.coreRuntime.state.calendarReader)}_searchP6EndingActivities(e){this.assertReady(),uO(e);let n=e.query.trim().toLowerCase(),i=[],r=0;for(let a of this.coreRuntime.state.getVisualOrderIds()){let o=this._getP6EndingActivityOption(a);if(!(!o||!o.label.toLowerCase().includes(n))&&!(r++<e.offset)){if(i.length===e.limit)return{items:i,hasMore:!0};i.push(o)}}return{items:i,hasMore:!1}}_getP6EndingActivityOption(e){this.assertReady();let n=this.coreRuntime.state.getActivity(e);if(!n)return null;let i=n.customId?.trim()||n.uniqueCorrelativeId||String(n.correlativeId);return{id:n.id,label:`${i} \u2014 ${n.name}`}}_getP6ScheduleReadiness(e){this.assertReady();let n=this.coreRuntime.dataDateCapability;return n===null?{ready:!1,code:"capability_not_enabled",count:0,sampleActivityIds:[],missingInputs:[]}:n.scheduleReadiness({settings:this.coreRuntime.state.dataDateSettings(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:e,activities:this.coreRuntime.state.getAllActivities(),projectState:this.coreRuntime.state.dataDateProjectState()})}_updateP6Settings(e){let n=this._admitScheduleMutation(),i=!1,r=!1,a=this._enqueue(async()=>{try{this.assertReady();let o=this._requireDataDateCapability().prepareSettingsUpdate(this.coreRuntime.state.dataDateSettings(),e),{before:s,after:l}=o,c={kind:Ht.P6_SETTINGS_UPDATE};if(!o.changed)return{changes:{source:c,activities:[],links:[],calendars:[],trackingEvents:[]}};let d=this._requireDataDateCapability(),u=d.prepareLiveDerived(this.coreRuntime.state,s,l),p=[...u.keys()],f=new Map(p.flatMap(m=>{let h=this.coreRuntime.state.getActivity(m);return h===null?[]:[[m,rt(h)]]}));this.coreRuntime.state.beginWriteCapture();let y;try{this.coreRuntime.state.setDataDateSettings(l),d.applyLiveDerived(this.coreRuntime.state,u),y={...await G(this.coreRuntime.state,{source:c,beforeSnap:f,touchedIds:p,scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),p6Settings:{before:s,after:l}}}catch(m){throw this._rollback(),m}finally{this.coreRuntime.state.endWriteCapture()}return this._undo.record(Bi(Lr(y))),this._saveTracker.recordChanges(y.activities,y.links,m=>this.coreRuntime.state.getActivity(m),m=>this.coreRuntime.state.getLink(m)),this._saveTracker.recordP6Settings(l),r=lt(s)&&!lt(l),this._recordDirectScheduleMutation(!r),i=!0,{changes:y}}finally{this._settleScheduleMutation(n,i)}});return a.then(()=>{r&&this.recomputeCriticalPath().catch(o=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after Data Date deactivation failed",o)})},()=>{}),a}_updateP6Activity(e,n){let i=this._admitScheduleMutation(),r=!1;return this._enqueue(async()=>{try{this.assertReady();let a=this._requireDataDateCapability(),o=a.requireSettings(this.coreRuntime.state.dataDateSettings()),s=this.coreRuntime.state.getActivity(e);if(s?.p6===void 0)throw new Error(`P6 activity ${e} does not exist`);let l=a.prepareActivityUpdate(s.p6,n,s.constraintType),c=this.coreRuntime.state.calendarReader.getCalendar(s.calendarId),d=lt(o)&&c!==null?a.projectLocalActivity(s.p6,l.next,{calendar:c,dataDate:o.dataDate,totalFloatMethod:o.totalFloatMethod}):{p6:l.next};if(!l.changed)return{changes:{source:{kind:Ht.P6_ACTIVITY_UPDATE},activities:[],links:[],calendars:[],trackingEvents:[]}};let u=new Map([[e,rt(s)]]);this.coreRuntime.state.beginWriteCapture();let p;try{this.coreRuntime.state.setActivityField(e,"p6",d.p6),d.startDate!==void 0&&this.coreRuntime.state.setActivityField(e,"startDate",d.startDate),d.endDate!==void 0&&this.coreRuntime.state.setActivityField(e,"endDate",d.endDate),(d.startDate!==void 0||d.endDate!==void 0)&&await we(this.coreRuntime.state,new Set([e]),!1),p=await G(this.coreRuntime.state,{source:{kind:Ht.P6_ACTIVITY_UPDATE},beforeSnap:u,touchedIds:[e],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}catch(f){throw this._rollback(),f}finally{this.coreRuntime.state.endWriteCapture()}return this._undo.record(Bi(Lr(p))),this._saveTracker.recordChanges(p.activities,p.links,f=>this.coreRuntime.state.getActivity(f),f=>this.coreRuntime.state.getLink(f)),this._recordDirectScheduleMutation(!0),r=!0,{changes:p}}finally{this._settleScheduleMutation(i,r)}})}_scheduleP6(e){let n=this._admitScheduleMutation(),i=!1;return this._enqueue(async()=>{try{let r=await this._runP6Schedule(e);return i=this._changeSetIsSubstantive(r.changes),r}finally{this._settleScheduleMutation(n,i)}})}async _runP6Schedule(e){this.assertReady();let n=this._requireDataDateCapability().prepareSchedule({state:this.coreRuntime.state,settings:this.coreRuntime.state.dataDateSettings(),projectState:this.coreRuntime.state.dataDateProjectState(),externalRelationshipIds:this.coreRuntime.externalRelationshipIds,patch:e,sector:this.coreRuntime.sector}),{settings:i,projectState:r,calculated:a,projection:o,changeSetContribution:s}=n,l=new Map;for(let p of a.activities.keys()){let f=this.coreRuntime.state.getActivity(p);f!==null&&l.set(p,rt(f))}this.coreRuntime.state.beginWriteCapture();let c,d,u;try{this.coreRuntime.state.setDataDateSettings(i),this.coreRuntime.state.setDataDateProjectState(r),this._requireDataDateCapability().applyScheduleProjection(this.coreRuntime.state,o),await we(this.coreRuntime.state,new Set(a.activities.keys()),!1),c={...await G(this.coreRuntime.state,{source:{kind:Ht.P6_SCHEDULE},beforeSnap:l,touchedIds:a.activities.keys(),scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),...s},d=[...a.activities.keys()].flatMap(f=>{let y=this.coreRuntime.state.getActivity(f);return y===null?[]:[rt(y)]}),u={schemaVersion:1,calculatedAt:this.coreRuntime.clock?.()??null,dataDate:v(i.dataDate),project:{projectId:String(this.coreRuntime.sector.projectId),scheduleId:String(this.coreRuntime.sector.id),scheduleCode:this.coreRuntime.sector.name,scheduleName:this.coreRuntime.sector.name},settings:v(i),statistics:{calculatedActivityCount:d.length,criticalActivityCount:a.criticalPath.length,warningCount:a.warnings.length},warnings:v(a.warnings),scheduleDigest:this._computeP6ScheduleStateFingerprint()},this.coreRuntime.state.setDataDateLatestRunLog(u)}catch(p){throw this._rollback(),p}finally{this.coreRuntime.state.endWriteCapture()}return this._changeSetIsSubstantive(c)&&(this._undo.record(Bi(Lr(c))),this._saveTracker.recordChanges(c.activities,c.links,p=>this.coreRuntime.state.getActivity(p),p=>this.coreRuntime.state.getLink(p)),this._saveTracker.recordP6Settings(i),this._saveTracker.recordP6ProjectState(r),this._recordDirectScheduleMutation(!0)),this._p6ScheduleStateFingerprintCache={stateRevision:this._stateRevision,value:u.scheduleDigest},this._saveTracker.recordP6LatestRunLog(u),{changes:c,calculatedActivities:d,criticalPath:[...a.criticalPath],warnings:[...a.warnings],log:u}}_requireDataDateCapability(){let e=this.coreRuntime.dataDateCapability;if(e===null)throw new ce("capability_not_enabled","P6 capability is not enabled for this Schedule");return e}_changeSetIsSubstantive(e){return Sh(e,this._hasDataDateChanges(e))}_hasDataDateChanges(e){return this.coreRuntime.dataDateCapability?.changeSetIsSubstantive(e)??!1}_applyDataDateChangeSet(e,n){this.coreRuntime.dataDateCapability?.applyChangeSet(e,n,{setSettings:i=>{this.coreRuntime.state.setDataDateSettings(i)},setProjectPlannedStart:i=>{this._setP6ProjectPlannedStart(i)}})}async _applyDataDateActivationProjection(e,n){let i=this.coreRuntime.dataDateCapability,r=this.coreRuntime.state.dataDateSettings();if(i===null||e===null||r===null)return[];let a=i.prepareLiveDerived(this.coreRuntime.state,e,r);return a.size===0?[]:this._assembleDataDateActivationProjection(i,a,n)}async _assembleDataDateActivationProjection(e,n,i){let r=[...n.keys()],a=this._snapshotActivities(r);this.coreRuntime.state.beginWriteCapture();try{return e.applyLiveDerived(this.coreRuntime.state,n),(await G(this.coreRuntime.state,{source:{kind:i},beforeSnap:a,touchedIds:r,scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})).activities}catch(o){throw this._rollback(),o}finally{this.coreRuntime.state.endWriteCapture()}}_snapshotActivities(e){return new Map(e.flatMap(n=>{let i=this.coreRuntime.state.getActivity(n);return i===null?[]:[[n,rt(i)]]}))}_setP6ProjectPlannedStart(e){let n=this.coreRuntime.state.dataDateProjectState();n!==null&&this.coreRuntime.state.setDataDateProjectState({...n,plannedStart:e})}_beginScheduleMutation(e){return Dr(e)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(e,n){e&&(n||(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(e,n={}){let i=this._beginScheduleMutation(e);return this._enqueue(()=>this._dispatchInner(e,n,i))}async dispatchMany(e,n={}){let i=e.some(Dr)?this._admitScheduleMutation():!1;return this._enqueue(()=>this._dispatchManyInner(e,n,i))}async applyActivityBatch(e,n={}){let i=this._beginScheduleMutation(e);return this._enqueue(()=>this._dispatchInner(e,n,i))}planLookaheadConversion(e){return this.assertReady(),Wl(e,{adapter:this.coreRuntime.state,stateRevision:this._stateRevision})}applyLookaheadConversion(e){return this.dispatch({...e,kind:I.ACTIVITY_LOOKAHEAD_CONVERT})}async _dispatchInner(e,n={},i=!1){let r=!1;try{let a=await this._runDispatch(e,n);return r=a.changedState,a.result}finally{this._settleScheduleMutation(i,r)}}async _dispatchManyInner(e,n,i){let r=this._snapshotProjection(),a={...n,skipAutoSchedule:!0,skipCriticalPath:!0},o=[],s=[],l=[],c=!1,d=!1,u,p=!1,f=null,y=!1,m=!1;try{for(let h of e){if(h.kind===I.SCHEDULE_AUTO_SCHEDULE){if(h.activityId!==void 0&&!this.coreRuntime.state.activityExists(h.activityId)){o.push({ok:!1,reason:_.ACTIVITY_NOT_FOUND});continue}let T=pO(h);o.push({ok:!0,changes:T}),s.push(T),l.push(h),d=!0,h.activityId===void 0||u!==void 0&&u!==h.activityId?p=!0:u=h.activityId;continue}let A=await this._runDispatch(h,a,!0);o.push(A.result),A.result.ok&&(s.push(A.result.changes),l.push(h)),A.changedState&&(c=!0,d=!0,p=!0)}if(d){let h=p||u===void 0?{kind:I.SCHEDULE_AUTO_SCHEDULE}:{kind:I.SCHEDULE_AUTO_SCHEDULE,activityId:u},A=await this._runDispatch(h,n,!0);A.result.ok&&(f=A.result.changes,s.push(A.result.changes),y=n.skipAutoSchedule!==!0),c||=A.changedState}return c&&this._recordScheduleMutation(f!==null&&n.skipAutoSchedule!==!0&&n.skipCriticalPath!==!0),m=!0,{results:o,autoScheduled:y,changeSet:this._aggregateDispatchManyChangeSets(r,s,l)}}finally{!m&&c&&this._recordScheduleMutation(!1),this._settleScheduleMutation(i,m&&c)}}_aggregateDispatchManyChangeSets(e,n,i){if(n.length===0)return null;let r=$c(this._snapshotProjection(),e),a=n.flatMap(s=>s.effects??[]),o=n.flatMap(s=>s.warnings??[]);return{...r,source:{kind:Ht.DISPATCH_MANY,actions:i},trackingEvents:n.flatMap(s=>s.trackingEvents),...a.length===0?{}:{effects:a},...o.length===0?{}:{warnings:o}}}async _runDispatch(e,n,i=!1){if(this.assertReady(),this._isFork&&fO(e))return{result:{ok:!1,reason:_.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let r=No(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),a=Ih(e),o=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,l;try{s=await Ly(e,n,{adapter:this.coreRuntime.state,ctx:r,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:u=>this._saveTracker.hasCheckpointActivityId(u),isLinkIdReserved:u=>this._saveTracker.hasCheckpointLinkId(u),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,stateRevision:this._stateRevision,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(u=>u.baseDefault)?.id??null,hasCompleteSchedulingState:this.coreRuntime.state.dataDateSettings()!==null&&this.coreRuntime.state.hasCompleteSchedulingState(),dataDateCapability:this.coreRuntime.dataDateCapability,dataDateSettings:this.coreRuntime.state.dataDateSettings(),now:this.coreRuntime.clock?Ma(this.coreRuntime.clock()):null});let d=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;d&&d.size>0&&(l=new Map(d)),s.ok||this._rollback(o)}catch(d){throw this._rollback(o),d}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&a===Hi.RECORD&&this._changeSetIsSubstantive(s.changes)){let d=hh(this.coreRuntime.state,s.changes),u=l?new Map(Array.from(l.keys(),p=>[p,this.coreRuntime.state.getProgressFallback(p)])):void 0;this._undo.record({...Bi(Lr(s.changes),s.__beforeSnap,s.__beforeLinks,d.afterSnap,d.afterLinks,l,u),...lt(this.coreRuntime.state.dataDateSettings())?{beforeLinks:v(s.__beforeLinks),afterLinks:v(d.afterLinks)}:{}},mh(e),Date.now())}if(s.ok)if(a===Hi.CHECKPOINT_ON_SUCCESS){if(e.kind!==I.PERSISTENCE_ACKNOWLEDGE)throw new Error("checkpoint-on-success requires persistence acknowledge");let d=this.coreRuntime.state.getAllActivities(),u=this.coreRuntime.state.getAllLinks(),p=e.checkpoint,f=p?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(p?.activities??d,p?.links??u,e.activities,e.links,d,u,p?.p6Settings??this.coreRuntime.state.dataDateSettings(),p?.p6ProjectState===void 0?this.coreRuntime.state.dataDateProjectState():p.p6ProjectState,p?.p6LatestRunLog===void 0?this.coreRuntime.state.dataDateLatestRunLog():p.p6LatestRunLog),this._undo.discardThrough(f),this._undo.applyPersistedIdentities(e.activities??[],e.links??[])}else e.kind===I.ACTIVITY_LOOKAHEAD_SYNC&&e.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,d=>this.coreRuntime.state.getActivity(d)),e.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,d=>this.coreRuntime.state.getActivity(d),d=>this.coreRuntime.state.getLink(d));if(s=this._withReappliedViewState(e,s),!s.ok)return{result:s,changedState:!1};let c=this._changeSetIsSubstantive(s.changes);return c&&this._stateRevision++,Dr(e)&&c?(i||this._recordScheduleMutation(n.skipAutoSchedule!==!0&&n.skipCriticalPath!==!0&&Yn(e)),{result:rA(s),changedState:!0}):{result:rA(s),changedState:!1}}recomputeCriticalPath(){let e=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:n})=>n);return this._criticalPathReady=e,e}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(e,n){if(!n.ok||(e.kind===I.VISIBILITY_SET&&this.coreRuntime.state.setFilterProjection(null),!Zp(e)))return n;let i=this._reapplyViewState(n.changes);return i===null?n:{...n,changes:i}}_reapplyViewState(e){let n=this._reapplyActiveFilter(e),i=this._emitTouchedBranchOrder(n??e);return this._reapplyActiveOrder(i.changes??n??e,i.touchedParents)??i.changes??n}_emitTouchedBranchOrder(e){let n=this.coreRuntime.state,i=Dh(e,a=>n.getParentId(a));if(n.getActiveOrder()!==null)return{changes:null,touchedParents:i};if(i.size===0)return{changes:null,touchedParents:i};let r=Es(n,i);return r.length===0?{changes:null,touchedParents:i}:{changes:{...e,order:r},touchedParents:i}}_reapplyActiveOrder(e,n){let i=this.coreRuntime.state;if(i.getActiveOrder()===null)return null;if(i.invalidateDerivedOrder(),e.links.length>0||e.calendars.length>0)return{...e,order:Xe(i)};let a=new Set(n);for(let s of e.activities){if(s.kind===x.DELETED)return{...e,order:Xe(i)};let l=i.getParentId(s.id);a.add(l===null?"0":String(l))}let o=Es(i,a);return o.length===0?null:{...e,order:o}}_reapplyActiveFilter(e){let n=this.coreRuntime.state,i=n.getActiveFilter();if(i===null)return null;let r=bn(this.coreRuntime.sector.hoursPerDay),a=n.getFilterProjection(),o=mO(a,i,r),s=yO(e)?null:hO(e,n),l,c;if(s===null||!o){let p=sa({activities:n.getAllActivities(),parentOf:f=>n.getParentId(f),filter:i,context:r,viewAttributeCatalogs:n.getViewAttributeCatalogMap()});n.setFilterProjection(p),c=p.visibleIds,l=n.getAllIds()}else l=Ad(a,s,p=>n.getParentId(p)),c=a.visibleIds;let u=Rn(n,c,l);return u.length===0?null:{...e,viewState:[...e.viewState??[],...u]}}_recordScheduleMutation(e){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),e&&(this._criticalPathRevision=this._scheduleRevision)}_recordDirectScheduleMutation(e){this.coreRuntime.dataDateCapability!==null&&this._stateRevision++,this._recordScheduleMutation(e)}_startCriticalPathForCurrentRevision(){if(this._status===Ie.DESTROYED)return Promise.resolve(null);if(lt(this.coreRuntime.state.dataDateSettings()))return this._criticalPathRevision=this._scheduleRevision,Promise.resolve(null);let e=this._scheduleRevision;if(this._criticalPathRevision===e)return Promise.resolve(null);if(this._activeCriticalPath?.revision===e)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let n={cancelled:!1},i=new Ui(wo(this.coreRuntime.state.getAllActivities().map(s=>rt(s)),this.coreRuntime.state.getAllLinks().map(s=>({...s})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),r=()=>!n.cancelled&&this._status!==Ie.DESTROYED&&this._scheduleRevision===e&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let s=await Sl(i,this.coreRuntime.sector.hoursPerDay,r);return!r()||s===null?null:this._enqueue(async()=>{if(!r())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let l;try{for(let[c,d]of s.activities)Al(this.coreRuntime.state,c,d);for(let[c,d]of s.links)Il(this.coreRuntime.state,c,d);l=await G(this.coreRuntime.state,{source:{kind:Ht.INIT},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=e}catch(c){throw this._rollback(),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:l}})})();this._activeCriticalPath={revision:e,cancellation:n,promise:a};let o=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(o,o),a}undo(e={}){let n=this._admitScheduleMutation(),i=!1,r=this._enqueue(async()=>{try{return await this._runUndo(e,a=>{i=a})}finally{this._settleScheduleMutation(n,i)}});return r.then(a=>{let o=a!==null&&this._hasDataDateChanges(a)&<(this.coreRuntime.state.dataDateSettings());a&&!o&&e.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),r}async _runUndo(e,n){{if(this.assertReady(),e.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==e.expectedUndoDepth)return null;let i=this._undo.takeUndo();if(!i)return null;let r=v(this.coreRuntime.state.dataDateSettings()),a;try{hc(this.coreRuntime.state,i,(l,c)=>this._applyDataDateChangeSet(l,c)),a=await this._applyDataDateActivationProjection(r,Ht.UNDO)}catch(l){throw mc(this.coreRuntime.state,i,(c,d)=>this._applyDataDateChangeSet(c,d)),this._undo.restoreTakenUndo(i),l}this._recordDirectScheduleMutation(this._hasDataDateChanges(i.changeSet)&<(this.coreRuntime.state.dataDateSettings())),n(!0),fc(i)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(i),this._undo.resetCoalesce();let o=yc(this.coreRuntime.state,i,At.BEFORE,l=>this.coreRuntime.dataDateCapability?.historyContribution(i.changeSet,l)??{}),s={...o,activities:[...o.activities,...a]};return this._saveTracker.recordChanges(s.activities,s.links,l=>this.coreRuntime.state.getActivity(l),l=>this.coreRuntime.state.getLink(l)),this._saveTracker.recordP6Settings(this.coreRuntime.state.dataDateSettings()),this._saveTracker.recordP6ProjectState(this.coreRuntime.state.dataDateProjectState()),this._reapplyViewState(s)??s}}redo(e={}){let n=this._admitScheduleMutation(),i=!1,r=this._enqueue(async()=>{try{return await this._runRedo(a=>{i=a})}finally{this._settleScheduleMutation(n,i)}});return r.then(a=>{let o=a!==null&&this._hasDataDateChanges(a)&<(this.coreRuntime.state.dataDateSettings());a&&!o&&e.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",s)})},()=>{}),r}async _runRedo(e){this.assertReady();let n=this._undo.takeRedo();if(!n)return null;let i=v(this.coreRuntime.state.dataDateSettings()),r;try{mc(this.coreRuntime.state,n,(s,l)=>this._applyDataDateChangeSet(s,l)),r=await this._applyDataDateActivationProjection(i,Ht.REDO)}catch(s){throw hc(this.coreRuntime.state,n,(l,c)=>this._applyDataDateChangeSet(l,c)),this._undo.restoreTakenRedo(n),s}this._recordDirectScheduleMutation(this._hasDataDateChanges(n.changeSet)&<(this.coreRuntime.state.dataDateSettings())),e(!0),fc(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(n),this._undo.resetCoalesce();let a=yc(this.coreRuntime.state,n,At.AFTER,s=>this.coreRuntime.dataDateCapability?.historyContribution(n.changeSet,s)??{}),o={...a,activities:[...a.activities,...r]};return this._saveTracker.recordChanges(o.activities,o.links,s=>this.coreRuntime.state.getActivity(s),s=>this.coreRuntime.state.getLink(s)),this._saveTracker.recordP6Settings(this.coreRuntime.state.dataDateSettings()),this._saveTracker.recordP6ProjectState(this.coreRuntime.state.dataDateProjectState()),this._reapplyViewState(o)??o}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=Ie.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Uo;assertReady(){if(this._status===Ie.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===Ie.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(e){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.scheduler.invalidateAllCaches(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),e&&(this.coreRuntime.activityIdGenerator.restore(e[0]),this.coreRuntime.linkIdGenerator.restore(e[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(e[2]))}catch(n){throw this._status=Ie.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",n),n}}};function rA(t){let{__beforeSnap:e,__beforeLinks:n,...i}=t;return i}async function aA(t){let e=new qi(t);return await e.ready,e}var oA=(t=[])=>(t??[]).filter(e=>!e.proplannerId);var Wr=class extends Error{constructor(n){super(n);this.code=n;this.name="LookaheadActualTransitionError"}code},gO=/^(\d{4})-(\d{2})-(\d{2})$/;function fs(t){Xc(t.timeSource)||Se("INVALID_ACTUAL_TIME_SOURCE");let e=AO(t.selectedDay),[n,i,r]=e,a=new Date(t.timeSource);return a.setUTCFullYear(n,i-1,r),vO(a,e)||Se("INVALID_ACTUAL_DAY"),a}function AO(t){let e=gO.exec(t);return e||Se("INVALID_ACTUAL_DAY"),[Number(e[1]),Number(e[2]),Number(e[3])]}function Zc(t){if(SO(t),t.dataDate===null)return{start:null,finish:null,uncomplete:null};let e=t.activity.executionStatus===et.NOT_STARTED&&t.nextProgress>0?{required:!0,suggestedAt:new Date(t.dataDate)}:null,n=t.activity.executionStatus!==et.COMPLETED&&t.nextProgress===100?{optional:!0,suggestedAt:t.displayedFinish?new Date(t.displayedFinish):null}:null,i=t.activity.executionStatus===et.COMPLETED&&t.activity.actualFinish!==null&&t.nextProgress<100?{required:!0,removes:new Date(t.activity.actualFinish)}:null;return{start:e,finish:n,uncomplete:i}}function sA(t){let e=Zc(t);t.dataDate===null&&CO(t.intent)&&Se("DATA_DATE_INACTIVE"),e.start&&t.intent?.actualStart===void 0&&Se("ACTUAL_START_REQUIRED"),t.intent?.actualFinish instanceof Date&&t.nextProgress!==100&&Se("ACTUAL_FINISH_REQUIRES_100"),e.uncomplete&&t.intent?.actualFinish!==null&&Se("ACTUAL_FINISH_REMOVAL_REQUIRED"),!e.uncomplete&&t.intent?.actualFinish===null&&Se("ACTUAL_FINISH_REMOVAL_NOT_APPLICABLE");let n=Jo(t.activity,t.intent??{});return t.dataDate===null?n:IO(t.activity,n,t.nextProgress)}function IO(t,e,n){if((e.executionStatus??t.executionStatus)!==et.IN_PROGRESS)return e;switch(t.percentCompleteType){case ht.PHYSICAL:return{...e,physicalPercentComplete:n};case ht.DURATION:return{...e,remainingDurationHours:t.originalDurationHours*(1-n/100)};default:return e}}function SO(t){(!Number.isFinite(t.nextProgress)||t.nextProgress<0||t.nextProgress>100)&&Se("INVALID_PROGRESS"),t.dataDate!==null&&!Xc(t.dataDate)&&Se("INVALID_DATA_DATE"),t.displayedFinish!=null&&!Xc(t.displayedFinish)&&Se("INVALID_DISPLAYED_FINISH")}function Xc(t){return t instanceof Date&&Number.isFinite(t.getTime())}function vO(t,[e,n,i]){return t.getUTCFullYear()===e&&t.getUTCMonth()===n-1&&t.getUTCDate()===i}function CO(t){return t?.actualStart!==void 0||t?.actualFinish!==void 0}function Se(t){throw new Wr(t)}function lA(t){return fs({selectedDay:t.selectedDay,timeSource:t.expectedFinish??t.displayedFinish})}function cA(t){let e=jo([...t.calendars],void 0,t.baseCalendars===void 0?void 0:[...t.baseCalendars]),{reader:n}=Po(gc(e.calendars,e.baseCalendars));return{derive({previous:i,next:r,calendarId:a,dataDate:o,totalFloatMethod:s}){if(!un(r))return null;let l=a!==null&&e.knownCalendarIds.has(a)?a:e.defaultCalendarId,c=n.getCalendar(l);if(!c)return null;let{p6:d}=Qo(i,r,{calendar:c,dataDate:o,...s===void 0?{}:{totalFloatMethod:s}});return{actualDurationHours:d.actualDurationHours,atCompletionDurationHours:d.atCompletionDurationHours,durationPercentComplete:d.durationPercentComplete,unitsPercentComplete:d.unitsPercentComplete,schedulePercentComplete:d.schedulePercentComplete}}}}var ct=t=>{let e=t.lifecycle??(t.classification==="f9_output"?"f9":"explicit_edit");return{...t,lifecycle:e,changesWhen:DO(e),f9Behavior:TO(e),persistence:"Persist exact null/zero/signed scalar or exact UTC instant; save/reload is lossless.",nullAndZero:t.typeAndUnit.includes("UTC")?"null means absent; midnight is a real exact UTC instant.":t.typeAndUnit.includes("boolean")?"false is a real value and is never normalized to null.":"null means unavailable when allowed; numeric zero and signed values are preserved.",calendarRule:t.typeAndUnit.includes("working hours")||t.classification==="derived"?"Use the activity calendar, including shifts and exceptions; never local wall-clock subtraction.":"No calendar arithmetic; date values cross boundaries as exact UTC components.",status:t.status??(e==="open"?"PARTIAL":"VERIFIED"),edgeCases:t.edgeCases??{}}};function DO(t){return t==="f9"?"Changes only during explicit P6 F9 and its atomic Undo/Redo replay.":t==="dependency_change"?"Changes when Data Date moves from one valid instant to another in the same canonical mutation, without running F9.":t==="open"?"Formula is known; immediate pre-F9 refresh timing remains open pending a discriminant P6 observation.":"Changes on an authorized import or explicit user edit; open/save/reload do not calculate it."}function TO(t){return t==="explicit_edit"?"Preserved as scheduling reality/input unless the documented P6 algorithm consumes the input without rewriting it.":t==="open"?"Recalculated by F9; whether dependency edits refresh it earlier is not yet certified.":"Recalculated by Schedule Core; no frontend or backend formula is authoritative."}var Tn="src/p6/api.test.ts; src/p6/testing/p6-data-date/property-coverage.test.ts",Ve="src/p6/testing/p6-data-date/fixtures/obdd-math/obdd-math-before-f9.xer",zi="src/p6/testing/p6-floats/obdd-floats.schedule.test.ts",Ji="src/p6/testing/p6-floats/fixtures/obdd-floats-smallest.xer",Ke="src/p6/derived.test.ts",_n="src/p6/testing/p6-derived/fixtures/obdd-derived-edges.p6.json",_O={notStarted:"0 hours.",inProgress:"Working time from Actual Start to Data Date, excluding a valid Suspend/Resume interval.",completed:"Working time from Actual Start to Actual Finish.",zeroDuration:"0 hours.",zeroDenominator:"Not applicable; no division.",suspendResume:"Subtract only the overlap of Suspend..Resume with the measured actual interval.",calendarException:"Exception time contributes only when the activity calendar marks it workable.",signedValues:"Invalid negative duration inputs are rejected; P6 clamps a reversed Actual Start/end interval to 0 hours.",nullValue:"Missing required actual endpoint yields 0 under the P6 status contract.",milestone:"0 hours when the actual endpoints coincide."},EO={notStarted:"Working duration Planned Start..Planned Finish.",inProgress:"Working duration Actual Start..Remaining Early Finish, excluding Suspend/Resume.",completed:"Working duration Actual Start..Actual Finish.",zeroDuration:"0 hours.",zeroDenominator:"Not applicable; no division.",suspendResume:"Subtract the suspended overlap from the selected endpoint interval.",calendarException:"Measured with shifts and exceptions from the activity calendar.",signedValues:"P6 clamps a chronologically reversed Actual Start/selected finish interval to 0 hours.",nullValue:"Missing required endpoints yields 0 for the matching status branch.",milestone:"0 hours for coincident endpoints."},PO={notStarted:"(Original - Remaining) / Original \xD7 100, normally 0.",inProgress:"(Original - Remaining) / Original \xD7 100, clamped to 0..100.",completed:"Same formula; P6 completed input normally has zero Remaining.",zeroDuration:"0%, including a zero-duration milestone.",zeroDenominator:"0%, never NaN or Infinity.",suspendResume:"No direct effect; only duration inputs affect the percentage.",calendarException:"No direct effect after durations are canonical working hours.",signedValues:"Negative/non-finite duration inputs are rejected.",nullValue:"Duration inputs are required canonical scalars, not nullable.",milestone:"0% for zero Original Duration under the certified P6 golden."},RO={notStarted:"Actual units are normally zero; result is 0%.",inProgress:"100 \xD7 (actual labor + actual nonlabor) / (actual + remaining units).",completed:"100% when remaining units are zero and actual units are positive.",zeroDuration:"Independent of duration; units still control the result.",zeroDenominator:"0%, never NaN or Infinity.",suspendResume:"No direct effect.",calendarException:"No direct effect on already canonical assignment scalars.",signedValues:"Finite negative unit scalars are preserved; P6 can produce percentages below 0% or above 100%. Non-finite inputs are rejected.",nullValue:"Canonical TASK unit scalars are required; missing assignment totals hydrate as zero.",milestone:"0% with no units; otherwise the same units formula."},kO={notStarted:"0% when Data Date is at or before primary baseline start.",inProgress:"Baseline working time elapsed through Data Date divided by total baseline working time.",completed:"100% when Data Date is at or after primary baseline finish.",zeroDuration:"0% before the coincident endpoint and 100% at or after it.",zeroDenominator:"0% when signed baseline working duration is non-positive.",suspendResume:"No direct effect; baseline dates and Data Date are authoritative.",calendarException:"Elapsed and total durations use the activity calendar exception set.",signedValues:"Result is clamped to 0..100; P6 UI does not allow an inverted assigned baseline.",nullValue:"When neither primary baseline endpoint is assigned, P6 uses Current Project planned dates; one missing endpoint or missing effective planned dates returns null.",milestone:"Boundary result is determined by Data Date relative to the coincident baseline endpoints."},LO={notStarted:"Calculated from remaining early and late endpoints.",inProgress:"Same remaining endpoint formula after the selected OOS policy forward/backward passes.",completed:"null when no remaining endpoints exist.",zeroDuration:"Can be positive, zero or negative; milestone duration does not erase float.",zeroDenominator:"Not applicable; no division.",suspendResume:"Affects scheduled endpoints before float is measured.",calendarException:"Start and finish float use signed working time on the activity calendar.",signedValues:"Negative float is preserved exactly; -0 normalizes to numeric 0.",nullValue:"null when required start/finish endpoints for the selected method are absent.",milestone:"Measured between coincident remaining endpoint and its late endpoint."},ve=(t,e)=>`Input: canonical activities, relationships, Data Date and settings; phase: ${t}; policy: retained logic/progress override/actual dates relation classification; constraint: primary, secondary and project bounds; calendar: activity and configured lag calendars with exceptions; result: ${e}.`,dA=Object.freeze([ct({uiName:"Actual Start",property:"actualStart",xerField:"TASK.act_start_date",xmlField:"Activity.ActualStart",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"controlled",authority:"Imported/user-confirmed actual reality",phase:"input",algorithm:"Input only; status validation may infer status but F9 never moves it.",interactions:"Activity Status, Actual Finish, Actual Duration and OOS policy.",unitTest:Tn,p6Golden:Ve}),ct({uiName:"Actual Finish",property:"actualFinish",xerField:"TASK.act_end_date",xmlField:"Activity.ActualFinish",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"controlled",authority:"Imported/user-confirmed actual reality",phase:"input",algorithm:"Input only; completed status requires a consistent actual endpoint; F9 never moves it.",interactions:"Activity Status, Actual Start and Actual Duration.",unitTest:Tn,p6Golden:Ve}),ct({uiName:"Planned Start",property:"plannedStart",xerField:"TASK.target_start_date",xmlField:"Activity.PlannedStart",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Initial planning input; never replaced by projected Start.",interactions:"At Completion Duration and not-started fallback.",unitTest:Tn,p6Golden:Ve}),ct({uiName:"Planned Finish",property:"plannedFinish",xerField:"TASK.target_end_date",xmlField:"Activity.PlannedFinish",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Initial planning input; never replaced by projected Finish.",interactions:"At Completion Duration and not-started fallback.",unitTest:Tn,p6Golden:Ve}),ct({uiName:"Remaining Duration",property:"remainingDurationHours",xerField:"TASK.remain_drtn_hr_cnt",xmlField:"Activity.RemainingDuration",classification:"editable_input",typeAndUnit:"number, working hours",editability:"editable",authority:"Imported/user input consumed by explicit F9",phase:"input",algorithm:"Forward pass consumes/preserves remaining working hours according to status and OOS policy.",interactions:"Remaining Early Finish, Actual/At Completion Duration and Duration %.",unitTest:Tn,p6Golden:Ve}),ct({uiName:"Activity Status",property:"executionStatus",xerField:"TASK.status_code",xmlField:"Activity.Status",classification:"reality",typeAndUnit:"not_started | in_progress | completed",editability:"controlled",authority:"Actual-date/status invariant",phase:"input",algorithm:"Validated before F9; scheduling never invents actual dates.",interactions:"Actual endpoints, Remaining Duration and all derived duration fields.",unitTest:"src/p6/status.test.ts",p6Golden:Ve}),ct({uiName:"Expected Finish",property:"expectedFinish",xerField:"TASK.expect_end_date",xmlField:"Activity.ExpectedFinish",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input plus useExpectedFinishDates setting",phase:"input",algorithm:"Forward bound only when the project setting enables Expected Finish dates.",interactions:"Use Expected Finish Dates and Remaining Early Finish.",unitTest:"src/p6/testing/p6-native/obdd-native.schedule.test.ts",p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step24-expected-finish-calendar-exception.xer"}),ct({uiName:"Suspend Date",property:"suspendDate",xerField:"TASK.suspend_date",xmlField:"Activity.SuspendDate",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user actual reality",phase:"input",algorithm:"Preserved; duration derivation subtracts the valid Suspend..Resume overlap.",interactions:"Resume Date, Actual Duration and At Completion Duration.",unitTest:Ke,p6Golden:_n}),ct({uiName:"Resume Date",property:"resumeDate",xerField:"TASK.resume_date",xmlField:"Activity.ResumeDate",classification:"reality",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user actual reality",phase:"input",algorithm:"Preserved; duration derivation subtracts the valid Suspend..Resume overlap.",interactions:"Suspend Date, Actual Duration and At Completion Duration.",unitTest:Ke,p6Golden:_n}),ct({uiName:"Secondary Constraint",property:"secondaryConstraintType",xerField:"TASK.cstr_type2",xmlField:"Activity.SecondaryConstraintType",classification:"editable_input",typeAndUnit:"canonical P6 constraint enum | null",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Constraint classifier applies the declared start/finish lower/upper bound during forward/backward passes.",interactions:"Secondary Constraint Date, primary constraint and calendars.",unitTest:Tn,p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step18-secondary-finish-on-or-after.xer"}),ct({uiName:"Secondary Constraint Date",property:"secondaryConstraintDate",xerField:"TASK.cstr_date2",xmlField:"Activity.SecondaryConstraintDate",classification:"editable_input",typeAndUnit:"Date | null, exact UTC instant",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Provides the exact bound for Secondary Constraint Type; ignored when type is null.",interactions:"Secondary Constraint Type and early/late passes.",unitTest:Tn,p6Golden:"src/p6/testing/p6-native/fixtures/obdd-native-step18-secondary-finish-on-or-after.xer"}),ct({uiName:"Percent Complete Type",property:"percentCompleteType",xerField:"TASK.complete_pct_type",xmlField:"Activity.PercentCompleteType",classification:"editable_input",typeAndUnit:"duration | units | physical",editability:"editable",authority:"Imported/user input",phase:"input",algorithm:"Selects displayed progress authority; individual derived percentages remain independently calculated.",interactions:"Physical %, Duration %, Units % and progress projection.",unitTest:Ke,p6Golden:_n}),ct({uiName:"Physical % Complete",property:"physicalPercentComplete",xerField:"TASK.phys_complete_pct",xmlField:"Activity.PhysicalPercentComplete",classification:"editable_input",typeAndUnit:"number, percentage points 0..100",editability:"editable",authority:"Imported/user physical-progress input",phase:"input",algorithm:"Preserved by F9 and used only when Percent Complete Type is physical.",interactions:"Percent Complete Type and visible progress.",unitTest:Tn,p6Golden:Ve}),ct({uiName:"Actual Duration",property:"actualDurationHours",xerField:"TASK.act_drtn_hr_cnt or actual endpoints",xmlField:"Activity.ActualDuration",classification:"derived",lifecycle:"open",typeAndUnit:"number, working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Status-specific non-negative working duration using actual endpoints/Data Date minus suspended overlap; reversed endpoints clamp to zero.",interactions:"Status, Actual Start/Finish, Data Date, Suspend/Resume and activity calendar.",unitTest:Ke,p6Golden:_n,status:"PARTIAL",edgeCases:_O}),ct({uiName:"At Completion Duration",property:"atCompletionDurationHours",xerField:"TASK.total_drtn_hr_cnt or planned/actual/remaining endpoints",xmlField:"Activity.AtCompletionDuration",classification:"derived",lifecycle:"open",typeAndUnit:"number, working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Not started: planned interval; in progress: Actual Start..Remaining Early Finish; completed: actual interval.",interactions:"Status, planned/actual/remaining endpoints, Suspend/Resume and calendar.",unitTest:Ke,p6Golden:_n,status:"PARTIAL",edgeCases:EO}),ct({uiName:"Duration % Complete",property:"durationPercentComplete",xerField:"TASK.target_drtn_hr_cnt + remain_drtn_hr_cnt",xmlField:"Activity.DurationPercentComplete",classification:"derived",lifecycle:"open",typeAndUnit:"number, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"100 \xD7 (Original Duration - Remaining Duration) / Original Duration, clamped to 0..100.",interactions:"Original and Remaining Duration; independent of Percent Complete Type selection.",unitTest:Ke,p6Golden:_n,status:"PARTIAL",edgeCases:PO}),ct({uiName:"Units % Complete",property:"unitsPercentComplete",xerField:"TASKRSRC actual and remaining unit scalars",xmlField:"Activity.ResourceAssignment.ActualUnits/RemainingUnits",classification:"derived",lifecycle:"open",typeAndUnit:"number, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields over canonical TASK scalars",phase:"derived",algorithm:"100 \xD7 total actual labor/nonlabor units / (actual + remaining units); zero denominator returns 0; finite signed values are not clamped.",interactions:"TASK unit scalars and Percent Complete Type; no full assignment subsystem.",unitTest:Ke,p6Golden:_n,status:"PARTIAL",edgeCases:RO}),ct({uiName:"Schedule % Complete",property:"schedulePercentComplete",xerField:"PROJECT.last_recalc_date + assigned baseline TASK dates, otherwise current TASK planned dates",xmlField:"Activity.SchedulePercentComplete",classification:"derived",lifecycle:"dependency_change",typeAndUnit:"number | null, percentage points",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Working effective-baseline time elapsed at Data Date / total working time, clamped to 0..100; a coincident milestone is 100% at its timestamp.",interactions:"Data Date, assigned baseline/current planned dates and activity calendar.",unitTest:Ke,p6Golden:_n,status:"VERIFIED",edgeCases:kO}),ct({uiName:"Remaining Float",property:"remainingFloatHours",xerField:"TASK remaining early/late endpoints",xmlField:"Activity.RemainingFloat",classification:"derived",lifecycle:"f9",typeAndUnit:"number | null, signed working hours",editability:"readonly",authority:"Schedule Core deriveP6ActivityFields",phase:"derived",algorithm:"Start Float, Finish Float or their minimum as selected, using signed working duration.",interactions:"Total Float method, remaining early/late endpoints and activity calendar.",unitTest:Ke,p6Golden:"src/p6/testing/p6-float-method/fixtures/obdd-float-method-smallest.xer",status:"VERIFIED",edgeCases:LO}),ct({uiName:"Remaining Early Start",property:"remainingEarlyStart",xerField:"TASK.restart_date",xmlField:"Activity.RemainingEarlyStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:ve("forward","earliest start of remaining work"),interactions:"Data Date, predecessors, OOS policy, constraints and calendar.",unitTest:"src/p6/testing/p6-data-date/obdd-math.schedule.test.ts",p6Golden:Ve,status:"VERIFIED"}),ct({uiName:"Remaining Early Finish",property:"remainingEarlyFinish",xerField:"TASK.reend_date",xmlField:"Activity.RemainingEarlyFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:ve("forward","calendar finish after remaining duration"),interactions:"Remaining Early Start, Remaining Duration, OOS policy and calendar.",unitTest:"src/p6/testing/p6-data-date/obdd-math.schedule.test.ts",p6Golden:Ve,status:"VERIFIED"}),ct({uiName:"Remaining Late Start",property:"remainingLateStart",xerField:"TASK.rem_late_start_date",xmlField:"Activity.RemainingLateStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:ve("backward","latest remaining start without violating successor/project bounds"),interactions:"Remaining Late Finish, constraints, successors and calendar.",unitTest:zi,p6Golden:Ji,status:"VERIFIED"}),ct({uiName:"Remaining Late Finish",property:"remainingLateFinish",xerField:"TASK.rem_late_end_date",xmlField:"Activity.RemainingLateFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:ve("backward","latest remaining finish without violating successor/project bounds"),interactions:"Successors, Must Finish By, constraints and calendar.",unitTest:zi,p6Golden:Ji,status:"VERIFIED"}),ct({uiName:"Early Start",property:"earlyStart",xerField:"TASK.early_start_date",xmlField:"Activity.EarlyStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:ve("forward","projected early start respecting immutable actuals"),interactions:"Actual Start, Remaining Early Start and OOS policy.",unitTest:zi,p6Golden:Ji,status:"VERIFIED"}),ct({uiName:"Early Finish",property:"earlyFinish",xerField:"TASK.early_end_date",xmlField:"Activity.EarlyFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 forward pass",phase:"forward",algorithm:ve("forward","projected early finish respecting immutable actuals"),interactions:"Actual Finish, Remaining Early Finish and OOS policy.",unitTest:zi,p6Golden:Ji,status:"VERIFIED"}),ct({uiName:"Late Start",property:"lateStart",xerField:"TASK.late_start_date",xmlField:"Activity.LateStart",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:ve("backward","projected late start"),interactions:"Remaining Late Start, constraints, float and immutable actuals.",unitTest:zi,p6Golden:Ji,status:"VERIFIED"}),ct({uiName:"Late Finish",property:"lateFinish",xerField:"TASK.late_end_date",xmlField:"Activity.LateFinish",classification:"f9_output",typeAndUnit:"Date | null, exact UTC instant",editability:"readonly",authority:"Schedule Core P6 backward pass",phase:"backward",algorithm:ve("backward","projected late finish"),interactions:"Remaining Late Finish, Must Finish By, constraints and float.",unitTest:zi,p6Golden:Ji,status:"VERIFIED"}),ct({uiName:"Float Path",property:"floatPath",xerField:"TASK.float_path",xmlField:"Activity.FloatPath",classification:"f9_output",typeAndUnit:"number | null, path number",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:ve("float_path","selected multiple-float-path identifier"),interactions:"Ending Activity, Total/Free Float selection, enabled and path limit settings.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-multiple-paths-limit-2.xer",status:"VERIFIED"}),ct({uiName:"Float Path Order",property:"floatPathOrder",xerField:"TASK.float_path_order",xmlField:"Activity.FloatPathOrder",classification:"f9_output",typeAndUnit:"number | null, ordinal",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:ve("float_path","stable order inside the selected float path"),interactions:"Float Path, relationship topology and deterministic tie-breaking.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-multiple-paths-limit-2.xer",status:"VERIFIED"}),ct({uiName:"Longest Path",property:"longestPath",xerField:"TASK.driving_path_flag",xmlField:"Activity.IsLongestPath",classification:"f9_output",typeAndUnit:"boolean",editability:"readonly",authority:"Schedule Core P6 float-path pass",phase:"float_path",algorithm:ve("float_path","true for activities on the selected longest path"),interactions:"Critical Activity Method, Ending Activity and deterministic path topology.",unitTest:"src/p6/paths.test.ts",p6Golden:"src/p6/testing/p6-floats/fixtures/obdd-floats-longest-path.xer",status:"VERIFIED"})]);var uA={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 pA=8;var fA={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return IA(OO);})();
|
|
2
2
|
//# sourceMappingURL=schedule-core.global.js.map
|