@geoapify/route-planner-sdk
Version:
TypeScript SDK for the Geoapify Route Planner API. Supports route optimization, delivery planning, and timeline visualization in browser and Node.js
1 lines • 599 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).RoutePlannerSDK={})}(this,(function(t){"use strict";function e(t,e,i,n){return new(i||(i=Promise))((function(s,o){function a(t){try{l(n.next(t))}catch(t){o(t)}}function r(t){try{l(n.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(a,r)}l((n=n.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const i="reoptimize",n="preserveOrder";class s{constructor(t){this.raw=t||{capabilities:[],time_windows:[],breaks:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setStartLocation(t,e){return this.raw.start_location=[t,e],this}setStartLocationIndex(t){return this.raw.start_location_index=t,this}setEndLocation(t,e){return this.raw.end_location=[t,e],this}setEndLocationIndex(t){return this.raw.end_location_index=t,this}setPickupCapacity(t){return this.raw.pickup_capacity=t,this}setDeliveryCapacity(t){return this.raw.delivery_capacity=t,this}addCapability(t){return this.raw.capabilities.push(t),this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}addBreak(t){return this.raw.breaks.push(t.getRaw()),this}setId(t){return this.raw.id=t,this}setDescription(t){return this.raw.description=t,this}}class o{constructor(t){this.raw=t||{}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setLat(t){return this.raw.lat=t,this}setLon(t){return this.raw.lon=t,this}}class a{constructor(t){this.raw=t||{values:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setType(t){return this.raw.type=t,this}addValue(t,e){let i=(new o).setLat(e).setLon(t);return this.raw.values.push(i.getRaw()),this}}class r{constructor(t){this.raw=t||{time_windows:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}setDuration(t){return this.raw.duration=t,this}}class l{constructor(t){this.raw=t||{requirements:[],time_windows:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setLocation(t,e){return this.raw.location=[t,e],this}setLocationIndex(t){return this.raw.location_index=t,this}setPriority(t){return this.raw.priority=t,this}setDuration(t){return this.raw.duration=t,this}setPickupAmount(t){return this.raw.pickup_amount=t,this}setDeliveryAmount(t){return this.raw.delivery_amount=t,this}addRequirement(t){return this.raw.requirements.push(t),this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}setId(t){return this.raw.id=t,this}setDescription(t){return this.raw.description=t,this}}class d{constructor(t){this.raw=t||{}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setId(t){return this.raw.id=t,this}setLocation(t,e){return this.raw.location=[t,e],this}}class c{constructor(t){this.raw=t||{requirements:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setId(t){return this.raw.id=t,this}setPickup(t){return this.raw.pickup=t.getRaw(),this}setDelivery(t){return this.raw.delivery=t.getRaw(),this}addRequirement(t){return this.raw.requirements.push(t),this}setPriority(t){return this.raw.priority=t,this}setDescription(t){return this.raw.description=t,this}setAmount(t){return this.raw.amount=t,this}}class p{constructor(t){this.raw=t||{time_windows:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setLocation(t,e){return this.raw.location=[t,e],this}setLocationIndex(t){return this.raw.location_index=t,this}setDuration(t){return this.raw.duration=t,this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}}class u{constructor(t){if(!t)throw new Error("RouteLegStepData is undefined");this.raw=t}getRaw(){return this.raw}getDistance(){return this.raw.distance}getTime(){return this.raw.time}getFromIndex(){return this.raw.from_index}getToIndex(){return this.raw.to_index}}class h{constructor(t){if(!t)throw new Error("RouteLegData is undefined");this.raw=t}getRaw(){return this.raw}getTime(){return this.raw.time}getDistance(){return this.raw.distance}getSteps(){return this.raw.steps.map((t=>new u(t)))}getFromWaypointIndex(){return this.raw.from_waypoint_index}getToWaypointIndex(){return this.raw.to_waypoint_index}}class g{constructor(t){if(!t)throw new Error("ActionResponseData is undefined");this.raw=t}getRaw(){return this.raw}getType(){return this.raw.type}getStartTime(){return this.raw.start_time}getDuration(){return this.raw.duration}getShipmentIndex(){return this.raw.shipment_index}getShipmentId(){return this.raw.shipment_id}getLocationIndex(){return this.raw.location_index}getLocationId(){return this.raw.location_id}getJobIndex(){return this.raw.job_index}getJobId(){return this.raw.job_id}getActionIndex(){return this.raw.index}getWaypointIndex(){return this.raw.waypoint_index}}class m{constructor(t){if(!t)throw new Error("WaypointData is undefined");this.raw=t}getRaw(){return this.raw}getOriginalLocation(){return this.raw.original_location}getOriginalLocationIndex(){return this.raw.original_location_index}getOriginalLocationId(){return this.raw.original_location_id}getLocation(){return this.raw.location||this.raw.original_location}getStartTime(){return this.raw.start_time}getDuration(){return this.raw.duration}getActions(){return this.raw.actions.map((t=>new g(t)))}getPrevLegIndex(){return this.raw.prev_leg_index}getNextLegIndex(){return this.raw.next_leg_index}}class y{constructor(t,e,i,n,s){if(this.raw=t,this.agentInputData=e,this.routingOptions=i,this.callOptions=n,this.violations=s,!t)throw new Error("AgentSolutionData is undefined")}getRaw(){return this.raw}getAgentIndex(){return this.raw.agent_index}getAgentId(){return this.raw.agent_id}getTime(){return this.raw.time}getStartTime(){return this.raw.start_time}getEndTime(){return this.raw.end_time}getDistance(){return this.raw.distance}getMode(){return this.raw.mode}getLegs(){return this.raw.legs.map((t=>new h(t)))}getActions(){return this.raw.actions.map((t=>new g(t)))}getDelays(){return this.getActions().filter((t=>"delay"===t.getType()))}getWaypoints(){return this.raw.waypoints.map((t=>new m(t)))}getPlannedShipments(){return[...new Set(this.raw.actions.filter((t=>void 0!==t.shipment_index)).map((t=>t.shipment_index)))]}getPlannedJobs(){return[...new Set(this.raw.actions.filter((t=>void 0!==t.job_index)).map((t=>t.job_index)))]}getAgentInputData(){return this.agentInputData}containsShipment(t){return this.getActions().some((e=>e.getShipmentIndex()===t||e.getShipmentId()===t))}containsJob(t){return this.getActions().some((e=>e.getJobIndex()===t||e.getJobId()===t))}getViolations(){return this.violations}getRoute(t){var i;return e(this,void 0,void 0,(function*(){const e=this.getWaypoints().map((t=>t.getLocation())),n=e.map((t=>"lonlat:"+t)).join("|");if(0===n.length)return;const s=yield fetch(this.constructRoutingRequest(n,t||this.routingOptions,this.callOptions)),o=yield s.json(),a=null===(i=null==o?void 0:o.features)||void 0===i?void 0:i[0];return a?(a.properties=Object.assign(Object.assign({},a.properties||{}),{agent_index:this.getAgentIndex(),agent_id:this.getAgentId()}),a):{type:"Feature",geometry:{type:"LineString",coordinates:e},properties:{agent_index:this.getAgentIndex(),agent_id:this.getAgentId()}}}))}constructRoutingRequest(t,e,i){let n=`${i.baseUrl}/v1/routing?waypoints=${t}&apiKey=${i.apiKey}`;return e.mode&&(n+=`&mode=${e.mode}`),e.type&&(n+=`&type=${e.type}`),e.units&&(n+=`&units=${e.units}`),e.lang&&(n+=`&lang=${e.lang}`),e.avoid&&e.avoid.length>0&&(n+=`&avoid=${e.avoid.map((t=>t.type)).join("|")}`),e.details&&e.details.length>0&&(n+=`&details=${e.details.join(",")}`),e.traffic&&(n+=`&traffic=${e.traffic}`),e.max_speed&&(n+=`&max_speed=${e.max_speed}`),n}}class v extends Error{constructor(t,e,i){super(e),this.errorName=t,this.message=e,this.rawResponse=i,this.name=t,this.rawResponse=i}}class f{static cleanObject(t){if(Array.isArray(t))return t.length>0?t.map(f.cleanObject):void 0;if(null!==t&&"object"==typeof t){const e=Object.entries(t).reduce(((t,[e,i])=>{const n=f.cleanObject(i);return void 0!==n&&(t[e]=n),t}),{});return Object.keys(e).length>0?e:void 0}return t}static cloneObject(t){return JSON.parse(JSON.stringify(t))}}class w{static generateRoutePlannerResultData(t){var e,i,n;let s=f.cloneObject(t);return{agents:this.generateAgents(s),inputData:s.properties.params,unassignedAgents:null===(e=s.properties.issues)||void 0===e?void 0:e.unassigned_agents,unassignedJobs:null===(i=s.properties.issues)||void 0===i?void 0:i.unassigned_jobs,unassignedShipments:null===(n=s.properties.issues)||void 0===n?void 0:n.unassigned_shipments}}static generateAgents(t){let e=[];return t.features.forEach((t=>{e.push(t.properties)})),e}}class x{constructor(t,e,i){if(this.jobIndex=t,this.jobInputData=e,this.agentPlan=i,!e)throw new Error("jobInputData is undefined")}getAgentId(){return this.agentPlan?this.agentPlan.getAgentId():void 0}getAgentIndex(){return this.agentPlan?this.agentPlan.getAgentIndex():void 0}getRouteActions(){return this.agentPlan?this.agentPlan.getActions().filter((t=>t.getJobIndex()===this.jobIndex)):[]}getAgentPlan(){return this.agentPlan}getJobInputData(){return this.jobInputData}getJobIndex(){return this.jobIndex}}class A{constructor(t,e,i){if(this.shipmentIndex=t,this.shipmentInputData=e,this.agentPlan=i,!e)throw new Error("shipmentInputData is undefined")}getAgentId(){return this.agentPlan?this.agentPlan.getAgentId():void 0}getAgentIndex(){return this.agentPlan?this.agentPlan.getAgentIndex():void 0}getShipmentId(){return this.shipmentInputData.id}getShipmentIndex(){return this.shipmentIndex}getRouteActions(){return this.agentPlan?this.agentPlan.getActions().filter((t=>t.getShipmentIndex()===this.shipmentIndex)):[]}getAgentPlan(){return this.agentPlan}getShipmentInputData(){return this.shipmentInputData}}class _{constructor(t,e){this.agentIndex=e,this.message=t,this.name="Violation"}toString(){return this.message}}class b extends _{constructor(t,e,i,n){super(t,e),this.totalAmount=i,this.capacity=n,this.name="AgentPickupCapacityExceeded"}}class I extends _{constructor(t,e,i,n){super(t,e),this.totalAmount=i,this.capacity=n,this.name="AgentDeliveryCapacityExceeded"}}class T extends _{constructor(t,e,i){super(t,e),this.missingCapabilities=i,this.name="AgentMissingCapability"}}class S extends _{constructor(t,e){super(t,e),this.name="TimeWindowViolation"}}class L extends _{constructor(t,e){super(t,e),this.name="BreakViolation"}}class P extends Error{constructor(t,e){super(t),this.parameterName=e,this.name="InvalidParameter"}}class D extends Error{constructor(t,e){super(t),this.agentIdOrIndex=e,this.name="AgentNotFound"}}class R extends Error{constructor(t,e){super(t),this.jobIdOrIndex=e,this.name="JobNotFound"}}class E extends Error{constructor(t,e){super(t),this.shipmentIdOrIndex=e,this.name="ShipmentNotFound"}}class k extends Error{constructor(t,e){super(t),this.agentIndex=e,this.name="AgentHasNoPlan"}}class $ extends Error{constructor(t,e){super(t),this.itemType=e,this.name="ItemsNotUnique"}}class O extends Error{constructor(t,e){super(t),this.itemType=e,this.name="NoItemsProvided"}}class W extends Error{constructor(t,e,i,n){super(t),this.itemType=e,this.itemIndex=i,this.agentIndex=n,this.name="ItemAlreadyAssigned"}}class j extends Error{constructor(t,e,i,n){super(t),this.agentIndex=e,this.waypointIndex=i,this.actionId=n,this.name="InvalidInsertionPosition"}}class C extends Error{constructor(t,e,i){super(t),this.strategy=e,this.operationType=i,this.name="UnknownStrategy"}}class M extends Error{constructor(t,e,i){super(t),this.statusCode=e,this.statusText=i,this.name="RouteMatrixApiError"}}class J extends Error{constructor(t,e,i){super(t),this.statusCode=e,this.statusText=i,this.name="RoutingApiError"}}class N{static convertAgentToIndex(t,e,i=!1){if("number"==typeof e)return e;let n=t.properties.params.agents.findIndex((t=>t.id===e));if(-1===n){if(i)throw new D(`Agent with id ${e} not found`,e);return-1}return n}static convertJobToIndex(t,e){if("number"==typeof e)return e;let i=t.properties.params.jobs.findIndex((t=>t.id===e));return i<0?-1:i}static convertShipmentToIndex(t,e){if("number"==typeof e)return e;let i=t.properties.params.shipments.findIndex((t=>t.id===e));return i<0?-1:i}static convertJobsToIndexes(t,e){if("number"==typeof e[0])return e;let i=[];return e.forEach((e=>{let n=t.properties.params.jobs.findIndex((t=>t.id===e));if(n<0)throw new R(`Job with id ${e} not found`,e);i.push(n)})),i}static convertShipmentsToIndexes(t,e){if("number"==typeof e[0])return e;let i=[];return e.forEach((e=>{let n=t.properties.params.shipments.findIndex((t=>t.id===e));if(n<0)throw new E(`Shipment with id ${e} not found`,e);i.push(n)})),i}}class F{constructor(t,e){this.callOptions=t,this.rawData=e,this.data=w.generateRoutePlannerResultData(this.rawData),this.agentPlans=new Array(this.data.inputData.agents.length).fill(void 0),this.data.agents.forEach((t=>{this.agentPlans[t.agent_index]=new y(t,this.data.inputData.agents[t.agent_index],this.getData().inputData,this.callOptions,this.getAgentViolations(t.agent_index))})),this.shipmentPlans=(this.data.inputData.shipments||[]).map(((t,e)=>{const i=this.agentPlans.find((t=>!!t&&t.containsShipment(e)));return new A(e,t,i)})),this.jobPlans=(this.data.inputData.jobs||[]).map(((t,e)=>{const i=this.agentPlans.find((t=>!!t&&t.containsJob(e)));return new x(e,t,i)}))}getData(){return this.data}getRaw(){return this.rawData}getAgentPlans(){return this.agentPlans}getAgentPlan(t){const e=N.convertAgentToIndex(this.getRaw(),t);if(e>=0)return this.agentPlans[e]}getUnassignedAgents(){let t=this.getData();return t.unassignedAgents&&0!=t.unassignedAgents.length?t.unassignedAgents.map((e=>t.inputData.agents[e])):[]}getUnassignedJobs(){let t=this.getData();return t.unassignedJobs&&0!=t.unassignedJobs.length?t.unassignedJobs.map((e=>t.inputData.jobs[e])):[]}getUnassignedShipments(){let t=this.getData();return t.unassignedShipments&&0!=t.unassignedShipments.length?t.unassignedShipments.map((e=>t.inputData.shipments[e])):[]}getJobPlans(){return this.jobPlans}getJobPlan(t){const e=N.convertJobToIndex(this.getRaw(),t);if(e>=0)return this.jobPlans[e]}getShipmentPlans(){return this.shipmentPlans}getShipmentPlan(t){const e=N.convertShipmentToIndex(this.getRaw(),t);if(e>=0)return this.shipmentPlans[e]}getCallOptions(){return this.callOptions}getRoutingOptions(){return this.data.inputData}getAgentViolations(t){var e,i;return null!==(i=null===(e=this.rawData.properties.violations)||void 0===e?void 0:e.filter((e=>e.agentIndex===t)))&&void 0!==i?i:[]}}var U={__proto__:null,Agent:s,AgentDeliveryCapacityExceeded:I,AgentHasNoPlan:k,AgentMissingCapability:T,AgentNotFound:D,AgentPickupCapacityExceeded:b,AgentPlan:y,Avoid:a,Break:r,BreakViolation:L,Coordinates:o,InvalidInsertionPosition:j,InvalidParameter:P,ItemAlreadyAssigned:W,ItemsNotUnique:$,Job:l,JobNotFound:R,Location:d,NoItemsProvided:O,PRESERVE_ORDER:n,REOPTIMIZE:i,RouteAction:g,RouteLeg:h,RouteLegStep:u,RouteMatrixApiError:M,RoutePlannerError:v,RoutePlannerResult:F,RoutingApiError:J,Shipment:c,ShipmentNotFound:E,ShipmentStep:p,TimeWindowViolation:S,UnknownStrategy:C,Violation:_,Waypoint:m};class B{constructor(t,e){this.baseUrl=t.baseUrl||"https://api.geoapify.com",this.options=Object.assign(Object.assign({},t),{baseUrl:this.baseUrl}),this.raw=e||{agents:[],jobs:[],shipments:[],locations:[],avoid:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setMode(t){return this.raw.mode=t,this}addAgent(t){return this.raw.agents.push(t.getRaw()),this}addJob(t){return this.raw.jobs.push(t.getRaw()),this}addLocation(t){return this.raw.locations.push(t.getRaw()),this}addShipment(t){return this.raw.shipments.push(t.getRaw()),this}addAvoid(t){return this.raw.avoid=this.raw.avoid||[],this.raw.avoid.push(t.getRaw()),this}setTraffic(t){return this.raw.traffic=t,this}setType(t){return this.raw.type=t,this}setMaxSpeed(t){return this.raw.max_speed=t,this}setUnits(t){return this.raw.units=t,this}plan(){return e(this,void 0,void 0,(function*(){try{return yield this.callPlan()}catch(t){if(t instanceof v)throw t;throw new v((null==t?void 0:t.name)||"UnknownError",(null==t?void 0:t.message)||"An unknown error occurred",t)}}))}callPlan(){return e(this,void 0,void 0,(function*(){const t=f.cleanObject(this.raw),i=yield function(t,i){return e(this,void 0,void 0,(function*(){if("undefined"!=typeof fetch)return fetch(t,i);try{const e=Function("return import('node-fetch')")();return(0,(yield e).default)(t,i)}catch(t){throw new Error("Fetch is not available in this environment. If you are using Node.js <18, install 'node-fetch' manually: npm install node-fetch")}}))}(`${this.baseUrl}/v1/routeplanner?apiKey=${this.options.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok){let t=yield i.json();throw new v(t.error,t.message,t)}let n=yield i.json();return new F(this.options,n)}))}}class q{static createAssignAgentRequirement(t){return`${this.ASSIGN_AGENT_PREFIX}${t}`}static ensureRequirementsArray(t){t.requirements||(t.requirements=[])}static addRequirement(t,e){t.includes(e)||t.push(e)}static removeRequirement(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}static markAsUnassigned(t){this.ensureRequirementsArray(t),this.addRequirement(t.requirements,this.UNASSIGNED_REQ)}static assignToAgent(t,e){const i=this.createAssignAgentRequirement(e);this.ensureRequirementsArray(t),this.removeRequirement(t.requirements,this.UNASSIGNED_REQ),this.addRequirement(t.requirements,i)}static markItemsAsUnassigned(t,e){for(const i of e)t[i]&&this.markAsUnassigned(t[i])}static assignItemsToAgent(t,e,i){for(const n of e)t[n]&&this.assignToAgent(t[n],i)}static markExistingUnassignedJobs(t,e){var i;const n=null===(i=t.getRawData().properties.issues)||void 0===i?void 0:i.unassigned_jobs;n&&this.markItemsAsUnassigned(e,n)}static markExistingUnassignedShipments(t,e){var i;const n=null===(i=t.getRawData().properties.issues)||void 0===i?void 0:i.unassigned_shipments;n&&this.markItemsAsUnassigned(e,n)}static markRemainingJobsWithAgentRequirement(t,e,i){for(let n=0;n<e.length;n++){if(i.includes(n))continue;const s=t.getAgentIndexForJob(n);void 0!==s&&this.assignToAgent(e[n],s)}}static markRemainingShipmentsWithAgentRequirement(t,e,i){for(let n=0;n<e.length;n++){if(i.includes(n))continue;const s=t.getAgentIndexForShipment(n);void 0!==s&&this.assignToAgent(e[n],s)}}static extendAgentTimeWindows(t){var e,i,n;const s=null!==(n=null===(i=null===(e=null==t?void 0:t.time_windows)||void 0===e?void 0:e[0])||void 0===i?void 0:i[0])&&void 0!==n?n:0;t.time_windows=[[s,4102444800]]}static restrictAssignmentsToTargetSet(t,e){for(let i=0;i<t.length;i++){const n=t[i];n&&(e.has(i)?delete n.requirements:(this.ensureRequirementsArray(n),this.addRequirement(n.requirements,this.NON_ASSIGNABLE_REQUIREMENT)))}}}q.UNASSIGNED_REQ="unassigned",q.ASSIGN_AGENT_PREFIX="assign-agent-",q.NON_ASSIGNABLE_REQUIREMENT="NON_ASSIGNABLE";class z{static validate(t,e){const i=t.getRawData(),n=[];let s=this.validateTimeWindows(t,e);n.push(...s);let o=this.validateBreaks(t,e);n.push(...o);let a=this.validateCapacity(t,e);n.push(...a);let r=this.validateCapabilities(t,e);n.push(...r),this.addViolationsToResult(i,e,n)}static validateTimeWindows(t,e){var i;const n=[],s=t.getRawData(),o=s.properties.params.agents[e],a=t.getAgentActions(e);for(const t of a){if(t.type===this.ACTION_TYPE_START||t.type===this.ACTION_TYPE_END||t.type===this.ACTION_TYPE_BREAK||t.type===this.ACTION_TYPE_DELAY)continue;const a=this.getActionTimeWindow(t),r=this.getItemTimeWindows(s,t);r.length>0&&!this.isWithinAnyTimeWindow(a,r)&&n.push(new S(`Action at time ${t.start_time} is outside ${t.type} time windows`,e)),(null===(i=o.time_windows)||void 0===i?void 0:i.length)>0&&!this.isWithinAnyTimeWindow(a,o.time_windows)&&n.push(new S(`Action at time ${t.start_time} is outside agent time windows`,e))}return n}static validateBreaks(t,e){var i;const n=[],s=t.getRawData().properties.params.agents[e],o=t.getAgentActions(e);if(!(null===(i=s.breaks)||void 0===i?void 0:i.length))return n;for(const t of o){if(t.type===this.ACTION_TYPE_START||t.type===this.ACTION_TYPE_END||t.type===this.ACTION_TYPE_BREAK||t.type===this.ACTION_TYPE_DELAY)continue;const i=this.getActionTimeWindow(t);for(const o of s.breaks)if(this.intersectsAnyTimeWindow(i,o.time_windows)){n.push(new L(`Action at time ${t.start_time} conflicts with agent break`,e));break}}return n}static validateCapacity(t,e){const i=[],n=t.getRawData(),s=n.properties.params.agents[e],o=t.getAgentActions(e);let a=0,r=0;for(const t of o)t.type===this.ACTION_TYPE_PICKUP?a+=this.getActionAmount(n,t):t.type===this.ACTION_TYPE_DELIVERY?r+=this.getActionAmount(n,t):t.type===this.ACTION_TYPE_JOB&&(a+=this.getJobPickupAmount(n,t),r+=this.getJobDeliveryAmount(n,t));const l=this.normalizeCapacity(s.pickup_capacity);void 0!==s.pickup_capacity&&void 0===l?i.push(new b(`Agent pickup capacity is invalid (${String(s.pickup_capacity)})`,e,a,0)):void 0!==l&&a>l&&i.push(new b(`Total pickup amount (${a}) exceeds agent pickup capacity (${l})`,e,a,l));const d=this.normalizeCapacity(s.delivery_capacity);return void 0!==s.delivery_capacity&&void 0===d?i.push(new I(`Agent delivery capacity is invalid (${String(s.delivery_capacity)})`,e,r,0)):void 0!==d&&r>d&&i.push(new I(`Total delivery amount (${r}) exceeds agent delivery capacity (${d})`,e,r,d)),i}static validateCapabilities(t,e){var i,n;const s=[],o=t.getRawData(),a=o.properties.params.agents[e],r=t.getAgentActions(e),l=new Set;for(const t of r){if(void 0!==t.job_index){const e=null===(i=o.properties.params.jobs)||void 0===i?void 0:i[t.job_index];this.collectMissingRequirements(a,null==e?void 0:e.requirements,l)}if(void 0!==t.shipment_index){const e=null===(n=o.properties.params.shipments)||void 0===n?void 0:n[t.shipment_index];this.collectMissingRequirements(a,null==e?void 0:e.requirements,l)}}if(0===l.size)return s;const d=Array.from(l),c=1===d.length?`Agent is missing required capability: '${d[0]}'`:`Agent is missing required capabilities: ${d.join(", ")}`;return s.push(new T(c,e,d)),s}static collectMissingRequirements(t,e,i){var n;if(null==e?void 0:e.length)for(const s of e)(null===(n=t.capabilities)||void 0===n?void 0:n.includes(s))||i.add(s)}static getActionTimeWindow(t){return[t.start_time,t.start_time+(t.duration||0)]}static getItemTimeWindows(t,e){var i,n;if(void 0!==e.job_index){const i=t.properties.params.jobs[e.job_index];return(null==i?void 0:i.time_windows)||[]}if(void 0!==e.shipment_index){const s=t.properties.params.shipments[e.shipment_index];if(e.type===this.ACTION_TYPE_PICKUP)return(null===(i=null==s?void 0:s.pickup)||void 0===i?void 0:i.time_windows)||[];if(e.type===this.ACTION_TYPE_DELIVERY)return(null===(n=null==s?void 0:s.delivery)||void 0===n?void 0:n.time_windows)||[]}return[]}static getActionAmount(t,e){if(void 0!==e.shipment_index){const i=t.properties.params.shipments[e.shipment_index];return this.normalizeAmount(null==i?void 0:i.amount)}return 0}static getJobPickupAmount(t,e){if(void 0!==e.job_index){const i=t.properties.params.jobs[e.job_index];return this.normalizeAmount(null==i?void 0:i.pickup_amount)}return 0}static getJobDeliveryAmount(t,e){if(void 0!==e.job_index){const i=t.properties.params.jobs[e.job_index];return this.normalizeAmount(null==i?void 0:i.delivery_amount)}return 0}static normalizeAmount(t){return"number"!=typeof t||!Number.isFinite(t)||t<0?0:t}static normalizeCapacity(t){if(void 0!==t&&"number"==typeof t&&Number.isFinite(t)&&!(t<0))return t}static isWithinAnyTimeWindow(t,e){const[i,n]=t;return e.some((([t,e])=>i>=t&&n<=e))}static intersectsAnyTimeWindow(t,e){const[i,n]=t;return e.some((([t,e])=>i<e&&n>t))}static addViolationsToResult(t,e,i){t.properties.violations=(t.properties.violations||[]).filter((t=>t.agentIndex!==e)),0!==i.length?t.properties.violations.push(...i):t.properties.violations.length||delete t.properties.violations}}z.ACTION_TYPE_PICKUP="pickup",z.ACTION_TYPE_DELIVERY="delivery",z.ACTION_TYPE_START="start",z.ACTION_TYPE_END="end",z.ACTION_TYPE_BREAK="break",z.ACTION_TYPE_DELAY="delay",z.ACTION_TYPE_JOB="job";class Y{static hasExplicitInsertPosition(t){return(void 0!==t.afterId&&""!==t.afterId||void 0!==t.afterWaypointIndex)&&!0===t.append}static shouldAppend(t){return!0===t.append&&!t.afterId&&void 0===t.afterWaypointIndex}static resolveInsertPosition(t){return void 0!==t.afterWaypointIndex?t.afterWaypointIndex+1:0}static validateAfterWaypointIndex(t,e,i){const n=t.getAgentWaypoints(e),s=n.length-1;if(0===n.length)throw new j(`Agent ${e} has no route.`,e);if(i<0||i>=n.length)throw new j(`Waypoint index ${i} out of range (0-${n.length-1})`,e,i);if(i===s&&n[s].actions.some((t=>"end"===t.type)))throw new j(`Cannot change the route after waypoint ${i} (end location).`,e,i)}static extractRouteLocations(t){return t.properties.waypoints.map((t=>t.location||t.original_location))}}class V{static createJobAction(t,e,i){const n=this.getJobByIndex(t,e);return{index:0,type:"job",start_time:0,duration:n.duration||0,job_index:e,job_id:n.id,waypoint_index:i}}static createShipmentAction(t,e,i,n){var s,o;const a=this.getShipmentByIndex(t,e);return{index:0,type:i,start_time:0,duration:"pickup"===i?(null===(s=a.pickup)||void 0===s?void 0:s.duration)||0:(null===(o=a.delivery)||void 0===o?void 0:o.duration)||0,shipment_index:e,shipment_id:a.id,waypoint_index:n}}static getJobByIndex(t,e){return t.getRawData().properties.params.jobs[e]}static getShipmentByIndex(t,e){return t.getRawData().properties.params.shipments[e]}static resolveShipmentStepLocation(t,e){return this.resolveShipmentStepWaypointLocationData(t,e).location}static resolveShipmentStepWaypointLocationData(t,e){if(e.location)return{location:e.location};if(void 0!==e.location_index){const i=t.getRawData().properties.params.locations[e.location_index];if(!(null==i?void 0:i.location))throw new Error(`Shipment step has invalid location_index ${e.location_index}`);return{location:i.location,locationIndex:e.location_index,locationId:i.id}}throw new Error("Shipment step must have either location or location_index")}static resolveJobLocation(t,e){return this.resolveJobWaypointLocationData(t,e).location}static resolveJobWaypointLocationData(t,e){if(e.location)return{location:e.location};if(void 0!==e.location_index){const i=t.getRawData().properties.params.locations[e.location_index];if(!(null==i?void 0:i.location))throw new Error(`Job has invalid location_index ${e.location_index}`);return{location:i.location,locationIndex:e.location_index,locationId:i.id}}throw new Error("Job must have either location or location_index")}}const K=-1;class H{static replaceLegsForInsertedWaypoint(t,e,i){const n=t.getAgentFeature(e).properties;n.legs||(n.legs=[]);const s=n.legs,o=n.waypoints,a={from_waypoint_index:i-1,to_waypoint_index:i,time:K,distance:K,steps:[]},r={from_waypoint_index:i,to_waypoint_index:i+1,time:K,distance:K,steps:[]};o.length<=1||(0===i?s.splice(i,0,r):i===o.length-1?s.splice(i,0,a):s.splice(i-1,1,a,r),s.forEach(((t,e)=>{t.from_waypoint_index=e,t.to_waypoint_index=e+1})))}static fillMissingLegData(t,i){return e(this,void 0,void 0,(function*(){const e=i.properties.waypoints||[],n=i.properties.legs||[],s=this.findMissingLegIndices(n);s.length>0&&(yield this.fillMissingOrderedLegs(t,e,n,s)),this.recreateGeometry(i,e,n)}))}static fillMissingOrderedLegs(t,i,n,s){var o,a,r,l,d,c;return e(this,void 0,void 0,(function*(){const p=t.getRoutingHelper(),u=yield Promise.all(s.map((t=>e(this,void 0,void 0,(function*(){const e=i[t+1],n=this.getWaypointLocation(i[t]),s=this.getWaypointLocation(e);if(!n||!s)return{legIndex:t,routeData:null};try{const e=yield p.calculateRouteData([n,s]);return{legIndex:t,routeData:e}}catch(e){return{legIndex:t,routeData:null}}})))));for(const t of u){const e=n[t.legIndex];if(!e)continue;const s=null===(a=null===(o=t.routeData)||void 0===o?void 0:o.legs)||void 0===a?void 0:a[0];s?(e.time=null!==(r=s.time)&&void 0!==r?r:0,e.distance=null!==(l=s.distance)&&void 0!==l?l:0,e.steps=[{distance:e.distance,time:s.time,from_index:0,to_index:1}]):(e.time=0,e.distance=0,e.steps=[]);const p=this.getMappedRouteWaypointLocation(null===(d=t.routeData)||void 0===d?void 0:d.waypoints,0),u=this.getMappedRouteWaypointLocation(null===(c=t.routeData)||void 0===c?void 0:c.waypoints,1);p&&(i[t.legIndex].location=p),u&&(i[t.legIndex+1].location=u)}}))}static recreateGeometry(t,e,i){const n=[];for(let t=0;t<i.length;t++){const s=this.getWaypointLocation(e[t]),o=this.getWaypointLocation(e[t+1]);s&&o&&(i[t].from_waypoint_index=t,i[t].to_waypoint_index=t+1,n.push([s,o]))}t.geometry=Object.assign(Object.assign({},t.geometry),{type:"MultiLineString",coordinates:n})}static getMappedRouteWaypointLocation(t,e){var i;if(!t||0===t.length)return;const n=t.find((t=>(null==t?void 0:t.original_index)===e));return(null==n?void 0:n.location)||(null===(i=t[e])||void 0===i?void 0:i.location)}static getWaypointLocation(t){if(t)return t.location||t.original_location}static findMissingLegIndices(t){const e=[];for(let i=0;i<t.length;i++){const n=t[i];n&&(void 0===n.time||n.time===K||n.time<0||void 0===n.distance||n.distance===K||n.distance<0)&&e.push(i)}return e}}class G{static insertJobWaypoint(t,e,i,n){const s=t.getAgentFeature(e).properties.waypoints,o=V.getJobByIndex(t,i),a=V.resolveJobWaypointLocationData(t,o),r=V.createJobAction(t,i,n.position);n.createWaypoint?(s.splice(n.position,0,{original_location:a.location,original_location_index:a.locationIndex,original_location_id:a.locationId,start_time:r.start_time||0,duration:r.duration||0,actions:[r],prev_leg_index:void 0,next_leg_index:void 0}),H.replaceLegsForInsertedWaypoint(t,e,n.position)):this.addActionToWaypoint(s[n.position],r)}static insertShipmentWaypoints(t,e,i,n){const s=t.getAgentFeature(e).properties.waypoints,o=V.getShipmentByIndex(t,i),a=V.createShipmentAction(t,i,"pickup",n.pickup),r=V.createShipmentAction(t,i,"delivery",n.delivery);if(n.createPickupWaypoint){const i=V.resolveShipmentStepWaypointLocationData(t,o.pickup),r={original_location:i.location,original_location_index:i.locationIndex,original_location_id:i.locationId,start_time:a.start_time||0,duration:a.duration||0,actions:[Object.assign(Object.assign({},a),{waypoint_index:n.pickup})],prev_leg_index:void 0,next_leg_index:void 0};s.splice(n.pickup,0,r),H.replaceLegsForInsertedWaypoint(t,e,n.pickup)}else{const t=s[n.pickup];t&&this.addActionToWaypoint(t,a)}if(n.createDeliveryWaypoint){const i=V.resolveShipmentStepWaypointLocationData(t,o.delivery),a={original_location:i.location,original_location_index:i.locationIndex,original_location_id:i.locationId,start_time:r.start_time||0,duration:r.duration||0,actions:[Object.assign(Object.assign({},r),{waypoint_index:n.delivery})],prev_leg_index:void 0,next_leg_index:void 0};s.splice(n.delivery,0,a),H.replaceLegsForInsertedWaypoint(t,e,n.delivery)}else{const t=s[n.delivery];t&&this.addActionToWaypoint(t,r)}}static addActionToWaypoint(t,e){const i=t.actions.findIndex((t=>"end"===t.type));i>=0?t.actions.splice(i,0,Object.assign({},e)):t.actions.push(Object.assign({},e))}static actionsMatch(t,e){return t.type===e.type&&("job"===t.type?t.job_index===e.job_index:"pickup"===t.type||"delivery"===t.type?t.shipment_index===e.shipment_index:"start"===t.type||"end"===t.type)}static removeJobsFromWaypoints(t,e){for(const i of t)i.actions=i.actions.filter((t=>t.job_index!==e))}static removeShipmentsFromWaypoints(t,e){for(const i of t)i.actions=i.actions.filter((t=>t.shipment_index!==e))}static removeEmptyWaypoints(t,e){const i=[],n=[];for(let e=0;e<t.length;e++)t[e].actions.length>0?i.push(t[e]):n.push(e);return e&&0!==n.length?{waypoints:i,legs:this.rebuildLegs(i,e),removedWaypointIndices:n}:{waypoints:i,removedWaypointIndices:n}}static buildLegDataMap(t,e){const i=new Map;for(const n of e){const e=t[n.from_waypoint_index],s=t[n.to_waypoint_index];if(!e||!s)continue;const o=this.getLocationPairKey(this.getWaypointLocation(e),this.getWaypointLocation(s));i.set(o,n)}return i}static rebuildLegs(t,e){const i=[];for(let n=0;n<t.length-1;n++){const s=t[n+1],o=this.getLocationPairKey(this.getWaypointLocation(t[n]),this.getWaypointLocation(s)),a=e.get(o);i.push(a?{from_waypoint_index:n,to_waypoint_index:n+1,time:a.time,distance:a.distance,steps:a.steps||[]}:{from_waypoint_index:n,to_waypoint_index:n+1,time:K,distance:K,steps:[]})}return i}static getLocationPairKey(t,e){return`${t[0]},${t[1]}->${e[0]},${e[1]}`}static getWaypointLocation(t){return t.location||t.original_location}}class X{static recalculate(t,i){return e(this,void 0,void 0,(function*(){const e=t.getAgentFeature(i),n=e.properties.waypoints,s=e.properties.legs||[];yield H.fillMissingLegData(t,e);let o=e.properties.start_time;const a=[];for(let t=0;t<n.length;t++)if(o+=t>0?s[t-1].time:0,n[t].start_time=o,0===t?delete n[t].prev_leg_index:n[t].prev_leg_index=t-1,t===n.length-1?delete n[t].next_leg_index:n[t].next_leg_index=t,n[t].actions.forEach((e=>{e.waypoint_index=t,e.index=a.length,e.start_time=o,o+=e.duration||0,a.push(e)})),n[t].duration=o-n[t].start_time,t<n.length-1)n[t].location=e.geometry.coordinates[t][0];else{const i=e.geometry.coordinates[t-1];n[t].location=i[i.length-1]}e.properties.end_time=o,e.properties.time=e.properties.end_time-e.properties.start_time,e.properties.actions=a,e.properties.distance=s.reduce(((t,e)=>t+e.distance),0)}))}}class Q{constructor(t,e){this.baseUrl=t.baseUrl||"https://api.geoapify.com",this.apiKey=t.apiKey,this.routingOptions=e}calculateMatrix(t,i){return e(this,void 0,void 0,(function*(){const e=`${this.baseUrl}/v1/routematrix?apiKey=${this.apiKey}`,n=yield fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:this.routingOptions.mode||"drive",type:this.routingOptions.type,avoid:this.routingOptions.avoid,traffic:this.routingOptions.traffic,max_speed:this.routingOptions.max_speed,units:this.routingOptions.units,sources:t,targets:i})});if(!n.ok)throw new M(`Route Matrix API failed: ${n.statusText}`,n.status,n.statusText);return yield n.json()}))}calculateTravelTime(t,i){return e(this,void 0,void 0,(function*(){return(yield this.calculateMatrix([{location:t}],[{location:i}])).sources_to_targets[0][0].time}))}calculateTimesToLocation(t,i){return e(this,void 0,void 0,(function*(){return(yield this.calculateMatrix(this.toMatrixLocations(t),this.toMatrixLocations([i]))).sources_to_targets.map((t=>t[0].time))}))}calculateTimesFromLocation(t,i){return e(this,void 0,void 0,(function*(){return(yield this.calculateMatrix(this.toMatrixLocations([t]),this.toMatrixLocations(i))).sources_to_targets[0].map((t=>t.time))}))}toMatrixLocations(t){return t.map((t=>({location:t})))}}class Z{constructor(t,e){this.baseUrl=t.baseUrl||"https://api.geoapify.com",this.apiKey=t.apiKey,this.routingOptions=e}calculateConsecutiveTravelTimes(t){var i,n;return e(this,void 0,void 0,(function*(){if(t.length<2)return[];const e=t.map((t=>`lonlat:${t[0]},${t[1]}`)).join("|"),s=this.constructRoutingUrl(e),o=yield fetch(s);if(!o.ok)throw new J(`Routing API failed: ${o.statusText}`,o.status,o.statusText);const a=yield o.json(),r=null===(i=null==a?void 0:a.features)||void 0===i?void 0:i[0];return r&&(null===(n=r.properties)||void 0===n?void 0:n.legs)?r.properties.legs.map((t=>t.time)):new Array(t.length-1).fill(0)}))}calculateLegData(t){return e(this,void 0,void 0,(function*(){return(yield this.calculateRouteData(t)).legs}))}calculateRouteData(t){var i,n;return e(this,void 0,void 0,(function*(){if(t.length<2)return{legs:[],waypoints:[]};const e=t.map((t=>`lonlat:${t[0]},${t[1]}`)).join("|"),s=this.constructRoutingUrl(e),o=yield fetch(s);if(!o.ok)throw new J(`Routing API failed: ${o.statusText}`,o.status,o.statusText);const a=yield o.json(),r=null===(i=null==a?void 0:a.features)||void 0===i?void 0:i[0];return r&&(null===(n=r.properties)||void 0===n?void 0:n.legs)?{legs:r.properties.legs||[],waypoints:r.properties.waypoints||[]}:{legs:[],waypoints:[]}}))}constructRoutingUrl(t){let e=`${this.baseUrl}/v1/routing?waypoints=${t}&apiKey=${this.apiKey}`;return this.routingOptions.mode&&(e+=`&mode=${this.routingOptions.mode}`),this.routingOptions.type&&(e+=`&type=${this.routingOptions.type}`),this.routingOptions.units&&(e+=`&units=${this.routingOptions.units}`),this.routingOptions.avoid&&this.routingOptions.avoid.length>0&&(e+=`&avoid=${this.routingOptions.avoid.map((t=>t.type)).join("|")}`),this.routingOptions.traffic&&(e+=`&traffic=${this.routingOptions.traffic}`),this.routingOptions.max_speed&&(e+=`&max_speed=${this.routingOptions.max_speed}`),e}}const tt=1e-6;class et{static findOptimalInsertionPoint(t,i,n,s,o){return e(this,void 0,void 0,(function*(){if(0===n.length)return 0;const e=this.getInsertionPositions(n.length,(null==o?void 0:o.canInsertBeforeFirst)||!1,(null==o?void 0:o.canInsertAfterLast)||!1);if(1===e.length)return e[0];const a=this.buildTravelTimeMap((null==o?void 0:o.travelTimes)||[]),r=yield this.getConsecutiveTimes(t,i,n,a);let l=e[0],d=Number.POSITIVE_INFINITY;for(const t of e){const e=this.calculateInsertionCost(t,n,s,a,r);e<d&&(d=e,l=t)}return l}))}static getConsecutiveTimes(t,i,n,s){return e(this,void 0,void 0,(function*(){if(n.length<2)return[];const e=t.getAgentFeature(i),o=e.properties.legs||[],a=(e.properties.waypoints||[]).map((t=>t.location||t.original_location)),r=this.findSubRouteStartIndex(a,n),l=[];for(let e=0;e<n.length-1;e++){const i=n[e],a=n[e+1];if(this.sameLocation(i,a)){l.push(0);continue}if(-1!==r){const t=r+e,i=t+1,n=o.find((e=>e.from_waypoint_index===t&&e.to_waypoint_index===i));if(n&&"number"==typeof n.time&&n.time>=0){l.push(n.time);continue}}const d=this.getTravelTimeKey(i,a),c=s.get(d);if(void 0!==c){l.push(c);continue}const p=(yield t.getRoutingHelper().calculateConsecutiveTravelTimes([i,a]))[0];if("number"!=typeof p)throw new Error(`Unable to calculate travel time between ${i[0]},${i[1]} and ${a[0]},${a[1]}.`);l.push(p)}return l}))}static findSubRouteStartIndex(t,e){if(0===e.length||t.length<e.length)return-1;const i=t.length-e.length;for(let n=0;n<=i;n++){let i=!0;for(let s=0;s<e.length;s++)if(!this.sameLocation(t[n+s],e[s])){i=!1;break}if(i)return n}return-1}static sameLocation(t,e){return Math.abs(t[0]-e[0])<=tt&&Math.abs(t[1]-e[1])<=tt}static calculateInsertionCost(t,e,i,n,s){if(t<=0)return this.getTravelTime(n,i,e[0]);if(t>=e.length)return this.getTravelTime(n,e[e.length-1],i);const o=t-1;return this.getTravelTime(n,e[o],i)+this.getTravelTime(n,i,e[t])-s[o]}static buildTravelTimeMap(t){const e=new Map;for(const i of t)e.set(this.getTravelTimeKey(i.locationFrom,i.locationTo),i.time);return e}static getTravelTime(t,e,i){const n=this.getTravelTimeKey(e,i),s=t.get(n);if(void 0===s)throw new Error(`Missing travel time for pair ${n}.`);return s}static getTravelTimeKey(t,e){return`${t[0]},${t[1]}->${e[0]},${e[1]}`}static getInsertionPositions(t,e,i){const n=i?t:t-1,s=[];for(let t=e?0:1;t<=n;t++)s.push(t);return s}}class it{execute(t,i,n){return e(this,void 0,void 0,(function*(){const e=new Set;for(const n of i){const i=this.removeJobFromResult(t,n);-1!==i&&e.add(i)}for(const i of e)yield X.recalculate(t,i),z.validate(t,i);return!0}))}removeJobFromResult(t,e){const i=t.getAgentIndexForJob(e);if(void 0===i)return-1;const n=t.getAgentFeature(i),s=n.properties.waypoints,o=G.buildLegDataMap(s,n.properties.legs||[]);G.removeJobsFromWaypoints(s,e);const a=G.removeEmptyWaypoints(s,o);return n.properties.waypoints=a.waypoints,a.legs&&(n.properties.legs=a.legs),this.addToUnassignedJobs(t,e),i}addToUnassignedJobs(t,e){const i=t.getRawData();i.properties.issues||(i.properties.issues={});const n=i.properties.issues;n.unassigned_jobs||(n.unassigned_jobs=[]),n.unassigned_jobs.includes(e)||n.unassigned_jobs.push(e)}}class nt{execute(t,i,n){return e(this,void 0,void 0,(function*(){const e=new Map;for(const n of i){const i=t.getAgentIndexForJob(n);void 0!==i&&(e.has(i)||e.set(i,[]),e.get(i).push(n))}for(const[i,n]of e.entries()){const e=new Set(n),s=t.getAgentJobs(i).filter((t=>!e.has(t))),o=new Set(s),a=t.cloneInputData(),r=new Set(t.getAgentShipments(i)),l=a.agents[i];l&&(a.agents=[l],q.restrictAssignmentsToTargetSet(a.jobs||[],o),q.restrictAssignmentsToTargetSet(a.shipments||[],r),yield t.executeAgentPlan(i,a),z.validate(t,i))}return!0}))}}class st{static getEndPosition(t,i){return e(this,void 0,void 0,(function*(){const e=(yield t.getOrCreateAgentFeature(i)).properties.waypoints||[];if(0===e.length)return 0;const n=e.length-1;return(e[n].actions||[]).some((t=>"end"===t.type))?n:n+1}))}static hasAgentStartLocation(t,e){const i=t.getRawData().properties.params.agents[e];return void 0!==i.start_location_index||void 0!==i.start_location}static hasAgentEndLocation(t,e){const i=t.getRawData().properties.params.agents[e];return void 0!==i.end_location_index||void 0!==i.end_location}}const ot=1e-6;class at extends st{static determineInsertPosition(t,i,n,s){var o;return e(this,void 0,void 0,(function*(){const e=V.getJobByIndex(t,n),a=V.resolveJobLocation(t,e),r=t.getAgentFeature(i).properties.waypoints||[];if(Y.shouldAppend(s))return{position:yield this.getEndPosition(t,i),createWaypoint:!0};if(Y.hasExplicitInsertPosition(s))return{position:Y.resolveInsertPosition(s),createWaypoint:!0};if(void 0!==s.afterWaypointIndex&&!s.append){const e=null!==(o=s.afterWaypointIndex)&&void 0!==o?o:0,l=this.findExistingWaypointByLocation(r,a,e+1);return-1!==l?{position:l,createWaypoint:!1}:{position:yield this.findOptimalInsertPositionAfter(t,i,n,e),createWaypoint:!0}}const l=this.findExistingWaypointByLocation(r,a,0);return-1!==l?{position:l,createWaypoint:!1}:{position:yield this.findOptimalInsertPosition(t,i,n),createWaypoint:!0}}))}static findOptimalInsertPosition(t,i,n){return e(this,void 0,void 0,(function*(){const e=V.getJobByIndex(t,n),s=V.resolveJobLocation(t,e),o=t.getAgentFeature(i);if(!o)return 1;const a=Y.extractRouteLocations(o);if(0===a.length)return 1;const r=yield this.calculateTravelTimes(t,a,s);return yield et.findOptimalInsertionPoint(t,i,a,s,{canInsertBeforeFirst:!this.hasAgentStartLocation(t,i),canInsertAfterLast:!this.hasAgentEndLocation(t,i),travelTimes:r})}))}static findOptimalInsertPositionAfter(t,i,n,s){return e(this,void 0,void 0,(function*(){const e=V.getJobByIndex(t,n),o=V.resolveJobLocation(t,e),a=t.getAgentFeature(i),r=Y.extractRouteLocations(a),l=Math.max(0,s),d=r.slice(l);if(0===d.length)return l;const c=yield this.calculateTravelTimes(t,d,o);return l+(yield et.findOptimalInsertionPoint(t,i,d,o,{canInsertBeforeFirst:!1,canInsertAfterLast:!this.hasAgentEndLocation(t,i),travelTimes:c}))}))}static calculateTravelTimes(t,i,n){return e(this,void 0,void 0,(function*(){const e=t.getMatrixHelper(),[s,o]=yield Promise.all([e.calculateTimesToLocation(i,n),e.calculateTimesFromLocation(n,i)]),a=[];for(let t=0;t<i.length;t++)a.push({locationFrom:i[t],locationTo:n,time:s[t]}),a.push({locationFrom:n,locationTo:i[t],time:o[t]});return a}))}static findExistingWaypointByLocation(t,e,i){for(let n=Math.max(0,i);n<t.length;n++)if(this.sameLocation(t[n].original_location||t[n].location,e))return n;return-1}static sameLocation(t,e){return Math.abs(t[0]-e[0])<=ot&&Math.abs(t[1]-e[1])<=ot}}class rt{static createAssignStrategy(t){const e=this.assignStrategies.get(t);if(!e)throw new C(`Unknown assign strategy: ${t}`,t,"assign");return e}static createRemoveStrategy(t){const e=this.removeStrategies.get(t);if(!e)throw new C(`Unknown remove strategy: ${t}`,t,"remove");return e}}rt.assignStrategies=new Map([[i,new class{execute(t,i,n,s){return e(this,void 0,void 0,(function*(){yield this.removeJobsFromCurrentAgents(t,n,s);const e=new Set(t.getAgentJobs(i));n.forEach((t=>e.add(t)));const o=new Set(t.getAgentShipments(i)),a=t.cloneInputData(),r=a.agents[i];if(!r)return!1;q.extendAgentTimeWindows(r),this.clearTimeWindowsForAssignedJobs(a.jobs||[],n),a.agents=[r],q.restrictAssignmentsToTargetSet(a.jobs||[],e),q.restrictAssignmentsToTargetSet(a.shipments||[],o);const l=yield t.executeAgentPlan(i,a);return z.validate(t,i),l}))}removeJobsFromCurrentAgents(t,s,o){var a;return e(this,void 0,void 0,(function*(){const e=null!==(a=o.removeStrategy)&&void 0!==a?a:n,r=e===i?new nt:new it,l={strategy:e};yield r.execute(t,s,l)}))}clearTimeWindowsForAssignedJobs(t,e){for(const i of e){const e=t[i];e&&delete e.time_windows}}}],[n,new class{execute(t,i,n,s){return e(this,void 0,void 0,(function*(){yield this.removeJobsFromCurrentAgents(t,n,s);for(let e=0;e<n.length;e++){const o=yield at.determineInsertPosition(t,i,n[e],s);G.insertJobWaypoint(t,i,n[e],o),yield X.recalculate(t,i)}return z.validate(t,i),!0}))}removeJobsFromCurrentAgents(t,s,o){var a;return e(this,void 0,void 0,(function*(){const e=null!==(a=o.removeStrategy)&&void 0!==a?a:n,r=e===i?new nt:new it,l={strategy:e};yield r.execute(t,s,l)}))}}]]),rt.removeStrategies=new Map([[i,new nt],[n,new it]]);class lt{execute(t,i,n){return e(this,void 0,void 0,(function*(){const e=new Set;for(const n of i){const i=this.removeShipmentFromResult(t,n);-1!==i&&e.add(i)}for(const i of e)yield X.recalculate(t,i),z.validate(t,i);return!0}))}removeShipmentFromResult(t,e){const i=t.getAgentIndexForShipment(e);if(void 0===i)return-1;const n=t.getAgentFeature(i),s=n.properties.waypoints,o=n.properties.legs||[];G.removeShipmentsFromWaypoints(s,e);const a=G.buildLegDataMap(s,o),r=G.removeEmptyWaypoints(s,a);return n.properties.waypoints=r.waypoints,r.legs&&(n.properties.legs=r.legs),i}}class dt{execute(t,i,n){return e(this,void 0,void 0,(function*(){const e=new Map;for(const n of i){const i=t.getAgentIndexForShipment(n);void 0!==i&&(e.has(i)||e.set(i,[]),e.get(i).push(n))}for(const[i,n]of e.entries()){const e=new Set(n),s=t.getAgentShipments(i).filter((t=>!e.has(t))),o=new Set(s),a=t.cloneInputData(),r=new Set(t.getAgentJobs(i)),l=a.agents[i];l&&(a.agents=[l],q.restrictAssignmentsToTargetSet(a.jobs||[],r),q.restrictAssignmentsToTargetSet(a.shipments||[],o),yield t.executeAgentPlan(i,a),z.validate(t,i))}return!0}))}}const ct=1e-6;class pt extends st{static determineShipmentInsertPositions(t,i,n,s){return e(this,void 0,void 0,(function*(){if(Y.shouldAppend(s)){const e=yield this.getAppendToEndPositions(t,i);return Object.assign(Object.assign({},e),{createPickupWaypoint:!0,createDeliveryWaypoint:!0})}if(Y.hasExplicitInsertPosition(s)){const t=Y.resolveInsertPosition(s);return{pickup:t,delivery:t+1,createPickupWaypoint:!0,createDeliveryWaypoint:!0}}if(void 0!==s.afterWaypointIndex&&!s.append){const e=s.afterWaypointIndex;return yield this.findOptimalShipmentPositionsAfter(t,i,n,e)}return yield this.findOptimalShipmentPositions(t,i,n)}))}static getAppendToEndPositions(t,i){return e(this,void 0,void 0,(function*(){const e=(yield t.getOrCreateAgentFeature(i)).properties.waypoints||[];return 0===e.length?{pickup:0,delivery:1}:e[e.length-1].actions.some((t=>"end"===t.type))?{pickup:e.length-1,delivery:e.length}:{pickup:e.length,delivery:e.length+1}}))}static findOptimalShipmentPositions(t,i,n){return e(this,void 0,void 0,(function*(){const e=V.getShipmentByIndex(t,n),s=V.resolveShipmentStepLocation(t,e.pickup),o=V.resolveShipmentStepLocation(t,e.delivery),a=t.getAgentFeature(i),r=Y.extractRouteLocations(a),l=a.properties.waypoints||[],d=this.findExistingWaypointByOriginalLocation(l,s,0),c=this.findExistingWaypointByOriginalLocation(l,o,0);let p,u=!0,h=!0,g=0,m=0;if(-1!==d)u=!1,g=d;else if(-1!==c){const e=r.slice(0,c+1);p=yield this.calculateTravelTimes(t,e,s),g=yield et.findOptimalInsertionPoint(t,i,e,s,{canInsertBeforeFirst:!this.hasAgentStartLocation(t,i),canInsertAfterLast:!1,travelTimes:p})}else 0===r.length?g=0:1===r.length?g=this.hasAgentStartLocation(t,i)?1:0:(p=yield this.calculateTravelTimes(t,r,s),g=yield et.findOptimalInsertionPoint(t,i,r,s,{canInsertBeforeFirst:!this.hasAgentStartLocation(t,i),canInsertAfterLast:!this.hasAgentEndLocation(t,i),travelTimes:p}));if(-1!==c&&c>=g)h=!1,m=c;else{const e=[...r];u&&e.splice(g,0,s);const n=yield this.calculateTravelTimes(t,e.slice(g),o,p);m=g+(yield et.findOptimalInsertionPoint(t,i,e.slice(g),o,{canInsertBeforeFirst:!1,travelTimes:n}))}return{pickup:g,delivery:m,createPickupWaypoint:u,createDeliveryWaypoint:h}}))}static findOptimalShipmentPositionsAfter(t,i,n,s){return e(this,void 0,void 0,(function*(){const e=V.getShipmentByIndex(t,n),o=V.resolveShipmentStepLocation(t,e.pickup),a=V.resolveShipmentStepLocation(t,e.delivery),r=t.getAgentFeature(i),l=Y.extractRouteLocations(r),d=r.properties.waypoints||[],c=this.findExistingWaypointByOriginalLocation(d,o,0),p=this.findExistingWaypointByOriginalLocation(d,a,0);let u,h=!0,g=!0,m=0,y=0,v=-1;if(-1!==c&&c>=s&&(h=!1,m=c,v=c),-1===v){const e=Math.max(0,s),n=-1!==p&&p>=e;let a;const r=n?l.slice(e,p+1):l.slice(e);if(0===r.length)m=e,v=e;else{const s=n?{canInsertBeforeFirst:!1,canInsertAfterLast:!1}:{canInsertBeforeFirst:!1,canInsertAfterLast:!this.hasAgentEndLocation(t,i)};u=yield this.calculateTravelTimes(t,r,o),a=yield et.findOptimalInsertionPoint(t,i,r,o,Object.assign(Object.assign({},s),{travelTimes:u})),v=e+a,m=v}}if(-1!==p&&p>=v)g=!1,y=h?p+1:p;else{const e=[...l];h&&e.splice(v,0,o);const n=yield this.calculateTravelTimes(t,e.slice(v),a,u),s=yield et.findOptimalInsertionPoint(t,i,e.slice(v),a,{canInsertBeforeFirst:!1,travelTimes:n});y=h?m+s+1:m+s}return{pickup:m,delivery:y,createPickupWaypoint:h,createDeliveryWaypoint:g}}))}static findExistingWaypointByOriginalLocation(t,e,i){for(let n=Math.max(0,i);n<t.length;n++)if(this.sameLocation(t[n].original_location,e))return n;return-1}static sameLocation(t,e){return Math.abs(t[0]-e[0])<=ct&&Math.abs(t[1]-e[1])<=ct}static calculateTravelTimes(t,i,n,s){return e(this,void 0,void 0,(function*(){const e=t.getMatrixHelper(),[o,a]=yield Promise.all([e.calculateTimesToLocation(i,n),e.calculateTimesFromLocation(n,i)]),r=s||[];for(let t=0;t<i.length;t++)r.push({locationFrom:i[t],locationTo:n,time:o[t]}),r.push({locationFrom:n,locationTo:i[t],time:a[t]});return r}))}}class ut{static createAssignStrategy(t){const e=this.assignStrategies.get(t);if(!e)th