@elite-dangerous-almanac/core 0.2.2 → 0.2.4

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.
@@ -1791,6 +1791,31 @@ up straight through with no disambiguation at all. Both paths are evidence that
1791
1791
  against rows already here — the large rack is 3A and its other Merc row is 900 MC, the
1792
1792
  medium is 2B and its Lockdown row is 800 MC — and that corroboration is what carries
1793
1793
  the weight.
1794
+ - **Ten of the 22 carry a default experimental effect** applied beside the grade-1
1795
+ blueprint, recorded as `experimentalEffectSymbol`: Screening Shell on both Double
1796
+ Screaming Fragment Cannons, Incendiary Rounds on the Long Range Mining Laser,
1797
+ Phasing Sequence on the Rapid Phase Multi-Cannon, Feedback Cascade on the Enduring
1798
+ Feedback Rail Gun, Drag Munitions on both Drag Seeker Missile Racks, Thermal Cascade
1799
+ on the Lightweight Thermal Seeker Missile Rack, and FSD Interrupt on both Lockdown
1800
+ Seeker Missile Racks. Source: repository-owner in-game observation, recorded
1801
+ 2026-08-29 UTC; no registry publishes them. These rows still carry no `modifiers`:
1802
+ the effect is recorded, the unpublished grade-1 blueprint transformation is not.
1803
+ - **Two independent checks each corroborate nine of the ten, and between them cover
1804
+ all ten.** The first: the effect is one the stock module's own experimental menu
1805
+ offers, so the shop is baking in an effect the module can carry
1806
+ (`engineering-options.jsonc`). That covers every row but the Mining Laser, whose
1807
+ base module offers no experimental effect at all. The second: the same base module
1808
+ already carries the same effect on a catalogued community-goal or tech-broker
1809
+ variant. That covers every row but the large Drag Seeker Missile Rack, whose
1810
+ corroboration is its medium twin rather than a variant of its own symbol.
1811
+ - **The mining laser is the weakest of the ten.** Incendiary Rounds is outside
1812
+ `Hpt_MiningLaser_Fixed_Small`'s experimental menu — it is the only row a shop menu
1813
+ could not have offered — so only the twin check speaks for it, and a twin is
1814
+ consistency more than evidence. It is recorded because it was observed. The
1815
+ blueprint names of the seeker racks and the rail gun do echo their effects
1816
+ (`SeekerMissileRack*_Lockdown`, `_LightWeightThermal`, `_Drag`, "Enduring
1817
+ Feedback"), but a name is weaker evidence than either check above, and no row
1818
+ rests on one.
1794
1819
  - **`communityGoal`** — modules awarded for taking part in a community goal. Source:
1795
1820
  EDSY's stored-module presets, which record each reward as an encoded module state; the
1796
1821
  blueprint, grade and experimental effect were
@@ -1 +1 @@
1
- import{fixedSlotReason,validateLoadout}from"./chunk-OJC6AUL7.js";import{calculateModuleLimits}from"./chunk-KPETDYQX.js";import{publishLoadoutInternals,normalizeLoadoutEvent,preEngineeredVariantFor,moduleFitProblem,effectiveModule,moduleFitError}from"./chunk-SS6XK336.js";import{getShipBySymbol}from"./chunk-6UNAD74Z.js";import{parseSlef,toSlef,stringifySlef,getLoadoutModifier}from"./chunk-T4MKUKYS.js";import{getSourceModuleValue}from"./chunk-NIURLW2F.js";import{statesInertModifiers,rolledOverFixedArticle,isNonOutfittingSlot,isBuiltInHullModule,cloneLoadoutModule,cloneModuleStats,availableBlueprintsFor,availableExperimentalsFor,ownKeyIn,FITTED_ITEM,blueprintAvailableFor,blueprintRoutesFor,experimentalAvailableFor,primitiveEngineeringInputsFor,missingBaseLabels,journalModifiersFor,getPreEngineeredStats,getPreEngineeredJournalModifiers,getPreEngineeredModifiers,ordinaryEngineeringProof,unresolvedModifiers,matchingKeyIn,isCargoHatchSlot,orderBySlotLayout}from"./chunk-4OTQBHQL.js";import{builtInModuleBySymbol}from"./chunk-3LZXB2MC.js";import{getPreEngineeredVariants}from"./chunk-PL75RTA2.js";import{ALL_MODULES}from"./chunk-7ZERP4TB.js";import{getExperimentalEffect}from"./chunk-77I24V6B.js";import{singleJumpRange}from"./chunk-VTMCSCXV.js";import{calculateUnladenMass,calculateCargoCapacity,calculateFuelCapacity}from"./chunk-DCB4COCL.js";import{resolveBlueprintForModule}from"./chunk-OLKNYGGT.js";import{getBlueprintGrade}from"./chunk-AYAKU4YA.js";import{getDefaultLoadout}from"./chunk-GRIK3EDH.js";import{getExperimentalsForModule}from"./chunk-GLWPSVFV.js";import{baseStats,computeModifiers,labelsForDamageType,scaleForLabel}from"./chunk-CJQ37JII.js";import{ammunitionCapacity}from"./chunk-AA3K5XUE.js";import{loadoutSlotName}from"./chunk-KAA4VOOB.js";import{parseSlotName,enumerateSlots}from"./chunk-RAO35XDF.js";import{normalizeKey,CATALOGUE_KEY}from"./chunk-BKWLI44T.js";import{truncate,describeValue,requireString,requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";var REBUY_FRACTION=.05;function exportLoadoutEvent(input,options){const fromSource=options.credits==="source";const source=fromSource?input.sourcePurchase:null;const totals=source!==null&&!input.sourceTotalsVoided&&sourceTotalsHold(input.modules,source)?source:null;const hullValue=fromSource?source?.hullValue??null:input.retailHullValue;const modulesValue=fromSource?totals?.modulesValue??null:computedModulesValue(input.modules,input.statsFor);const rebuy=fromSource?totals?.rebuy??null:hullValue===null||modulesValue===null?null:Math.trunc((hullValue+modulesValue)*REBUY_FRACTION);return{Ship:input.shipSymbol.toLowerCase(),...input.shipName===void 0?{}:{ShipName:input.shipName},...input.shipIdent===void 0?{}:{ShipIdent:input.shipIdent},...hullValue===null?{}:{HullValue:hullValue},...modulesValue===null?{}:{ModulesValue:modulesValue},UnladenMass:input.unladenMass,CargoCapacity:input.cargoCapacity,...input.maxJumpRange===null?{}:{MaxJumpRange:input.maxJumpRange},FuelCapacity:{Main:input.fuelCapacity.main,Reserve:input.fuelCapacity.reserve},...rebuy===null?{}:{Rebuy:rebuy},Modules:exportModules(input,options,fromSource)}}function exportModules(input,options,fromSource){const ordered=options.moduleOrder==="slots"?slotOrderedModules(input.modules,input.layout):[...input.modules.values()];return ordered.map(module=>{const on=module.On??(options.explicitPower?true:void 0);const priority=module.Priority??(options.explicitPower?0:void 0);const value=fromSource?sourceModuleValue(module,input.sourcePurchase):moduleValue(module,input.statsFor);return{Slot:module.Slot,Item:module.Item.toLowerCase(),...on===void 0?{}:{On:on},...priority===void 0?{}:{Priority:priority},...module.Health===void 0?{}:{Health:module.Health},...typeof value==="number"?{Value:value}:{},...module.Engineering===void 0?{}:{Engineering:cloneLoadoutModule(module).Engineering}}})}function slotOrderedModules(modules,layout){return orderBySlotLayout([...modules.values()],layout,module=>module.Slot)}function computedModulesValue(modules,statsFor){let sum=0;for(const module of modules.values()){const value=moduleValue(module,statsFor);if(value==="unknown")return null;if(value!=="free")sum+=value}return sum}function moduleValue(module,statsFor){const stats=statsFor(module);if(stats!==null)return stats.cost??"unknown";return isNonOutfittingSlot(module.Slot)||isBuiltInHullModule(module)?"free":"unknown"}var SOURCE_ITEM="ShipLoadout: sourcePurchase moduleValues[].item";function sourceModuleValue(module,source){const entry=source===null?null:getSourceModuleValue(source,module.Slot);if(entry===null)return"unknown";return normalizeKey(entry.item,SOURCE_ITEM)===normalizeKey(module.Item,FITTED_ITEM)?entry.value:"unknown"}function sourceTotalsHold(modules,source){for(const entry of source.moduleValues){const key=matchingKeyIn(modules,entry.slot);const fitted=key===null?void 0:modules.get(key);if(!fitted)return false;if(isCargoHatchSlot(entry.slot)&&entry.value===0)continue;if(normalizeKey(fitted.Item,FITTED_ITEM)!==normalizeKey(entry.item,SOURCE_ITEM)){return false}}return true}var SLOT_KEY="ShipLoadout: slotKey";var FITTED_SLOT="ShipLoadout: fitted module Slot";var LoadoutEditError=class extends TypeError{code;constraint;params;constructor(message,code,params,constraint){super(message);this.code=code;this.params=deepFreeze(structuredClone(params));if(constraint!==void 0)this.constraint=constraint}};var experimentalEffectUnsupported=(code,params)=>deepFreeze({kind:"unsupported",code:code,params:params});var engineeringNormalizationUnsupported=(code,params)=>deepFreeze({kind:"unsupported",code:code,params:params});function weighable(tonnes){return tonnes!==void 0&&Number.isFinite(tonnes)&&tonnes>=0?tonnes:void 0}var AGGREGATE_STATS=["mass","cargoCapacity","fuelCapacity"];var ShipLoadout=class _ShipLoadout{#ship;#shipSymbol;#modules;#moduleStats;#primitiveModifiers;#top;#sourcePurchase;#importOutcomes;#slotCache=/* @__PURE__ */new Map;#layoutCache;constructor(ship,shipSymbol,modules,top,sourcePurchase=null,moduleStats=/* @__PURE__ */new Map,primitiveModifiers=/* @__PURE__ */new Map,importOutcomes=deepFreeze([])){this.#ship=ship;this.#shipSymbol=shipSymbol;this.#modules=modules;this.#top=top;this.#sourcePurchase=sourcePurchase;this.#moduleStats=moduleStats;this.#primitiveModifiers=primitiveModifiers;this.#importOutcomes=importOutcomes;publishLoadoutInternals(this,{ship:ship,modules:()=>[...this.#modules.values()],effectiveModules:()=>this.#modulesForEffectiveStats(),effectiveModule:module=>this.#moduleForEffectiveStats(module),statsFor:module=>this.#statsFor(module),layout:()=>this.#layout(),resolveDrive:()=>this.#resolveDrive(),frameShiftDriveModule:()=>this.#frameShiftDrive()?.module,calculationModules:()=>this.#calculationModules(),statedMainFuel:()=>this.#top.FuelCapacity?.Main})}static fromSlef(input,index=0){const entries=parseSlef(input);const entry=entries[index];if(!entry){throw new TypeError(`ShipLoadout.fromSlef: no entry at index ${truncate(index)} (have ${entries.length})`)}const imported=normalizeLoadoutEvent(entry.data);const ship=getShipBySymbol(imported.shipSymbol);if(!ship){throw new TypeError(`ShipLoadout.fromSlef: unknown hull "${truncate(imported.shipSymbol)}"`)}return _ShipLoadout.#fromImported(imported,ship)}static fromLoadout(event){if(event===null||typeof event!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: event must be a Loadout event, received ${describeValue(event)}`)}const imported=normalizeLoadoutEvent(event);const ship=getShipBySymbol(imported.shipSymbol);if(!ship){throw new TypeError(`ShipLoadout.fromLoadout: unknown hull "${truncate(imported.shipSymbol)}"`)}return _ShipLoadout.#fromImported(imported,ship)}static#fromImported(imported,ship){const outcomes=[...imported.outcomes];const loadout=new _ShipLoadout(ship,imported.shipSymbol,imported.modules,imported.top,imported.sourcePurchase,imported.moduleStats,imported.primitiveModifiers,outcomes);const{UnladenMass:UnladenMass,CargoCapacity:CargoCapacity,FuelCapacity:FuelCapacity}=imported.top;for(const module of[...imported.modules.values()]){const unresolved=loadout.#rollStatedRecipe(module);if(unresolved!==null)outcomes.push(unresolved)}if(UnladenMass!==void 0)loadout.#top.UnladenMass=UnladenMass;if(CargoCapacity!==void 0)loadout.#top.CargoCapacity=CargoCapacity;if(FuelCapacity!==void 0)loadout.#top.FuelCapacity=FuelCapacity;deepFreeze(outcomes);return loadout}#rollStatedRecipe(module){const engineering=module.Engineering;if(!engineering||typeof engineering.BlueprintName!=="string")return null;const stated=engineering.Modifiers;const stats=this.#statsFor(module);if(stated!==void 0&&(this.#moduleStats.has(module.Slot)||stats===null||!statesInertModifiers(stats,stated))){return null}if(stated===void 0&&this.#moduleStats.has(module.Slot)){const variant=preEngineeredVariantFor(module);if(variant?.acquisition!=="mercenary"||engineering.Level<=variant.grade){return null}}try{this.applyBlueprint(module.Slot,engineering.BlueprintName,{grade:engineering.Level,quality:engineering.Quality??1,...typeof engineering.ExperimentalEffect==="string"?{experimentalEffectSymbol:engineering.ExperimentalEffect}:{}});if(stated!==void 0){return{action:"rerolledEngineering",slot:module.Slot,sourceSymbol:module.Item,blueprintSymbol:engineering.BlueprintName}}const passedOver=rolledOverFixedArticle(module.Item,engineering);return passedOver===null?null:{action:"ambiguousEngineering",slot:module.Slot,sourceSymbol:module.Item,blueprintSymbol:engineering.BlueprintName,preEngineeredVariant:passedOver}}catch(error){if(!(error instanceof TypeError)&&!(error instanceof RangeError))throw error;return{action:"unresolvedEngineering",slot:module.Slot,sourceSymbol:module.Item,blueprintSymbol:engineering.BlueprintName}}}static empty(shipSymbol){const requested=requireString(shipSymbol,"ShipLoadout.empty: shipSymbol");const ship=getShipBySymbol(requested);if(!ship){throw new TypeError(`ShipLoadout.empty: no slot layout for hull "${truncate(shipSymbol)}"`)}const fitted=(getDefaultLoadout(ship.symbol)?.modules??[]).filter(module=>{const parsed=parseSlotName(module.slot);return parsed!==null&&fixedSlotReason(parsed)!==null});return new _ShipLoadout(ship,ship.symbol,new Map(fitted.map(module=>[module.slot,{Slot:module.slot,Item:module.symbol}])),{})}static default(shipSymbol){const requested=requireString(shipSymbol,"ShipLoadout.default: shipSymbol");const ship=getShipBySymbol(requested);if(!ship){throw new TypeError(`ShipLoadout.default: no default loadout for hull "${truncate(shipSymbol)}"`)}const loadout=getDefaultLoadout(ship.symbol);return new _ShipLoadout(ship,loadout.symbol,new Map(loadout.modules.map(module=>[module.slot,{Slot:module.slot,Item:module.symbol}])),{})}get shipSymbol(){return this.#shipSymbol}get shipName(){return this.#top.ShipName??null}get shipIdent(){return this.#top.ShipIdent??null}get unladenMass(){return this.#top.UnladenMass??this.#computedUnladenMass()}#computedUnladenMass(){return calculateUnladenMass(this.#ship.hullMass,this.#calculationModules())}get fuelCapacity(){const cap=this.#top.FuelCapacity;if(cap?.Main!==void 0&&cap.Reserve!==void 0){return Object.freeze({main:cap.Main,reserve:cap.Reserve})}const computed=this.#computedFuelCapacity();return Object.freeze({main:cap?.Main??computed.main,reserve:cap?.Reserve??computed.reserve})}get cargoCapacity(){return this.#top.CargoCapacity??this.#computedCargoCapacity()}#computedCargoCapacity(){return calculateCargoCapacity(this.#calculationModules())}#computedFuelCapacity(){return calculateFuelCapacity(this.#ship.reserveFuelCapacity,this.#calculationModules())}get hullValue(){return this.#top.HullValue??null}get modulesValue(){return this.#top.ModulesValue??null}get rebuy(){return this.#top.Rebuy??null}get sourcePurchase(){return this.#sourcePurchase}get importOutcomes(){return this.#importOutcomes}validation(){const slots=this.#layout();const byKey=new Map(slots.map(slot=>[normalizeKey(slot.key,CATALOGUE_KEY),slot]));const modules=[...this.#modules.values()].map(module=>{const stats=this.#statsFor(module);const slot=byKey.get(normalizeKey(module.Slot,FITTED_SLOT));const builtIn=stats===null&&isNonOutfittingSlot(module.Slot)||isBuiltInHullModule(module);const fitProblem=stats&&slot&&!builtIn?moduleFitProblem(this.#shipSymbol,slot,stats):null;const thrusterMaxMass=weighable(stats?.slot==="thrusters"?effectiveModule(this.#moduleForEffectiveStats(module),stats)?.maxMass:void 0);return{slot:module.Slot,symbol:module.Item,requiresKnownSlot:!builtIn,fitError:fitProblem?.message??null,...fitProblem===null?{}:{fitConstraint:fitProblem.constraint},...fitProblem?.params===void 0?{}:{fitParams:fitProblem.params},...stats?.exclusionGroup===void 0?{}:{exclusionGroup:stats.exclusionGroup},...stats?.limitGroup===void 0?{}:{limitGroup:stats.limitGroup},...stats?.limitIncrease===void 0?{}:{limitIncrease:stats.limitIncrease},...thrusterMaxMass===void 0?{}:{thrusterMaxMass:thrusterMaxMass}}});const dry=weighable(this.unladenMass);const fuel=weighable(this.fuelCapacity.main);const cargo=weighable(this.cargoCapacity);const mass=dry===void 0?void 0:{dry:dry,...fuel===void 0?{}:{fuel:fuel},...fuel===void 0||cargo===void 0?{}:{cargo:cargo}};return validateLoadout({shipSymbol:this.#shipSymbol,slots:slots,modules:modules,...mass===void 0?{}:{mass:mass}})}slots(kind){const cached=this.#slotCache.get(kind);if(cached!==void 0)return cached;const slots=kind===void 0?this.#layout():this.#layout().filter(slot=>slot.kind===kind);const currentLimits=this.#moduleLimits();const value=deepFreeze(slots.map(slot=>{const stats=this.#moduleStatsAt(slot.key);const fixedReason=fixedSlotReason(slot);const immovableReason=fixedReason!==null?fixedReason:stats?.limitIncrease!==void 0&&this.#moduleLimitRegression(slot.key,null,currentLimits,stats)!==null?"moduleLimit":null;return{...slot,name:loadoutSlotName(slot),module:this.fittedModuleAt(slot.key),removable:immovableReason===null,...immovableReason===null?{}:{immovableReason:immovableReason}}}));this.#slotCache.set(kind,value);return value}fittedModuleAt(slotKey){const module=this.#fittedModuleFor(slotKey);if(!module)return null;const raw=cloneLoadoutModule(module);const stats=this.#statsFor(module);const effective=effectiveModule(this.#moduleForEffectiveStats(module),stats);return deepFreeze({slot:module.Slot,symbol:raw.Item,on:raw.On,priority:raw.Priority,health:raw.Health,value:raw.Value,engineering:raw.Engineering,raw:raw,stats:stats===null?null:cloneModuleStats(stats),effectiveStats:effective===null?null:cloneModuleStats(effective),ammunition:ammunitionCapacity(effective),preEngineeredVariant:preEngineeredVariantFor(raw)})}fittedModules(){return deepFreeze([...this.#modules.keys()].flatMap(key=>{const fitted=this.fittedModuleAt(key);return fitted===null?[]:[fitted]}))}availableBlueprints(slotKey){const module=this.#fittedModuleFor(slotKey);return deepFreeze(module?availableBlueprintsFor(module.Item,this.#statsFor(module)):[])}availableExperimentalEffects(slotKey){const module=this.#fittedModuleFor(slotKey);return deepFreeze(module?availableExperimentalsFor(module.Item,this.#statsFor(module)):[])}modulesForSlot(slotKey){const slot=this.#requireSlot(slotKey);const occupied=new Set([...this.#modules.values()].flatMap(fitted=>{if(normalizeKey(fitted.Slot,FITTED_SLOT)===normalizeKey(slot.key,CATALOGUE_KEY))return[];const group=this.#statsFor(fitted)?.exclusionGroup;return group===void 0?[]:[group]}));const currentLimits=this.#moduleLimits();const currentStats=this.#moduleStatsAt(slot.key);return ALL_MODULES.filter(module=>module.grantOnly===void 0&&moduleFitError(this.#shipSymbol,slot,module)===null&&(module.exclusionGroup===void 0||!occupied.has(module.exclusionGroup))&&this.#moduleLimitRegression(slot.key,module,currentLimits,currentStats)===null)}repairFixedMount(slotKey){const requested=requireString(slotKey,SLOT_KEY);const wanted=normalizeKey(requested,SLOT_KEY);const slot=this.#requireSlot(requested);const fittedKey=this.#fittedKey(requested);const resultSlot=fittedKey??requested;const canonicalKey=slot.key;if(fixedSlotReason(slot)===null){return deepFreeze({status:"refused",slot:resultSlot,reason:"notFixedMount"})}const current=this.#fittedModuleFor(requested);const currentStats=current?this.#statsFor(current):null;const valid=current!==void 0&&currentStats!==null&&(slot.kind==="cargoHatch"?isBuiltInHullModule(current):moduleFitProblem(this.#shipSymbol,slot,currentStats)===null);if(valid){return deepFreeze({status:"unchanged",slot:current.Slot,symbol:current.Item})}const defaultModule=getDefaultLoadout(this.#shipSymbol)?.modules.find(module=>normalizeKey(module.slot,CATALOGUE_KEY)===wanted);if(!defaultModule){return deepFreeze({status:"defaultUnavailable",slot:resultSlot})}const ownKey=ownKeyIn(this.#modules,canonicalKey);const replacement={Slot:ownKey,Item:defaultModule.symbol,...current?.On===void 0?{}:{On:current.On},...current?.Priority===void 0?{}:{Priority:current.Priority},...current?.Health===void 0?{}:{Health:current.Health}};const replacementStats=builtInModuleBySymbol(defaultModule.symbol,"ShipLoadout.repairFixedMount")??(isBuiltInHullModule(replacement)?builtInModuleBySymbol("ModularCargoBayDoor","ShipLoadout.repairFixedMount"):null);if(!replacementStats){return deepFreeze({status:"defaultUnavailable",slot:resultSlot,symbol:defaultModule.symbol})}this.#replaceModule(ownKey,replacement,replacementStats);return deepFreeze({status:"repaired",slot:ownKey,symbol:defaultModule.symbol})}setModule(slotKey,module){const slot=this.#requireSlot(slotKey);if(module===null||module===void 0){throw new TypeError(`ShipLoadout.setModule: no module supplied for "${truncate(slotKey)}" (did the module lookup return undefined?)`)}if(typeof module.symbol!=="string"){throw new TypeError(`ShipLoadout.setModule: module for "${truncate(slotKey)}" must be an outfitting module, received ${describeValue(module)}`)}module=cloneModuleStats(module);const catalogued=builtInModuleBySymbol(module.symbol,FITTED_ITEM);if(catalogued===null){throw new TypeError(`ShipLoadout.setModule: no module is catalogued as "${truncate(module.symbol)}"`)}for(const field of AGGREGATE_STATS){const stated=module[field];if(stated===void 0){if(catalogued[field]===void 0)continue;throw new TypeError(`ShipLoadout.setModule: the supplied record for "${truncate(module.symbol)}" has no ${field}`)}if(typeof stated!=="number"||!Number.isFinite(stated)){throw new TypeError(`ShipLoadout.setModule: the supplied record for "${truncate(module.symbol)}" states a ${field} of ${describeValue(stated)}`)}}const problem=moduleFitProblem(this.#shipSymbol,slot,module);if(problem){if(problem.constraint==="immutableSlot"){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${problem.message}`,"immutableSlot",{slot:slot.key})}throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${problem.message}`,"incompatibleModule",{...problem.params,slot:slot.key,symbol:module.symbol,constraint:problem.constraint},problem.constraint)}if(module.exclusionGroup!==void 0){const conflict=[...this.#modules.values()].find(fitted=>normalizeKey(fitted.Slot,FITTED_SLOT)!==normalizeKey(slot.key,CATALOGUE_KEY)&&this.#statsFor(fitted)?.exclusionGroup===module.exclusionGroup);if(conflict){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${module.exclusionGroup} is limited to one per ship (already fitted in ${truncate(conflict.Slot)})`,"duplicateExclusiveModule",{exclusionGroup:module.exclusionGroup,slot:slot.key,symbol:module.symbol,previousSlot:conflict.Slot,previousSymbol:conflict.Item})}}const limitProblem=this.#moduleLimitRegression(slot.key,module);if(limitProblem!==null){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${limitProblem.group} would have ${limitProblem.count} modules but the ship allows ${limitProblem.limit}`,"moduleLimitExceeded",{group:limitProblem.group,count:limitProblem.count,limit:limitProblem.limit,slot:slot.key,symbol:module.symbol})}const key=this.#fittedKey(slotKey)??slot.key;this.#replaceModule(key,{Slot:key,Item:module.symbol},module);return this}removeModule(slotKey){const wanted=normalizeKey(slotKey,SLOT_KEY);if(wanted==="cargohatch"){throw new LoadoutEditError("ShipLoadout.removeModule: the cargoHatch slot cannot be changed","immutableSlot",{slot:"CargoHatch"})}const parsed=parseSlotName(slotKey);const slot=this.#layout().find(candidate=>normalizeKey(candidate.key,CATALOGUE_KEY)===wanted);if(parsed!==null&&fixedSlotReason(parsed)==="requiredSlot"){const fittedKey=this.#fittedKey(slotKey);const key2=slot?.key??fittedKey??slotKey;throw new LoadoutEditError(`ShipLoadout.removeModule: the ${truncate(key2)} slot is required and cannot be emptied`,"requiredSlot",{slot:key2})}const key=this.#fittedKey(slotKey);if(key!==null){const limitProblem=this.#moduleLimitRegression(key,null);if(limitProblem!==null){const fitted=this.#modules.get(key);throw new LoadoutEditError(`ShipLoadout.removeModule: ${truncate(slotKey)}: ${limitProblem.group} would have ${limitProblem.count} modules but the ship allows ${limitProblem.limit}`,"moduleLimitExceeded",{group:limitProblem.group,count:limitProblem.count,limit:limitProblem.limit,slot:key,...fitted===void 0?{}:{symbol:fitted.Item}})}this.#replaceModule(key,null)}return this}applyBlueprint(slotKey,blueprintSymbol,options){requireString(blueprintSymbol,"ShipLoadout.applyBlueprint: blueprintSymbol");if(options===null||typeof options!=="object"){throw new TypeError(`ShipLoadout.applyBlueprint: options must be an object with a grade, received ${describeValue(options)}`)}const wantedGrade=options.grade;const wantedQuality=options.quality;const wantedExperimental=options.experimentalEffectSymbol??void 0;requireStringIfPresent(wantedExperimental,"ShipLoadout.applyBlueprint: options.experimentalEffectSymbol");const module=this.#fittedModuleFor(slotKey);if(!module){throw new RangeError(`ShipLoadout.applyBlueprint: slot "${truncate(slotKey)}" is empty`)}const fittedStats=this.#statsFor(module);if(!fittedStats){throw new TypeError(`ShipLoadout.applyBlueprint: no stats for module "${truncate(module.Item)}"`)}const recipe=resolveBlueprintForModule(module.Item,blueprintSymbol);const named=recipe===blueprintSymbol?`"${truncate(blueprintSymbol)}"`:`"${truncate(blueprintSymbol)}" (${truncate(recipe)} on this module)`;const written=blueprintSymbol.trim().toLowerCase();const resolved=recipe.trim().toLowerCase();if(getPreEngineeredVariants(module.Item).some(variant=>variant.acquisition==="eventReward"&&(variant.blueprintSymbol.toLowerCase()===written||variant.blueprintSymbol.toLowerCase()===resolved))){throw new TypeError(`ShipLoadout.applyBlueprint: ${named} is a fixed pre-engineered identity, not a craftable blueprint; use setPreEngineeredVariant to fit its fixed article`)}if(!Number.isInteger(wantedGrade)||wantedGrade<1||wantedGrade>5){throw new RangeError(`ShipLoadout.applyBlueprint: no blueprint ${named} grade ${truncate(wantedGrade)}`)}const grade=getBlueprintGrade(recipe,wantedGrade);if(!grade){throw new RangeError(`ShipLoadout.applyBlueprint: no blueprint ${named} grade ${truncate(wantedGrade)}`)}let experimental;if(wantedExperimental!==void 0){experimental=getExperimentalEffect(wantedExperimental);if(!experimental){throw new RangeError(`ShipLoadout.applyBlueprint: unknown experimental effect "${truncate(wantedExperimental)}"`)}}const quality=wantedQuality??1;if(!Number.isFinite(quality)||quality<0||quality>1){throw new RangeError(`ShipLoadout.applyBlueprint: quality must be a finite number in [0, 1]`)}if(fittedStats.engineeringLocked){throw new TypeError(`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is a final pre-engineered article and accepts no further engineering`)}if(!blueprintAvailableFor(module.Item,blueprintSymbol)){const offered=[...blueprintRoutesFor(module.Item)].map(([blueprint,route])=>`${blueprint} (${route})`);throw new TypeError(offered.length>0?`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is not offered blueprint ${named}; available candidates are ${offered.join(", ")}`:`ShipLoadout.applyBlueprint: no registry lists an engineering menu for module "${truncate(module.Item)}"`)}if(wantedExperimental!==void 0&&!experimentalAvailableFor(module.Item,wantedExperimental)){const offered=getExperimentalsForModule(module.Item);throw new TypeError(`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is not offered experimental effect "${truncate(wantedExperimental)}"; it takes ${offered.length>0?offered.join(", "):"no experimental effect"}`)}const stats=this.#engineeringBaseStats(module)??fittedStats;const base=baseStats(stats);const canonical=primitiveEngineeringInputsFor(stats,grade,experimental);const missing=missingBaseLabels(stats,base,canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){throw new TypeError(`ShipLoadout.applyBlueprint: cannot compute ${named} for module "${truncate(module.Item)}"; missing base stats for ${missing.join(", ")}`)}const damageDistribution=experimental?.damageDistribution??grade.damageDistribution;const primitiveModifiers=computeModifiers(base,canonical.grade,quality,canonical.experimental);const modifiers=journalModifiersFor(stats,primitiveModifiers);if(damageDistribution){for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];if(value===void 0)continue;const label=labelsForDamageType(type)[0];if(label===void 0)continue;const damageModifier={Label:label,Value:value*scaleForLabel(label),OriginalValue:(stats.damageDistribution?.[type]??0)*scaleForLabel(label)};modifiers.push(damageModifier);primitiveModifiers.push(damageModifier)}}const engineering={BlueprintName:blueprintSymbol,Level:wantedGrade,Quality:quality,...wantedExperimental!==void 0?{ExperimentalEffect:wantedExperimental}:{},Modifiers:modifiers};this.#replaceModule(module.Slot,{...module,Engineering:engineering},stats,primitiveModifiers);return this}setExperimentalEffect(slotKey,experimental){if(experimental!==null){requireString(experimental,"ShipLoadout.setExperimentalEffect: experimental")}const wanted=experimental;const module=this.#fittedModuleFor(slotKey);if(!module)return experimentalEffectUnsupported("emptySlot",{slot:slotKey});const stats=this.#statsFor(module);if(!stats){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const engineering=module.Engineering;if(!engineering){return experimentalEffectUnsupported("notEngineered",{slot:module.Slot,symbol:module.Item})}if(stats.engineeringLocked){return experimentalEffectUnsupported("finalArticle",{slot:module.Slot,symbol:module.Item})}const previous=engineering.ExperimentalEffect??null;if(previous===null&&wanted===null||previous!==null&&wanted!==null&&previous.trim().toLowerCase()===wanted.trim().toLowerCase()){return deepFreeze({kind:"unchanged",experimentalEffectSymbol:previous})}const variant=preEngineeredVariantFor(module);let effect;if(wanted!==null){effect=getExperimentalEffect(wanted);if(!effect){return experimentalEffectUnsupported("unknownExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:wanted})}const restoresBakedEffect=variant?.experimentalEffectSymbol!==void 0&&variant.experimentalEffectSymbol.trim().toLowerCase()===wanted.trim().toLowerCase();if(!experimentalAvailableFor(module.Item,wanted)&&!restoresBakedEffect){return experimentalEffectUnsupported("unsupportedExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:wanted})}}if(variant&&variant.acquisition!=="mercenary"){const stock=this.#engineeringBaseStats(module);if(!stock){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const missing=missingBaseLabels(stock,baseStats(stock),[],effect?.modifiers);if(missing.length>0){return experimentalEffectUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}const{experimentalEffectSymbol:originalEffect,...withoutEffect}=variant;const adjusted=wanted===null?withoutEffect:{...withoutEffect,experimentalEffectSymbol:wanted};const resolved=getPreEngineeredStats(withoutEffect);if(!resolved){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const replacement={BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:engineering.Quality,...wanted===null?{}:{ExperimentalEffect:wanted},Modifiers:getPreEngineeredJournalModifiers(adjusted)};this.#replaceModule(module.Slot,{...module,Engineering:replacement},cloneModuleStats(resolved),getPreEngineeredModifiers(adjusted))}else{const blueprint=engineering.BlueprintName;const grade=engineering.Level;const quality=engineering.Quality;if(typeof blueprint!=="string"||!Number.isInteger(grade)||grade<1||grade>5){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const currentEffect=previous===null?void 0:getExperimentalEffect(previous)??null;if(ordinaryEngineeringProof(module.Item,engineering,currentEffect)==="unproven"){return experimentalEffectUnsupported("unidentifiedPreEngineeredVariant",{slot:module.Slot,symbol:module.Item,blueprint:blueprint})}const recipe=resolveBlueprintForModule(module.Item,blueprint);const blueprintGrade=getBlueprintGrade(recipe,grade);if(!blueprintGrade||!blueprintAvailableFor(module.Item,blueprint)||!Number.isFinite(quality)||quality<0||quality>1){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item,blueprint:blueprint,grade:grade})}const base=this.#engineeringBaseStats(module)??stats;const canonical=primitiveEngineeringInputsFor(base,blueprintGrade,effect);const missing=missingBaseLabels(base,baseStats(base),canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){return experimentalEffectUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}this.applyBlueprint(module.Slot,blueprint,{grade:grade,quality:quality,...wanted===null?{}:{experimentalEffectSymbol:wanted}})}return deepFreeze({kind:"updated",previousExperimentalEffectSymbol:previous,experimentalEffectSymbol:wanted})}completeEngineeringGrade(slotKey){const module=this.#fittedModuleFor(slotKey);if(!module)return engineeringNormalizationUnsupported("emptySlot",{slot:slotKey});const stats=this.#statsFor(module);if(!stats){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const engineering=module.Engineering;if(!engineering){return engineeringNormalizationUnsupported("notEngineered",{slot:module.Slot,symbol:module.Item})}if(stats.engineeringLocked){return engineeringNormalizationUnsupported("finalArticle",{slot:module.Slot,symbol:module.Item})}if(engineering.Quality===1&&engineering.Modifiers!==void 0){return deepFreeze({kind:"unchanged"})}const previousQuality=engineering.Quality;if(!Number.isFinite(previousQuality)||previousQuality<0||previousQuality>1){return engineeringNormalizationUnsupported("invalidQuality",{slot:module.Slot,symbol:module.Item})}const experimental=engineering.ExperimentalEffect??null;const effect=experimental===null?void 0:getExperimentalEffect(experimental)??void 0;if(experimental!==null&&!effect){return engineeringNormalizationUnsupported("unknownExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:experimental})}const blueprint=engineering.BlueprintName;const grade=engineering.Level;if(typeof blueprint!=="string"||!Number.isInteger(grade)||grade<1||grade>5){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const variant=preEngineeredVariantFor(module);const restoresBakedEffect=variant?.experimentalEffectSymbol!==void 0&&variant.experimentalEffectSymbol.trim().toLowerCase()===experimental?.trim().toLowerCase();if(experimental!==null&&!experimentalAvailableFor(module.Item,experimental)&&!restoresBakedEffect){return engineeringNormalizationUnsupported("unsupportedExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:experimental})}if(variant&&variant.acquisition!=="mercenary"){const stock=this.#engineeringBaseStats(module);if(!stock){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const missing=missingBaseLabels(stock,baseStats(stock),[],effect?.modifiers);if(missing.length>0){return engineeringNormalizationUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}const{experimentalEffectSymbol:originalEffect,...withoutEffect}=variant;const adjusted=experimental===null?withoutEffect:{...withoutEffect,experimentalEffectSymbol:experimental};const resolved=getPreEngineeredStats(withoutEffect);if(!resolved){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const replacement={BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:1,...experimental===null?{}:{ExperimentalEffect:experimental},Modifiers:getPreEngineeredJournalModifiers(adjusted)};this.#replaceModule(module.Slot,{...module,Engineering:replacement},cloneModuleStats(resolved),getPreEngineeredModifiers(adjusted))}else{const proof=ordinaryEngineeringProof(module.Item,engineering,effect);if(proof==="unproven"||proof==="proven"&&!blueprintAvailableFor(module.Item,blueprint)){return engineeringNormalizationUnsupported("unidentifiedPreEngineeredVariant",{slot:module.Slot,symbol:module.Item,blueprint:blueprint})}const recipe=resolveBlueprintForModule(module.Item,blueprint);const blueprintGrade=getBlueprintGrade(recipe,grade);if(!blueprintGrade||!blueprintAvailableFor(module.Item,blueprint)){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item,blueprint:blueprint,grade:grade})}const base=this.#engineeringBaseStats(module)??stats;const canonical=primitiveEngineeringInputsFor(base,blueprintGrade,effect);const missing=missingBaseLabels(base,baseStats(base),canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){return engineeringNormalizationUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}this.applyBlueprint(module.Slot,blueprint,{grade:grade,quality:1,...experimental===null?{}:{experimentalEffectSymbol:experimental}})}return deepFreeze({kind:"normalized",previousQuality:previousQuality,quality:1})}setPreEngineeredVariant(slotKey,variant){if(variant===null||typeof variant!=="object"){throw new TypeError(`ShipLoadout.setPreEngineeredVariant: variant must be a pre-engineered variant, received ${describeValue(variant)}`)}requireString(variant.symbol,"ShipLoadout.setPreEngineeredVariant: variant.symbol");requireString(variant.blueprintSymbol,"ShipLoadout.setPreEngineeredVariant: variant.blueprintSymbol");requireString(variant.acquisition,"ShipLoadout.setPreEngineeredVariant: variant.acquisition");requireStringIfPresent(variant.experimentalEffectSymbol,"ShipLoadout.setPreEngineeredVariant: variant.experimentalEffectSymbol");const known=getPreEngineeredVariants(variant.symbol).find(candidate=>candidate.blueprintSymbol.toLowerCase()===variant.blueprintSymbol.toLowerCase()&&candidate.grade===variant.grade&&(candidate.experimentalEffectSymbol?.toLowerCase()??"")===(variant.experimentalEffectSymbol?.toLowerCase()??"")&&candidate.acquisition===variant.acquisition);if(!known){throw new RangeError(`ShipLoadout.setPreEngineeredVariant: no catalogued variant "${truncate(variant.blueprintSymbol)}" for module "${truncate(variant.symbol)}"`)}const stats=getPreEngineeredStats(known);const unresolved=unresolvedModifiers(known);if(unresolved.length>0){throw new TypeError(`ShipLoadout.setPreEngineeredVariant: cannot resolve "${truncate(variant.blueprintSymbol)}" for module "${truncate(variant.symbol)}"; missing base stats for ${unresolved.join(", ")}`)}this.setModule(slotKey,stats);const module=this.#fittedModuleFor(slotKey);const engineering={BlueprintName:known.blueprintSymbol,Level:known.grade,Quality:1,...known.experimentalEffectSymbol===void 0?{}:{ExperimentalEffect:known.experimentalEffectSymbol},...known.modifiers?.length?{Modifiers:getPreEngineeredJournalModifiers(known)}:{}};this.#replaceModule(module.Slot,{...module,Engineering:engineering},cloneModuleStats(stats),getPreEngineeredModifiers(known));return this}clearEngineering(slotKey){const module=this.#fittedModuleFor(slotKey);if(module&&this.#statsFor(module)?.engineeringLocked){throw new TypeError(`ShipLoadout.clearEngineering: module "${truncate(module.Item)}" is a final pre-engineered article and its engineering cannot be removed`)}if(module?.Engineering){const baseStats2=this.#engineeringBaseStats(module);const bare={Slot:module.Slot,Item:module.Item};if(module.On!==void 0)bare.On=module.On;if(module.Priority!==void 0){bare.Priority=module.Priority}if(module.Health!==void 0)bare.Health=module.Health;if(module.Value!==void 0)bare.Value=module.Value;this.#replaceModule(module.Slot,bare,baseStats2??void 0)}return this}setModuleEnabled(slotKey,on){this.#patchModule(slotKey,{On:on});return this}setModulePriority(slotKey,priority){if(!Number.isInteger(priority)||priority<0||priority>4){throw new RangeError(`ShipLoadout: power priority must be an integer 0-4, got ${truncate(priority)}`)}this.#patchModule(slotKey,{Priority:priority});return this}#patchModule(slotKey,patch){const module=this.#fittedModuleFor(slotKey);if(!module){throw new RangeError(`ShipLoadout: slot "${truncate(slotKey)}" is empty`)}this.#modules.set(module.Slot,cloneLoadoutModule({...module,...patch}));this.#slotCache.clear()}toLoadoutEvent(options={}){const unladenMass=this.#computedUnladenMass();const cargoCapacity=this.#computedCargoCapacity();const fuel=this.#computedFuelCapacity();const maxJumpRange=this.#exportableJumpRange(unladenMass);return exportLoadoutEvent({shipSymbol:this.#shipSymbol,...this.#top.ShipName===void 0?{}:{shipName:this.#top.ShipName},...this.#top.ShipIdent===void 0?{}:{shipIdent:this.#top.ShipIdent},modules:this.#modules,layout:this.#layout(),sourcePurchase:this.#sourcePurchase,retailHullValue:this.#ship.hullCost,unladenMass:unladenMass,cargoCapacity:cargoCapacity,fuelCapacity:fuel,maxJumpRange:maxJumpRange,sourceTotalsVoided:this.#importOutcomes.some(outcome=>outcome.sourceSymbol===null&&parseSlotName(outcome.slot)?.kind==="core"),statsFor:module=>this.#statsFor(module)},options)}toSlef(options){return toSlef(this.toLoadoutEvent(options),options.header)}toSlefString(options){return stringifySlef(this.toSlef(options),{indent:options.indent??0})}#exportableJumpRange(unladenMass){let drive;try{drive=this.#resolveDrive()}catch{return null}if(drive===null)return null;const tank=this.#computedFuelCapacity();return singleJumpRange(unladenMass,Math.min(tank.main,drive.maxFuel),drive)}#layout(){if(this.#layoutCache===void 0){this.#layoutCache=Object.freeze(enumerateSlots(this.#ship))}return this.#layoutCache}#requireSlot(slotKey){const wanted=normalizeKey(slotKey,SLOT_KEY);const slot=this.#layout().find(s=>normalizeKey(s.key,CATALOGUE_KEY)===wanted);if(!slot){throw new RangeError(`ShipLoadout: hull "${truncate(this.#shipSymbol)}" has no slot "${truncate(slotKey)}"`)}return slot}#fittedKey(slotKey){return matchingKeyIn(this.#modules,normalizeKey(slotKey,SLOT_KEY))}#fittedModuleFor(slotKey){const key=this.#fittedKey(slotKey);return key===null?void 0:this.#modules.get(key)}#calculationModules(){return[...this.#modules.values()].map(module=>({mass:this.#moduleMass(module),cargoCapacity:this.#moduleCapacity(module,"CargoCapacity","cargoCapacity"),fuelCapacity:this.#moduleCapacity(module,"FuelCapacity","fuelCapacity")}))}#moduleLimits(){const entries=[...this.#modules.values()].flatMap(module=>{const stats=this.#statsFor(module);return stats===null?[]:[stats]});return calculateModuleLimits(entries)}#moduleStatsAt(slotKey){const fitted=this.#fittedModuleFor(slotKey);return fitted===void 0?null:this.#statsFor(fitted)}#engineeringBaseStats(module){const fitted=this.#statsFor(module);if(!module.Engineering||preEngineeredVariantFor(module)===null)return fitted;const stock=builtInModuleBySymbol(module.Item,FITTED_ITEM);if(!stock)return fitted;return fitted?.engineeringLocked?cloneModuleStats({...stock,engineeringLocked:true}):stock}#moduleForEffectiveStats(module){const modifiers=this.#primitiveModifiers.get(module.Slot);if(modifiers===void 0||module.Engineering===void 0)return module;return{...module,Engineering:{...module.Engineering,Modifiers:modifiers}}}#modulesForEffectiveStats(){return[...this.#modules.values()].map(module=>this.#moduleForEffectiveStats(module))}#moduleLimitRegression(slotKey,replacement,current=this.#moduleLimits(),previous=this.#moduleStatsAt(slotKey)){if(previous?.limitGroup===void 0&&previous?.limitIncrease===void 0&&replacement?.limitGroup===void 0&&replacement?.limitIncrease===void 0){return null}for(const usage of current){const count=usage.count-Number(previous?.limitGroup===usage.group)+Number(replacement?.limitGroup===usage.group);const increase=usage.increase-(previous?.limitIncrease?.group===usage.group?previous.limitIncrease.amount:0)+(replacement?.limitIncrease?.group===usage.group?replacement.limitIncrease.amount:0);const limit=usage.baseLimit+increase;const excess=Math.max(0,count-limit);if(excess>usage.excess){return{...usage,increase:increase,limit:limit,count:count,excess:excess}}}return null}#replaceModule(slotKey,replacement,replacementStats,primitiveModifiers){const previous=this.#modules.get(slotKey)??null;this.#adjustImportedFigures(previous,replacement,replacementStats);if(replacement===null){this.#modules.delete(slotKey);this.#moduleStats.delete(slotKey);this.#primitiveModifiers.delete(slotKey)}else{this.#modules.set(slotKey,cloneLoadoutModule(replacement));if(replacementStats!==void 0)this.#moduleStats.set(slotKey,replacementStats);if(primitiveModifiers===void 0)this.#primitiveModifiers.delete(slotKey);else this.#primitiveModifiers.set(slotKey,primitiveModifiers)}this.#slotCache.clear()}#adjustImportedFigures(previous,next,nextStats){if(this.#top.UnladenMass!==void 0){this.#top.UnladenMass+=this.#moduleMass(next,nextStats)-this.#moduleMass(previous)}if(this.#top.CargoCapacity!==void 0){this.#top.CargoCapacity+=this.#moduleCapacity(next,"CargoCapacity","cargoCapacity",nextStats)-this.#moduleCapacity(previous,"CargoCapacity","cargoCapacity")}if(this.#top.FuelCapacity?.Main!==void 0){const reserve=this.#top.FuelCapacity.Reserve;this.#top.FuelCapacity={Main:this.#top.FuelCapacity.Main+this.#moduleCapacity(next,"FuelCapacity","fuelCapacity",nextStats)-this.#moduleCapacity(previous,"FuelCapacity","fuelCapacity"),...reserve===void 0?{}:{Reserve:reserve}}}if(normalizeKey(previous?.Item,FITTED_ITEM)===normalizeKey(next?.Item,FITTED_ITEM)){return}if(previous!==null&&isCargoHatchSlot(previous.Slot)||next!==null&&isCargoHatchSlot(next.Slot)){return}delete this.#top.ModulesValue;delete this.#top.Rebuy}#moduleMass(module,statsOverride){if(module===null)return 0;if(isCargoHatchSlot(module.Slot))return 0;const modified=getLoadoutModifier(module,"Mass");if(modified!==null)return modified;return(statsOverride??this.#statsFor(module))?.mass??0}#moduleCapacity(module,modifierLabel,field,statsOverride){if(module===null)return 0;if(isCargoHatchSlot(module.Slot))return 0;const modified=getLoadoutModifier(module,modifierLabel);if(modified!==null)return modified;return(statsOverride??this.#statsFor(module))?.[field]??0}#frameShiftDrive(){for(const m of this.#modules.values()){const stats=this.#statsFor(m);if(stats?.slot==="frameShiftDrive")return{module:m,stats:stats}}return void 0}#resolveDrive(){const fsd=this.#frameShiftDrive();if(!fsd)return null;const{module:fsdModule,stats:base}=fsd;if(base.fuelMul===void 0||base.fuelPower===void 0){throw new TypeError(`ShipLoadout: the fitted record for frame shift drive "${truncate(fsdModule.Item)}" has no jump constants`)}const optMass=getLoadoutModifier(fsdModule,"FSDOptimalMass")??base.optMass;const maxFuel=getLoadoutModifier(fsdModule,"MaxFuelPerJump")??base.maxFuel;if(optMass===void 0||maxFuel===void 0){const missing=[...optMass===void 0?["optMass"]:[],...maxFuel===void 0?["maxFuel"]:[]];throw new TypeError(`ShipLoadout: the fitted record for frame shift drive "${truncate(fsdModule.Item)}" has no ${missing.join(" or ")}`)}return{optMass:optMass,maxFuel:maxFuel,fuelMul:base.fuelMul,fuelPower:base.fuelPower,jumpBoost:this.#resolveJumpBoost()}}#resolveJumpBoost(){for(const m of this.#modules.values()){const stats=this.#statsFor(m);if(stats?.engineeringGroup!=="fsdBoosters"&&(stats?.jumpBoost===void 0||stats.jumpBoost===0)){continue}if(m.On===false)continue;if(stats?.jumpBoost===void 0){throw new TypeError(`ShipLoadout: the fitted record for FSD booster "${truncate(m.Item)}" has no jumpBoost`)}return stats.jumpBoost}return 0}#statsFor(module){if(module===null)return null;const stats=this.#moduleStats.get(module.Slot)??builtInModuleBySymbol(module.Item,FITTED_ITEM);if(stats)return stats;return isBuiltInHullModule(module)?builtInModuleBySymbol("ModularCargoBayDoor","ShipLoadout: built-in module"):null}};export{LoadoutEditError,ShipLoadout};//# sourceMappingURL=chunk-B5VTFOK4.js.map
1
+ import{fixedSlotReason,validateLoadout}from"./chunk-OJC6AUL7.js";import{calculateModuleLimits}from"./chunk-KPETDYQX.js";import{publishLoadoutInternals,normalizeLoadoutEvent,preEngineeredVariantFor,moduleFitProblem,effectiveModule,moduleFitError}from"./chunk-FD74K27A.js";import{getShipBySymbol}from"./chunk-6UNAD74Z.js";import{parseSlef,toSlef,stringifySlef,getLoadoutModifier}from"./chunk-T4MKUKYS.js";import{getSourceModuleValue}from"./chunk-NIURLW2F.js";import{statesInertModifiers,rolledOverFixedArticle,isNonOutfittingSlot,isBuiltInHullModule,cloneLoadoutModule,cloneModuleStats,availableBlueprintsFor,availableExperimentalsFor,ownKeyIn,FITTED_ITEM,blueprintAvailableFor,blueprintRoutesFor,experimentalAvailableFor,primitiveEngineeringInputsFor,missingBaseLabels,journalModifiersFor,getPreEngineeredStats,getPreEngineeredJournalModifiers,getPreEngineeredModifiers,ordinaryEngineeringProof,unresolvedModifiers,matchingKeyIn,isCargoHatchSlot,orderBySlotLayout}from"./chunk-SC6Z2TV7.js";import{builtInModuleBySymbol}from"./chunk-3LZXB2MC.js";import{getPreEngineeredVariants}from"./chunk-KPJ77VPS.js";import{ALL_MODULES}from"./chunk-7ZERP4TB.js";import{getExperimentalEffect}from"./chunk-77I24V6B.js";import{singleJumpRange}from"./chunk-VTMCSCXV.js";import{calculateUnladenMass,calculateCargoCapacity,calculateFuelCapacity}from"./chunk-DCB4COCL.js";import{resolveBlueprintForModule}from"./chunk-OLKNYGGT.js";import{getBlueprintGrade}from"./chunk-AYAKU4YA.js";import{getDefaultLoadout}from"./chunk-GRIK3EDH.js";import{getExperimentalsForModule}from"./chunk-GLWPSVFV.js";import{baseStats,computeModifiers,labelsForDamageType,scaleForLabel}from"./chunk-CJQ37JII.js";import{ammunitionCapacity}from"./chunk-AA3K5XUE.js";import{loadoutSlotName}from"./chunk-KAA4VOOB.js";import{parseSlotName,enumerateSlots}from"./chunk-RAO35XDF.js";import{normalizeKey,CATALOGUE_KEY}from"./chunk-BKWLI44T.js";import{truncate,describeValue,requireString,requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";var REBUY_FRACTION=.05;function exportLoadoutEvent(input,options){const fromSource=options.credits==="source";const source=fromSource?input.sourcePurchase:null;const totals=source!==null&&!input.sourceTotalsVoided&&sourceTotalsHold(input.modules,source)?source:null;const hullValue=fromSource?source?.hullValue??null:input.retailHullValue;const modulesValue=fromSource?totals?.modulesValue??null:computedModulesValue(input.modules,input.statsFor);const rebuy=fromSource?totals?.rebuy??null:hullValue===null||modulesValue===null?null:Math.trunc((hullValue+modulesValue)*REBUY_FRACTION);return{Ship:input.shipSymbol.toLowerCase(),...input.shipName===void 0?{}:{ShipName:input.shipName},...input.shipIdent===void 0?{}:{ShipIdent:input.shipIdent},...hullValue===null?{}:{HullValue:hullValue},...modulesValue===null?{}:{ModulesValue:modulesValue},UnladenMass:input.unladenMass,CargoCapacity:input.cargoCapacity,...input.maxJumpRange===null?{}:{MaxJumpRange:input.maxJumpRange},FuelCapacity:{Main:input.fuelCapacity.main,Reserve:input.fuelCapacity.reserve},...rebuy===null?{}:{Rebuy:rebuy},Modules:exportModules(input,options,fromSource)}}function exportModules(input,options,fromSource){const ordered=options.moduleOrder==="slots"?slotOrderedModules(input.modules,input.layout):[...input.modules.values()];return ordered.map(module=>{const on=module.On??(options.explicitPower?true:void 0);const priority=module.Priority??(options.explicitPower?0:void 0);const value=fromSource?sourceModuleValue(module,input.sourcePurchase):moduleValue(module,input.statsFor);return{Slot:module.Slot,Item:module.Item.toLowerCase(),...on===void 0?{}:{On:on},...priority===void 0?{}:{Priority:priority},...module.Health===void 0?{}:{Health:module.Health},...typeof value==="number"?{Value:value}:{},...module.Engineering===void 0?{}:{Engineering:cloneLoadoutModule(module).Engineering}}})}function slotOrderedModules(modules,layout){return orderBySlotLayout([...modules.values()],layout,module=>module.Slot)}function computedModulesValue(modules,statsFor){let sum=0;for(const module of modules.values()){const value=moduleValue(module,statsFor);if(value==="unknown")return null;if(value!=="free")sum+=value}return sum}function moduleValue(module,statsFor){const stats=statsFor(module);if(stats!==null)return stats.cost??"unknown";return isNonOutfittingSlot(module.Slot)||isBuiltInHullModule(module)?"free":"unknown"}var SOURCE_ITEM="ShipLoadout: sourcePurchase moduleValues[].item";function sourceModuleValue(module,source){const entry=source===null?null:getSourceModuleValue(source,module.Slot);if(entry===null)return"unknown";return normalizeKey(entry.item,SOURCE_ITEM)===normalizeKey(module.Item,FITTED_ITEM)?entry.value:"unknown"}function sourceTotalsHold(modules,source){for(const entry of source.moduleValues){const key=matchingKeyIn(modules,entry.slot);const fitted=key===null?void 0:modules.get(key);if(!fitted)return false;if(isCargoHatchSlot(entry.slot)&&entry.value===0)continue;if(normalizeKey(fitted.Item,FITTED_ITEM)!==normalizeKey(entry.item,SOURCE_ITEM)){return false}}return true}var SLOT_KEY="ShipLoadout: slotKey";var FITTED_SLOT="ShipLoadout: fitted module Slot";var LoadoutEditError=class extends TypeError{code;constraint;params;constructor(message,code,params,constraint){super(message);this.code=code;this.params=deepFreeze(structuredClone(params));if(constraint!==void 0)this.constraint=constraint}};var experimentalEffectUnsupported=(code,params)=>deepFreeze({kind:"unsupported",code:code,params:params});var engineeringNormalizationUnsupported=(code,params)=>deepFreeze({kind:"unsupported",code:code,params:params});function weighable(tonnes){return tonnes!==void 0&&Number.isFinite(tonnes)&&tonnes>=0?tonnes:void 0}var AGGREGATE_STATS=["mass","cargoCapacity","fuelCapacity"];var ShipLoadout=class _ShipLoadout{#ship;#shipSymbol;#modules;#moduleStats;#primitiveModifiers;#top;#sourcePurchase;#importOutcomes;#slotCache=/* @__PURE__ */new Map;#layoutCache;constructor(ship,shipSymbol,modules,top,sourcePurchase=null,moduleStats=/* @__PURE__ */new Map,primitiveModifiers=/* @__PURE__ */new Map,importOutcomes=deepFreeze([])){this.#ship=ship;this.#shipSymbol=shipSymbol;this.#modules=modules;this.#top=top;this.#sourcePurchase=sourcePurchase;this.#moduleStats=moduleStats;this.#primitiveModifiers=primitiveModifiers;this.#importOutcomes=importOutcomes;publishLoadoutInternals(this,{ship:ship,modules:()=>[...this.#modules.values()],effectiveModules:()=>this.#modulesForEffectiveStats(),effectiveModule:module=>this.#moduleForEffectiveStats(module),statsFor:module=>this.#statsFor(module),layout:()=>this.#layout(),resolveDrive:()=>this.#resolveDrive(),frameShiftDriveModule:()=>this.#frameShiftDrive()?.module,calculationModules:()=>this.#calculationModules(),statedMainFuel:()=>this.#top.FuelCapacity?.Main})}static fromSlef(input,index=0){const entries=parseSlef(input);const entry=entries[index];if(!entry){throw new TypeError(`ShipLoadout.fromSlef: no entry at index ${truncate(index)} (have ${entries.length})`)}const imported=normalizeLoadoutEvent(entry.data);const ship=getShipBySymbol(imported.shipSymbol);if(!ship){throw new TypeError(`ShipLoadout.fromSlef: unknown hull "${truncate(imported.shipSymbol)}"`)}return _ShipLoadout.#fromImported(imported,ship)}static fromLoadout(event){if(event===null||typeof event!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: event must be a Loadout event, received ${describeValue(event)}`)}const imported=normalizeLoadoutEvent(event);const ship=getShipBySymbol(imported.shipSymbol);if(!ship){throw new TypeError(`ShipLoadout.fromLoadout: unknown hull "${truncate(imported.shipSymbol)}"`)}return _ShipLoadout.#fromImported(imported,ship)}static#fromImported(imported,ship){const outcomes=[...imported.outcomes];const loadout=new _ShipLoadout(ship,imported.shipSymbol,imported.modules,imported.top,imported.sourcePurchase,imported.moduleStats,imported.primitiveModifiers,outcomes);const{UnladenMass:UnladenMass,CargoCapacity:CargoCapacity,FuelCapacity:FuelCapacity}=imported.top;for(const module of[...imported.modules.values()]){const unresolved=loadout.#rollStatedRecipe(module);if(unresolved!==null)outcomes.push(unresolved)}if(UnladenMass!==void 0)loadout.#top.UnladenMass=UnladenMass;if(CargoCapacity!==void 0)loadout.#top.CargoCapacity=CargoCapacity;if(FuelCapacity!==void 0)loadout.#top.FuelCapacity=FuelCapacity;deepFreeze(outcomes);return loadout}#rollStatedRecipe(module){const engineering=module.Engineering;if(!engineering||typeof engineering.BlueprintName!=="string")return null;const stated=engineering.Modifiers;const stats=this.#statsFor(module);if(stated!==void 0&&(this.#moduleStats.has(module.Slot)||stats===null||!statesInertModifiers(stats,stated))){return null}if(stated===void 0&&this.#moduleStats.has(module.Slot)){const variant=preEngineeredVariantFor(module);if(variant?.acquisition!=="mercenary"||engineering.Level<=variant.grade){return null}}try{this.applyBlueprint(module.Slot,engineering.BlueprintName,{grade:engineering.Level,quality:engineering.Quality??1,...typeof engineering.ExperimentalEffect==="string"?{experimentalEffectSymbol:engineering.ExperimentalEffect}:{}});if(stated!==void 0){return{action:"rerolledEngineering",slot:module.Slot,sourceSymbol:module.Item,blueprintSymbol:engineering.BlueprintName}}const passedOver=rolledOverFixedArticle(module.Item,engineering);return passedOver===null?null:{action:"ambiguousEngineering",slot:module.Slot,sourceSymbol:module.Item,blueprintSymbol:engineering.BlueprintName,preEngineeredVariant:passedOver}}catch(error){if(!(error instanceof TypeError)&&!(error instanceof RangeError))throw error;return{action:"unresolvedEngineering",slot:module.Slot,sourceSymbol:module.Item,blueprintSymbol:engineering.BlueprintName}}}static empty(shipSymbol){const requested=requireString(shipSymbol,"ShipLoadout.empty: shipSymbol");const ship=getShipBySymbol(requested);if(!ship){throw new TypeError(`ShipLoadout.empty: no slot layout for hull "${truncate(shipSymbol)}"`)}const fitted=(getDefaultLoadout(ship.symbol)?.modules??[]).filter(module=>{const parsed=parseSlotName(module.slot);return parsed!==null&&fixedSlotReason(parsed)!==null});return new _ShipLoadout(ship,ship.symbol,new Map(fitted.map(module=>[module.slot,{Slot:module.slot,Item:module.symbol}])),{})}static default(shipSymbol){const requested=requireString(shipSymbol,"ShipLoadout.default: shipSymbol");const ship=getShipBySymbol(requested);if(!ship){throw new TypeError(`ShipLoadout.default: no default loadout for hull "${truncate(shipSymbol)}"`)}const loadout=getDefaultLoadout(ship.symbol);return new _ShipLoadout(ship,loadout.symbol,new Map(loadout.modules.map(module=>[module.slot,{Slot:module.slot,Item:module.symbol}])),{})}get shipSymbol(){return this.#shipSymbol}get shipName(){return this.#top.ShipName??null}get shipIdent(){return this.#top.ShipIdent??null}get unladenMass(){return this.#top.UnladenMass??this.#computedUnladenMass()}#computedUnladenMass(){return calculateUnladenMass(this.#ship.hullMass,this.#calculationModules())}get fuelCapacity(){const cap=this.#top.FuelCapacity;if(cap?.Main!==void 0&&cap.Reserve!==void 0){return Object.freeze({main:cap.Main,reserve:cap.Reserve})}const computed=this.#computedFuelCapacity();return Object.freeze({main:cap?.Main??computed.main,reserve:cap?.Reserve??computed.reserve})}get cargoCapacity(){return this.#top.CargoCapacity??this.#computedCargoCapacity()}#computedCargoCapacity(){return calculateCargoCapacity(this.#calculationModules())}#computedFuelCapacity(){return calculateFuelCapacity(this.#ship.reserveFuelCapacity,this.#calculationModules())}get hullValue(){return this.#top.HullValue??null}get modulesValue(){return this.#top.ModulesValue??null}get rebuy(){return this.#top.Rebuy??null}get sourcePurchase(){return this.#sourcePurchase}get importOutcomes(){return this.#importOutcomes}validation(){const slots=this.#layout();const byKey=new Map(slots.map(slot=>[normalizeKey(slot.key,CATALOGUE_KEY),slot]));const modules=[...this.#modules.values()].map(module=>{const stats=this.#statsFor(module);const slot=byKey.get(normalizeKey(module.Slot,FITTED_SLOT));const builtIn=stats===null&&isNonOutfittingSlot(module.Slot)||isBuiltInHullModule(module);const fitProblem=stats&&slot&&!builtIn?moduleFitProblem(this.#shipSymbol,slot,stats):null;const thrusterMaxMass=weighable(stats?.slot==="thrusters"?effectiveModule(this.#moduleForEffectiveStats(module),stats)?.maxMass:void 0);return{slot:module.Slot,symbol:module.Item,requiresKnownSlot:!builtIn,fitError:fitProblem?.message??null,...fitProblem===null?{}:{fitConstraint:fitProblem.constraint},...fitProblem?.params===void 0?{}:{fitParams:fitProblem.params},...stats?.exclusionGroup===void 0?{}:{exclusionGroup:stats.exclusionGroup},...stats?.limitGroup===void 0?{}:{limitGroup:stats.limitGroup},...stats?.limitIncrease===void 0?{}:{limitIncrease:stats.limitIncrease},...thrusterMaxMass===void 0?{}:{thrusterMaxMass:thrusterMaxMass}}});const dry=weighable(this.unladenMass);const fuel=weighable(this.fuelCapacity.main);const cargo=weighable(this.cargoCapacity);const mass=dry===void 0?void 0:{dry:dry,...fuel===void 0?{}:{fuel:fuel},...fuel===void 0||cargo===void 0?{}:{cargo:cargo}};return validateLoadout({shipSymbol:this.#shipSymbol,slots:slots,modules:modules,...mass===void 0?{}:{mass:mass}})}slots(kind){const cached=this.#slotCache.get(kind);if(cached!==void 0)return cached;const slots=kind===void 0?this.#layout():this.#layout().filter(slot=>slot.kind===kind);const currentLimits=this.#moduleLimits();const value=deepFreeze(slots.map(slot=>{const stats=this.#moduleStatsAt(slot.key);const fixedReason=fixedSlotReason(slot);const immovableReason=fixedReason!==null?fixedReason:stats?.limitIncrease!==void 0&&this.#moduleLimitRegression(slot.key,null,currentLimits,stats)!==null?"moduleLimit":null;return{...slot,name:loadoutSlotName(slot),module:this.fittedModuleAt(slot.key),removable:immovableReason===null,...immovableReason===null?{}:{immovableReason:immovableReason}}}));this.#slotCache.set(kind,value);return value}fittedModuleAt(slotKey){const module=this.#fittedModuleFor(slotKey);if(!module)return null;const raw=cloneLoadoutModule(module);const stats=this.#statsFor(module);const effective=effectiveModule(this.#moduleForEffectiveStats(module),stats);return deepFreeze({slot:module.Slot,symbol:raw.Item,on:raw.On,priority:raw.Priority,health:raw.Health,value:raw.Value,engineering:raw.Engineering,raw:raw,stats:stats===null?null:cloneModuleStats(stats),effectiveStats:effective===null?null:cloneModuleStats(effective),ammunition:ammunitionCapacity(effective),preEngineeredVariant:preEngineeredVariantFor(raw)})}fittedModules(){return deepFreeze([...this.#modules.keys()].flatMap(key=>{const fitted=this.fittedModuleAt(key);return fitted===null?[]:[fitted]}))}availableBlueprints(slotKey){const module=this.#fittedModuleFor(slotKey);return deepFreeze(module?availableBlueprintsFor(module.Item,this.#statsFor(module)):[])}availableExperimentalEffects(slotKey){const module=this.#fittedModuleFor(slotKey);return deepFreeze(module?availableExperimentalsFor(module.Item,this.#statsFor(module)):[])}modulesForSlot(slotKey){const slot=this.#requireSlot(slotKey);const occupied=new Set([...this.#modules.values()].flatMap(fitted=>{if(normalizeKey(fitted.Slot,FITTED_SLOT)===normalizeKey(slot.key,CATALOGUE_KEY))return[];const group=this.#statsFor(fitted)?.exclusionGroup;return group===void 0?[]:[group]}));const currentLimits=this.#moduleLimits();const currentStats=this.#moduleStatsAt(slot.key);return ALL_MODULES.filter(module=>module.grantOnly===void 0&&moduleFitError(this.#shipSymbol,slot,module)===null&&(module.exclusionGroup===void 0||!occupied.has(module.exclusionGroup))&&this.#moduleLimitRegression(slot.key,module,currentLimits,currentStats)===null)}repairFixedMount(slotKey){const requested=requireString(slotKey,SLOT_KEY);const wanted=normalizeKey(requested,SLOT_KEY);const slot=this.#requireSlot(requested);const fittedKey=this.#fittedKey(requested);const resultSlot=fittedKey??requested;const canonicalKey=slot.key;if(fixedSlotReason(slot)===null){return deepFreeze({status:"refused",slot:resultSlot,reason:"notFixedMount"})}const current=this.#fittedModuleFor(requested);const currentStats=current?this.#statsFor(current):null;const valid=current!==void 0&&currentStats!==null&&(slot.kind==="cargoHatch"?isBuiltInHullModule(current):moduleFitProblem(this.#shipSymbol,slot,currentStats)===null);if(valid){return deepFreeze({status:"unchanged",slot:current.Slot,symbol:current.Item})}const defaultModule=getDefaultLoadout(this.#shipSymbol)?.modules.find(module=>normalizeKey(module.slot,CATALOGUE_KEY)===wanted);if(!defaultModule){return deepFreeze({status:"defaultUnavailable",slot:resultSlot})}const ownKey=ownKeyIn(this.#modules,canonicalKey);const replacement={Slot:ownKey,Item:defaultModule.symbol,...current?.On===void 0?{}:{On:current.On},...current?.Priority===void 0?{}:{Priority:current.Priority},...current?.Health===void 0?{}:{Health:current.Health}};const replacementStats=builtInModuleBySymbol(defaultModule.symbol,"ShipLoadout.repairFixedMount")??(isBuiltInHullModule(replacement)?builtInModuleBySymbol("ModularCargoBayDoor","ShipLoadout.repairFixedMount"):null);if(!replacementStats){return deepFreeze({status:"defaultUnavailable",slot:resultSlot,symbol:defaultModule.symbol})}this.#replaceModule(ownKey,replacement,replacementStats);return deepFreeze({status:"repaired",slot:ownKey,symbol:defaultModule.symbol})}setModule(slotKey,module){const slot=this.#requireSlot(slotKey);if(module===null||module===void 0){throw new TypeError(`ShipLoadout.setModule: no module supplied for "${truncate(slotKey)}" (did the module lookup return undefined?)`)}if(typeof module.symbol!=="string"){throw new TypeError(`ShipLoadout.setModule: module for "${truncate(slotKey)}" must be an outfitting module, received ${describeValue(module)}`)}module=cloneModuleStats(module);const catalogued=builtInModuleBySymbol(module.symbol,FITTED_ITEM);if(catalogued===null){throw new TypeError(`ShipLoadout.setModule: no module is catalogued as "${truncate(module.symbol)}"`)}for(const field of AGGREGATE_STATS){const stated=module[field];if(stated===void 0){if(catalogued[field]===void 0)continue;throw new TypeError(`ShipLoadout.setModule: the supplied record for "${truncate(module.symbol)}" has no ${field}`)}if(typeof stated!=="number"||!Number.isFinite(stated)){throw new TypeError(`ShipLoadout.setModule: the supplied record for "${truncate(module.symbol)}" states a ${field} of ${describeValue(stated)}`)}}const problem=moduleFitProblem(this.#shipSymbol,slot,module);if(problem){if(problem.constraint==="immutableSlot"){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${problem.message}`,"immutableSlot",{slot:slot.key})}throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${problem.message}`,"incompatibleModule",{...problem.params,slot:slot.key,symbol:module.symbol,constraint:problem.constraint},problem.constraint)}if(module.exclusionGroup!==void 0){const conflict=[...this.#modules.values()].find(fitted=>normalizeKey(fitted.Slot,FITTED_SLOT)!==normalizeKey(slot.key,CATALOGUE_KEY)&&this.#statsFor(fitted)?.exclusionGroup===module.exclusionGroup);if(conflict){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${module.exclusionGroup} is limited to one per ship (already fitted in ${truncate(conflict.Slot)})`,"duplicateExclusiveModule",{exclusionGroup:module.exclusionGroup,slot:slot.key,symbol:module.symbol,previousSlot:conflict.Slot,previousSymbol:conflict.Item})}}const limitProblem=this.#moduleLimitRegression(slot.key,module);if(limitProblem!==null){throw new LoadoutEditError(`ShipLoadout.setModule: ${truncate(module.symbol)} → ${truncate(slotKey)}: ${limitProblem.group} would have ${limitProblem.count} modules but the ship allows ${limitProblem.limit}`,"moduleLimitExceeded",{group:limitProblem.group,count:limitProblem.count,limit:limitProblem.limit,slot:slot.key,symbol:module.symbol})}const key=this.#fittedKey(slotKey)??slot.key;this.#replaceModule(key,{Slot:key,Item:module.symbol},module);return this}removeModule(slotKey){const wanted=normalizeKey(slotKey,SLOT_KEY);if(wanted==="cargohatch"){throw new LoadoutEditError("ShipLoadout.removeModule: the cargoHatch slot cannot be changed","immutableSlot",{slot:"CargoHatch"})}const parsed=parseSlotName(slotKey);const slot=this.#layout().find(candidate=>normalizeKey(candidate.key,CATALOGUE_KEY)===wanted);if(parsed!==null&&fixedSlotReason(parsed)==="requiredSlot"){const fittedKey=this.#fittedKey(slotKey);const key2=slot?.key??fittedKey??slotKey;throw new LoadoutEditError(`ShipLoadout.removeModule: the ${truncate(key2)} slot is required and cannot be emptied`,"requiredSlot",{slot:key2})}const key=this.#fittedKey(slotKey);if(key!==null){const limitProblem=this.#moduleLimitRegression(key,null);if(limitProblem!==null){const fitted=this.#modules.get(key);throw new LoadoutEditError(`ShipLoadout.removeModule: ${truncate(slotKey)}: ${limitProblem.group} would have ${limitProblem.count} modules but the ship allows ${limitProblem.limit}`,"moduleLimitExceeded",{group:limitProblem.group,count:limitProblem.count,limit:limitProblem.limit,slot:key,...fitted===void 0?{}:{symbol:fitted.Item}})}this.#replaceModule(key,null)}return this}applyBlueprint(slotKey,blueprintSymbol,options){requireString(blueprintSymbol,"ShipLoadout.applyBlueprint: blueprintSymbol");if(options===null||typeof options!=="object"){throw new TypeError(`ShipLoadout.applyBlueprint: options must be an object with a grade, received ${describeValue(options)}`)}const wantedGrade=options.grade;const wantedQuality=options.quality;const wantedExperimental=options.experimentalEffectSymbol??void 0;requireStringIfPresent(wantedExperimental,"ShipLoadout.applyBlueprint: options.experimentalEffectSymbol");const module=this.#fittedModuleFor(slotKey);if(!module){throw new RangeError(`ShipLoadout.applyBlueprint: slot "${truncate(slotKey)}" is empty`)}const fittedStats=this.#statsFor(module);if(!fittedStats){throw new TypeError(`ShipLoadout.applyBlueprint: no stats for module "${truncate(module.Item)}"`)}const recipe=resolveBlueprintForModule(module.Item,blueprintSymbol);const named=recipe===blueprintSymbol?`"${truncate(blueprintSymbol)}"`:`"${truncate(blueprintSymbol)}" (${truncate(recipe)} on this module)`;const written=blueprintSymbol.trim().toLowerCase();const resolved=recipe.trim().toLowerCase();if(getPreEngineeredVariants(module.Item).some(variant=>variant.acquisition==="eventReward"&&(variant.blueprintSymbol.toLowerCase()===written||variant.blueprintSymbol.toLowerCase()===resolved))){throw new TypeError(`ShipLoadout.applyBlueprint: ${named} is a fixed pre-engineered identity, not a craftable blueprint; use setPreEngineeredVariant to fit its fixed article`)}if(!Number.isInteger(wantedGrade)||wantedGrade<1||wantedGrade>5){throw new RangeError(`ShipLoadout.applyBlueprint: no blueprint ${named} grade ${truncate(wantedGrade)}`)}const grade=getBlueprintGrade(recipe,wantedGrade);if(!grade){throw new RangeError(`ShipLoadout.applyBlueprint: no blueprint ${named} grade ${truncate(wantedGrade)}`)}let experimental;if(wantedExperimental!==void 0){experimental=getExperimentalEffect(wantedExperimental);if(!experimental){throw new RangeError(`ShipLoadout.applyBlueprint: unknown experimental effect "${truncate(wantedExperimental)}"`)}}const quality=wantedQuality??1;if(!Number.isFinite(quality)||quality<0||quality>1){throw new RangeError(`ShipLoadout.applyBlueprint: quality must be a finite number in [0, 1]`)}if(fittedStats.engineeringLocked){throw new TypeError(`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is a final pre-engineered article and accepts no further engineering`)}if(!blueprintAvailableFor(module.Item,blueprintSymbol)){const offered=[...blueprintRoutesFor(module.Item)].map(([blueprint,route])=>`${blueprint} (${route})`);throw new TypeError(offered.length>0?`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is not offered blueprint ${named}; available candidates are ${offered.join(", ")}`:`ShipLoadout.applyBlueprint: no registry lists an engineering menu for module "${truncate(module.Item)}"`)}if(wantedExperimental!==void 0&&!experimentalAvailableFor(module.Item,wantedExperimental)){const offered=getExperimentalsForModule(module.Item);throw new TypeError(`ShipLoadout.applyBlueprint: module "${truncate(module.Item)}" is not offered experimental effect "${truncate(wantedExperimental)}"; it takes ${offered.length>0?offered.join(", "):"no experimental effect"}`)}const stats=this.#engineeringBaseStats(module)??fittedStats;const base=baseStats(stats);const canonical=primitiveEngineeringInputsFor(stats,grade,experimental);const missing=missingBaseLabels(stats,base,canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){throw new TypeError(`ShipLoadout.applyBlueprint: cannot compute ${named} for module "${truncate(module.Item)}"; missing base stats for ${missing.join(", ")}`)}const damageDistribution=experimental?.damageDistribution??grade.damageDistribution;const primitiveModifiers=computeModifiers(base,canonical.grade,quality,canonical.experimental);const modifiers=journalModifiersFor(stats,primitiveModifiers);if(damageDistribution){for(const type of["kinetic","thermal","explosive","absolute"]){const value=damageDistribution[type];if(value===void 0)continue;const label=labelsForDamageType(type)[0];if(label===void 0)continue;const damageModifier={Label:label,Value:value*scaleForLabel(label),OriginalValue:(stats.damageDistribution?.[type]??0)*scaleForLabel(label)};modifiers.push(damageModifier);primitiveModifiers.push(damageModifier)}}const engineering={BlueprintName:blueprintSymbol,Level:wantedGrade,Quality:quality,...wantedExperimental!==void 0?{ExperimentalEffect:wantedExperimental}:{},Modifiers:modifiers};this.#replaceModule(module.Slot,{...module,Engineering:engineering},stats,primitiveModifiers);return this}setExperimentalEffect(slotKey,experimental){if(experimental!==null){requireString(experimental,"ShipLoadout.setExperimentalEffect: experimental")}const wanted=experimental;const module=this.#fittedModuleFor(slotKey);if(!module)return experimentalEffectUnsupported("emptySlot",{slot:slotKey});const stats=this.#statsFor(module);if(!stats){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const engineering=module.Engineering;if(!engineering){return experimentalEffectUnsupported("notEngineered",{slot:module.Slot,symbol:module.Item})}if(stats.engineeringLocked){return experimentalEffectUnsupported("finalArticle",{slot:module.Slot,symbol:module.Item})}const previous=engineering.ExperimentalEffect??null;if(previous===null&&wanted===null||previous!==null&&wanted!==null&&previous.trim().toLowerCase()===wanted.trim().toLowerCase()){return deepFreeze({kind:"unchanged",experimentalEffectSymbol:previous})}const variant=preEngineeredVariantFor(module);let effect;if(wanted!==null){effect=getExperimentalEffect(wanted);if(!effect){return experimentalEffectUnsupported("unknownExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:wanted})}const restoresBakedEffect=variant?.experimentalEffectSymbol!==void 0&&variant.acquisition!=="mercenary"&&variant.experimentalEffectSymbol.trim().toLowerCase()===wanted.trim().toLowerCase();if(!experimentalAvailableFor(module.Item,wanted)&&!restoresBakedEffect){return experimentalEffectUnsupported("unsupportedExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:wanted})}}if(variant&&variant.acquisition!=="mercenary"){const stock=this.#engineeringBaseStats(module);if(!stock){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const missing=missingBaseLabels(stock,baseStats(stock),[],effect?.modifiers);if(missing.length>0){return experimentalEffectUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}const{experimentalEffectSymbol:originalEffect,...withoutEffect}=variant;const adjusted=wanted===null?withoutEffect:{...withoutEffect,experimentalEffectSymbol:wanted};const resolved=getPreEngineeredStats(withoutEffect);if(!resolved){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const replacement={BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:engineering.Quality,...wanted===null?{}:{ExperimentalEffect:wanted},Modifiers:getPreEngineeredJournalModifiers(adjusted)};this.#replaceModule(module.Slot,{...module,Engineering:replacement},cloneModuleStats(resolved),getPreEngineeredModifiers(adjusted))}else{const blueprint=engineering.BlueprintName;const grade=engineering.Level;const quality=engineering.Quality;if(typeof blueprint!=="string"||!Number.isInteger(grade)||grade<1||grade>5){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const currentEffect=previous===null?void 0:getExperimentalEffect(previous)??null;if(ordinaryEngineeringProof(module.Item,engineering,currentEffect)==="unproven"){return experimentalEffectUnsupported("unidentifiedPreEngineeredVariant",{slot:module.Slot,symbol:module.Item,blueprint:blueprint})}const recipe=resolveBlueprintForModule(module.Item,blueprint);const blueprintGrade=getBlueprintGrade(recipe,grade);if(!blueprintGrade||!blueprintAvailableFor(module.Item,blueprint)||!Number.isFinite(quality)||quality<0||quality>1){return experimentalEffectUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item,blueprint:blueprint,grade:grade})}const base=this.#engineeringBaseStats(module)??stats;const canonical=primitiveEngineeringInputsFor(base,blueprintGrade,effect);const missing=missingBaseLabels(base,baseStats(base),canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){return experimentalEffectUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}this.applyBlueprint(module.Slot,blueprint,{grade:grade,quality:quality,...wanted===null?{}:{experimentalEffectSymbol:wanted}})}return deepFreeze({kind:"updated",previousExperimentalEffectSymbol:previous,experimentalEffectSymbol:wanted})}completeEngineeringGrade(slotKey){const module=this.#fittedModuleFor(slotKey);if(!module)return engineeringNormalizationUnsupported("emptySlot",{slot:slotKey});const stats=this.#statsFor(module);if(!stats){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const engineering=module.Engineering;if(!engineering){return engineeringNormalizationUnsupported("notEngineered",{slot:module.Slot,symbol:module.Item})}if(stats.engineeringLocked){return engineeringNormalizationUnsupported("finalArticle",{slot:module.Slot,symbol:module.Item})}if(engineering.Quality===1&&engineering.Modifiers!==void 0){return deepFreeze({kind:"unchanged"})}const previousQuality=engineering.Quality;if(!Number.isFinite(previousQuality)||previousQuality<0||previousQuality>1){return engineeringNormalizationUnsupported("invalidQuality",{slot:module.Slot,symbol:module.Item})}const experimental=engineering.ExperimentalEffect??null;const effect=experimental===null?void 0:getExperimentalEffect(experimental)??void 0;if(experimental!==null&&!effect){return engineeringNormalizationUnsupported("unknownExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:experimental})}const blueprint=engineering.BlueprintName;const grade=engineering.Level;if(typeof blueprint!=="string"||!Number.isInteger(grade)||grade<1||grade>5){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const variant=preEngineeredVariantFor(module);const restoresBakedEffect=variant?.experimentalEffectSymbol!==void 0&&variant.acquisition!=="mercenary"&&variant.experimentalEffectSymbol.trim().toLowerCase()===experimental?.trim().toLowerCase();if(experimental!==null&&!experimentalAvailableFor(module.Item,experimental)&&!restoresBakedEffect){return engineeringNormalizationUnsupported("unsupportedExperimentalEffect",{slot:module.Slot,symbol:module.Item,experimental:experimental})}if(variant&&variant.acquisition!=="mercenary"){const stock=this.#engineeringBaseStats(module);if(!stock){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const missing=missingBaseLabels(stock,baseStats(stock),[],effect?.modifiers);if(missing.length>0){return engineeringNormalizationUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}const{experimentalEffectSymbol:originalEffect,...withoutEffect}=variant;const adjusted=experimental===null?withoutEffect:{...withoutEffect,experimentalEffectSymbol:experimental};const resolved=getPreEngineeredStats(withoutEffect);if(!resolved){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item})}const replacement={BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:1,...experimental===null?{}:{ExperimentalEffect:experimental},Modifiers:getPreEngineeredJournalModifiers(adjusted)};this.#replaceModule(module.Slot,{...module,Engineering:replacement},cloneModuleStats(resolved),getPreEngineeredModifiers(adjusted))}else{const proof=ordinaryEngineeringProof(module.Item,engineering,effect);if(proof==="unproven"||proof==="proven"&&!blueprintAvailableFor(module.Item,blueprint)){return engineeringNormalizationUnsupported("unidentifiedPreEngineeredVariant",{slot:module.Slot,symbol:module.Item,blueprint:blueprint})}const recipe=resolveBlueprintForModule(module.Item,blueprint);const blueprintGrade=getBlueprintGrade(recipe,grade);if(!blueprintGrade||!blueprintAvailableFor(module.Item,blueprint)){return engineeringNormalizationUnsupported("unsupportedEngineering",{slot:module.Slot,symbol:module.Item,blueprint:blueprint,grade:grade})}const base=this.#engineeringBaseStats(module)??stats;const canonical=primitiveEngineeringInputsFor(base,blueprintGrade,effect);const missing=missingBaseLabels(base,baseStats(base),canonical.grade.features,canonical.experimental?.modifiers);if(missing.length>0){return engineeringNormalizationUnsupported("unresolvedModifiers",{slot:module.Slot,symbol:module.Item,labels:missing})}this.applyBlueprint(module.Slot,blueprint,{grade:grade,quality:1,...experimental===null?{}:{experimentalEffectSymbol:experimental}})}return deepFreeze({kind:"normalized",previousQuality:previousQuality,quality:1})}setPreEngineeredVariant(slotKey,variant){if(variant===null||typeof variant!=="object"){throw new TypeError(`ShipLoadout.setPreEngineeredVariant: variant must be a pre-engineered variant, received ${describeValue(variant)}`)}requireString(variant.symbol,"ShipLoadout.setPreEngineeredVariant: variant.symbol");requireString(variant.blueprintSymbol,"ShipLoadout.setPreEngineeredVariant: variant.blueprintSymbol");requireString(variant.acquisition,"ShipLoadout.setPreEngineeredVariant: variant.acquisition");requireStringIfPresent(variant.experimentalEffectSymbol,"ShipLoadout.setPreEngineeredVariant: variant.experimentalEffectSymbol");const known=getPreEngineeredVariants(variant.symbol).find(candidate=>candidate.blueprintSymbol.toLowerCase()===variant.blueprintSymbol.toLowerCase()&&candidate.grade===variant.grade&&(candidate.experimentalEffectSymbol?.toLowerCase()??"")===(variant.experimentalEffectSymbol?.toLowerCase()??"")&&candidate.acquisition===variant.acquisition);if(!known){throw new RangeError(`ShipLoadout.setPreEngineeredVariant: no catalogued variant "${truncate(variant.blueprintSymbol)}" for module "${truncate(variant.symbol)}"`)}const stats=getPreEngineeredStats(known);const unresolved=unresolvedModifiers(known);if(unresolved.length>0){throw new TypeError(`ShipLoadout.setPreEngineeredVariant: cannot resolve "${truncate(variant.blueprintSymbol)}" for module "${truncate(variant.symbol)}"; missing base stats for ${unresolved.join(", ")}`)}this.setModule(slotKey,stats);const module=this.#fittedModuleFor(slotKey);const journalModifiers=getPreEngineeredJournalModifiers(known);const engineering={BlueprintName:known.blueprintSymbol,Level:known.grade,Quality:1,...known.experimentalEffectSymbol===void 0?{}:{ExperimentalEffect:known.experimentalEffectSymbol},...journalModifiers.length>0?{Modifiers:journalModifiers}:{}};this.#replaceModule(module.Slot,{...module,Engineering:engineering},cloneModuleStats(stats),getPreEngineeredModifiers(known));return this}clearEngineering(slotKey){const module=this.#fittedModuleFor(slotKey);if(module&&this.#statsFor(module)?.engineeringLocked){throw new TypeError(`ShipLoadout.clearEngineering: module "${truncate(module.Item)}" is a final pre-engineered article and its engineering cannot be removed`)}if(module?.Engineering){const baseStats2=this.#engineeringBaseStats(module);const bare={Slot:module.Slot,Item:module.Item};if(module.On!==void 0)bare.On=module.On;if(module.Priority!==void 0){bare.Priority=module.Priority}if(module.Health!==void 0)bare.Health=module.Health;if(module.Value!==void 0)bare.Value=module.Value;this.#replaceModule(module.Slot,bare,baseStats2??void 0)}return this}setModuleEnabled(slotKey,on){this.#patchModule(slotKey,{On:on});return this}setModulePriority(slotKey,priority){if(!Number.isInteger(priority)||priority<0||priority>4){throw new RangeError(`ShipLoadout: power priority must be an integer 0-4, got ${truncate(priority)}`)}this.#patchModule(slotKey,{Priority:priority});return this}#patchModule(slotKey,patch){const module=this.#fittedModuleFor(slotKey);if(!module){throw new RangeError(`ShipLoadout: slot "${truncate(slotKey)}" is empty`)}this.#modules.set(module.Slot,cloneLoadoutModule({...module,...patch}));this.#slotCache.clear()}toLoadoutEvent(options={}){const unladenMass=this.#computedUnladenMass();const cargoCapacity=this.#computedCargoCapacity();const fuel=this.#computedFuelCapacity();const maxJumpRange=this.#exportableJumpRange(unladenMass);return exportLoadoutEvent({shipSymbol:this.#shipSymbol,...this.#top.ShipName===void 0?{}:{shipName:this.#top.ShipName},...this.#top.ShipIdent===void 0?{}:{shipIdent:this.#top.ShipIdent},modules:this.#modules,layout:this.#layout(),sourcePurchase:this.#sourcePurchase,retailHullValue:this.#ship.hullCost,unladenMass:unladenMass,cargoCapacity:cargoCapacity,fuelCapacity:fuel,maxJumpRange:maxJumpRange,sourceTotalsVoided:this.#importOutcomes.some(outcome=>outcome.sourceSymbol===null&&parseSlotName(outcome.slot)?.kind==="core"),statsFor:module=>this.#statsFor(module)},options)}toSlef(options){return toSlef(this.toLoadoutEvent(options),options.header)}toSlefString(options){return stringifySlef(this.toSlef(options),{indent:options.indent??0})}#exportableJumpRange(unladenMass){let drive;try{drive=this.#resolveDrive()}catch{return null}if(drive===null)return null;const tank=this.#computedFuelCapacity();return singleJumpRange(unladenMass,Math.min(tank.main,drive.maxFuel),drive)}#layout(){if(this.#layoutCache===void 0){this.#layoutCache=Object.freeze(enumerateSlots(this.#ship))}return this.#layoutCache}#requireSlot(slotKey){const wanted=normalizeKey(slotKey,SLOT_KEY);const slot=this.#layout().find(s=>normalizeKey(s.key,CATALOGUE_KEY)===wanted);if(!slot){throw new RangeError(`ShipLoadout: hull "${truncate(this.#shipSymbol)}" has no slot "${truncate(slotKey)}"`)}return slot}#fittedKey(slotKey){return matchingKeyIn(this.#modules,normalizeKey(slotKey,SLOT_KEY))}#fittedModuleFor(slotKey){const key=this.#fittedKey(slotKey);return key===null?void 0:this.#modules.get(key)}#calculationModules(){return[...this.#modules.values()].map(module=>({mass:this.#moduleMass(module),cargoCapacity:this.#moduleCapacity(module,"CargoCapacity","cargoCapacity"),fuelCapacity:this.#moduleCapacity(module,"FuelCapacity","fuelCapacity")}))}#moduleLimits(){const entries=[...this.#modules.values()].flatMap(module=>{const stats=this.#statsFor(module);return stats===null?[]:[stats]});return calculateModuleLimits(entries)}#moduleStatsAt(slotKey){const fitted=this.#fittedModuleFor(slotKey);return fitted===void 0?null:this.#statsFor(fitted)}#engineeringBaseStats(module){const fitted=this.#statsFor(module);if(!module.Engineering||preEngineeredVariantFor(module)===null)return fitted;const stock=builtInModuleBySymbol(module.Item,FITTED_ITEM);if(!stock)return fitted;return fitted?.engineeringLocked?cloneModuleStats({...stock,engineeringLocked:true}):stock}#moduleForEffectiveStats(module){const modifiers=this.#primitiveModifiers.get(module.Slot);if(modifiers===void 0||module.Engineering===void 0)return module;return{...module,Engineering:{...module.Engineering,Modifiers:modifiers}}}#modulesForEffectiveStats(){return[...this.#modules.values()].map(module=>this.#moduleForEffectiveStats(module))}#moduleLimitRegression(slotKey,replacement,current=this.#moduleLimits(),previous=this.#moduleStatsAt(slotKey)){if(previous?.limitGroup===void 0&&previous?.limitIncrease===void 0&&replacement?.limitGroup===void 0&&replacement?.limitIncrease===void 0){return null}for(const usage of current){const count=usage.count-Number(previous?.limitGroup===usage.group)+Number(replacement?.limitGroup===usage.group);const increase=usage.increase-(previous?.limitIncrease?.group===usage.group?previous.limitIncrease.amount:0)+(replacement?.limitIncrease?.group===usage.group?replacement.limitIncrease.amount:0);const limit=usage.baseLimit+increase;const excess=Math.max(0,count-limit);if(excess>usage.excess){return{...usage,increase:increase,limit:limit,count:count,excess:excess}}}return null}#replaceModule(slotKey,replacement,replacementStats,primitiveModifiers){const previous=this.#modules.get(slotKey)??null;this.#adjustImportedFigures(previous,replacement,replacementStats);if(replacement===null){this.#modules.delete(slotKey);this.#moduleStats.delete(slotKey);this.#primitiveModifiers.delete(slotKey)}else{this.#modules.set(slotKey,cloneLoadoutModule(replacement));if(replacementStats!==void 0)this.#moduleStats.set(slotKey,replacementStats);if(primitiveModifiers===void 0)this.#primitiveModifiers.delete(slotKey);else this.#primitiveModifiers.set(slotKey,primitiveModifiers)}this.#slotCache.clear()}#adjustImportedFigures(previous,next,nextStats){if(this.#top.UnladenMass!==void 0){this.#top.UnladenMass+=this.#moduleMass(next,nextStats)-this.#moduleMass(previous)}if(this.#top.CargoCapacity!==void 0){this.#top.CargoCapacity+=this.#moduleCapacity(next,"CargoCapacity","cargoCapacity",nextStats)-this.#moduleCapacity(previous,"CargoCapacity","cargoCapacity")}if(this.#top.FuelCapacity?.Main!==void 0){const reserve=this.#top.FuelCapacity.Reserve;this.#top.FuelCapacity={Main:this.#top.FuelCapacity.Main+this.#moduleCapacity(next,"FuelCapacity","fuelCapacity",nextStats)-this.#moduleCapacity(previous,"FuelCapacity","fuelCapacity"),...reserve===void 0?{}:{Reserve:reserve}}}if(normalizeKey(previous?.Item,FITTED_ITEM)===normalizeKey(next?.Item,FITTED_ITEM)){return}if(previous!==null&&isCargoHatchSlot(previous.Slot)||next!==null&&isCargoHatchSlot(next.Slot)){return}delete this.#top.ModulesValue;delete this.#top.Rebuy}#moduleMass(module,statsOverride){if(module===null)return 0;if(isCargoHatchSlot(module.Slot))return 0;const modified=getLoadoutModifier(module,"Mass");if(modified!==null)return modified;return(statsOverride??this.#statsFor(module))?.mass??0}#moduleCapacity(module,modifierLabel,field,statsOverride){if(module===null)return 0;if(isCargoHatchSlot(module.Slot))return 0;const modified=getLoadoutModifier(module,modifierLabel);if(modified!==null)return modified;return(statsOverride??this.#statsFor(module))?.[field]??0}#frameShiftDrive(){for(const m of this.#modules.values()){const stats=this.#statsFor(m);if(stats?.slot==="frameShiftDrive")return{module:m,stats:stats}}return void 0}#resolveDrive(){const fsd=this.#frameShiftDrive();if(!fsd)return null;const{module:fsdModule,stats:base}=fsd;if(base.fuelMul===void 0||base.fuelPower===void 0){throw new TypeError(`ShipLoadout: the fitted record for frame shift drive "${truncate(fsdModule.Item)}" has no jump constants`)}const optMass=getLoadoutModifier(fsdModule,"FSDOptimalMass")??base.optMass;const maxFuel=getLoadoutModifier(fsdModule,"MaxFuelPerJump")??base.maxFuel;if(optMass===void 0||maxFuel===void 0){const missing=[...optMass===void 0?["optMass"]:[],...maxFuel===void 0?["maxFuel"]:[]];throw new TypeError(`ShipLoadout: the fitted record for frame shift drive "${truncate(fsdModule.Item)}" has no ${missing.join(" or ")}`)}return{optMass:optMass,maxFuel:maxFuel,fuelMul:base.fuelMul,fuelPower:base.fuelPower,jumpBoost:this.#resolveJumpBoost()}}#resolveJumpBoost(){for(const m of this.#modules.values()){const stats=this.#statsFor(m);if(stats?.engineeringGroup!=="fsdBoosters"&&(stats?.jumpBoost===void 0||stats.jumpBoost===0)){continue}if(m.On===false)continue;if(stats?.jumpBoost===void 0){throw new TypeError(`ShipLoadout: the fitted record for FSD booster "${truncate(m.Item)}" has no jumpBoost`)}return stats.jumpBoost}return 0}#statsFor(module){if(module===null)return null;const stats=this.#moduleStats.get(module.Slot)??builtInModuleBySymbol(module.Item,FITTED_ITEM);if(stats)return stats;return isBuiltInHullModule(module)?builtInModuleBySymbol("ModularCargoBayDoor","ShipLoadout: built-in module"):null}};export{LoadoutEditError,ShipLoadout};//# sourceMappingURL=chunk-A7KNIFRU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ships/internal/loadout-export.ts","../src/ships/ship-loadout.ts"],"names":["fixedSlotReason","validateLoadout","calculateModuleLimits","publishLoadoutInternals","normalizeLoadoutEvent","preEngineeredVariantFor","moduleFitProblem","effectiveModule","moduleFitError","getShipBySymbol","parseSlef","toSlef","stringifySlef","getLoadoutModifier","getSourceModuleValue","statesInertModifiers","rolledOverFixedArticle","isNonOutfittingSlot","isBuiltInHullModule","cloneLoadoutModule","cloneModuleStats","availableBlueprintsFor","availableExperimentalsFor","ownKeyIn","FITTED_ITEM","blueprintAvailableFor","blueprintRoutesFor","experimentalAvailableFor","primitiveEngineeringInputsFor","missingBaseLabels","journalModifiersFor","getPreEngineeredStats","getPreEngineeredJournalModifiers","getPreEngineeredModifiers","ordinaryEngineeringProof","unresolvedModifiers","matchingKeyIn","isCargoHatchSlot","orderBySlotLayout","builtInModuleBySymbol","getPreEngineeredVariants","ALL_MODULES","getExperimentalEffect","singleJumpRange","calculateUnladenMass","calculateCargoCapacity","calculateFuelCapacity","resolveBlueprintForModule","getBlueprintGrade","getDefaultLoadout","getExperimentalsForModule","baseStats","computeModifiers","labelsForDamageType","scaleForLabel","ammunitionCapacity","loadoutSlotName","parseSlotName","enumerateSlots","normalizeKey","CATALOGUE_KEY","truncate","describeValue","requireString","requireStringIfPresent","deepFreeze","REBUY_FRACTION","exportLoadoutEvent","input","options","fromSource","credits","source","sourcePurchase","totals","sourceTotalsVoided","sourceTotalsHold","modules","hullValue","retailHullValue","modulesValue","computedModulesValue","statsFor","rebuy","Math","trunc","Ship","shipSymbol","toLowerCase","shipName","ShipName","shipIdent","ShipIdent","HullValue","ModulesValue","UnladenMass","unladenMass","CargoCapacity","cargoCapacity","maxJumpRange","MaxJumpRange","FuelCapacity","Main","fuelCapacity","main","Reserve","reserve","Rebuy","Modules","exportModules","ordered","moduleOrder","slotOrderedModules","layout","values","map","module","on","On","explicitPower","priority","Priority","value","sourceModuleValue","moduleValue","Slot","Item","Health","Value","Engineering","sum","stats","cost","SOURCE_ITEM","entry","item","moduleValues","key","slot","fitted","get","SLOT_KEY","FITTED_SLOT","LoadoutEditError","TypeError","code","constraint","params","constructor","message","super","this","structuredClone","experimentalEffectUnsupported","kind","engineeringNormalizationUnsupported","weighable","tonnes","Number","isFinite","AGGREGATE_STATS","ShipLoadout","_ShipLoadout","ship","moduleStats","primitiveModifiers","top","importOutcomes","slotCache","Map","layoutCache","effectiveModules","modulesForEffectiveStats","moduleForEffectiveStats","resolveDrive","frameShiftDriveModule","frameShiftDrive","calculationModules","statedMainFuel","fromSlef","index","entries","length","imported","data","fromImported","fromLoadout","event","outcomes","loadout","unresolved","rollStatedRecipe","push","engineering","BlueprintName","stated","Modifiers","has","variant","acquisition","Level","grade","applyBlueprint","quality","Quality","ExperimentalEffect","experimentalEffectSymbol","action","sourceSymbol","blueprintSymbol","passedOver","preEngineeredVariant","error","RangeError","empty","requested","symbol","filter","parsed","computedUnladenMass","hullMass","cap","Object","freeze","computed","computedFuelCapacity","computedCargoCapacity","reserveFuelCapacity","validation","slots","byKey","builtIn","fitProblem","thrusterMaxMass","maxMass","requiresKnownSlot","fitError","fitConstraint","fitParams","exclusionGroup","limitGroup","limitIncrease","dry","fuel","cargo","mass","cached","currentLimits","moduleLimits","moduleStatsAt","fixedReason","immovableReason","moduleLimitRegression","name","fittedModuleAt","removable","set","slotKey","fittedModuleFor","raw","effective","health","effectiveStats","ammunition","fittedModules","keys","flatMap","availableBlueprints","availableExperimentalEffects","modulesForSlot","requireSlot","occupied","Set","group","currentStats","grantOnly","repairFixedMount","wanted","fittedKey","resultSlot","canonicalKey","status","reason","current","valid","defaultModule","find","ownKey","replacement","replacementStats","replaceModule","setModule","catalogued","field","problem","conflict","previousSlot","previousSymbol","limitProblem","count","limit","removeModule","candidate","wantedGrade","wantedQuality","wantedExperimental","fittedStats","recipe","named","written","trim","resolved","some","isInteger","experimental","engineeringLocked","offered","blueprint","route","join","engineeringBaseStats","base","canonical","missing","features","modifiers","damageDistribution","type","label","damageModifier","Label","OriginalValue","setExperimentalEffect","previous","effect","restoresBakedEffect","stock","labels","originalEffect","withoutEffect","adjusted","currentEffect","blueprintGrade","previousExperimentalEffectSymbol","completeEngineeringGrade","previousQuality","proof","setPreEngineeredVariant","known","journalModifiers","clearEngineering","bare","setModuleEnabled","patchModule","setModulePriority","patch","clear","toLoadoutEvent","exportableJumpRange","hullCost","outcome","header","toSlefString","indent","drive","tank","min","maxFuel","s","moduleMass","moduleCapacity","usage","increase","amount","baseLimit","excess","max","adjustImportedFigures","delete","next","nextStats","statsOverride","modified","modifierLabel","m","fsd","fsdModule","fuelMul","fuelPower","optMass","jumpBoost","resolveJumpBoost","engineeringGroup"],"mappings":"O,i+DAkDA,IAAMkE,eAAiB,IAGhB,SAASC,mBACZC,MACAC,SAEA,MAAMC,WAAaD,QAAQE,UAAY,SACvC,MAAMC,OAASF,WAAaF,MAAMK,eAAiB,KACnD,MAAMC,OACFF,SAAW,OAASJ,MAAMO,oBAAsBC,iBAAiBR,MAAMS,QAASL,QAC1EA,OACA,KACV,MAAMM,UAAYR,WAAcE,QAAQM,WAAa,KAAQV,MAAMW,gBACnE,MAAMC,aAAeV,WACdI,QAAQM,cAAgB,KACzBC,qBAAqBb,MAAMS,QAAST,MAAMc,UAChD,MAAMC,MAAQb,WACPI,QAAQS,OAAS,KAClBL,YAAc,MAAQE,eAAi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HsE,gBACAtB,gBACAoB,QAASlE,KAAKkE,QACdC,UAAWnE,KAAKmE,UAChBE,UAAW/O,MAAKgP,mBAExB,CAGA,iBAAAA,GACI,IAAA,MAAWP,KAAKzO,MAAK1E,QAASqC,SAAU,CACpC,MAAMiB,MAAQoB,MAAKrE,SAAU8S,GAO7B,GACI7P,OAAOqQ,mBAAqB,gBAC3BrQ,OAAOmQ,iBAAc,GAAanQ,MAAMmQ,YAAc,GACzD,CACE,QACJ,CACA,GAAIN,EAAE1Q,KAAO,MAAO,SACpB,GAAIa,OAAOmQ,iBAAc,EAAW,CAChC,MAAM,IAAItP,UACN,mDAAmDnF,SAASmU,EAAElQ,0BAEtE,CACA,OAAOK,MAAMmQ,SACjB,CACA,OAAO,CACX,CAGA,SAAApT,CAAUkC,QACN,GAAIA,SAAW,KAAM,OAAO,KAC5B,MAAMe,MACFoB,MAAKa,YAAaxB,IAAIxB,OAAOS,OAAStF,sBAAsB6E,OAAOU,KAAMtG,aAC7E,GAAI2G,MAAO,OAAOA,MAIlB,OAAOjH,oBAAoBkG,QACrB7E,sBAAsB,sBAAuB,gCAC7C,IACV,UACJwG,iBAAAkB"}
@@ -1 +1 @@
1
- import{shieldMetrics}from"./chunk-5VWACBTN.js";import{getShipBySymbol,getShipByName,getShipSlots}from"./chunk-6UNAD74Z.js";import{getLoadoutModifier}from"./chunk-T4MKUKYS.js";import{sourcePurchaseFromLoadout}from"./chunk-NIURLW2F.js";import{identifyPreEngineeredVariant,unrollableFixedArticle,cloneLoadoutModule,isNonOutfittingSlot,isBuiltInHullModule,matchingKeyIn,ownKeyIn,getPreEngineeredStats,getPreEngineeredModifiers,cloneModuleStats,isFinalGuardianWeaponEngineering,scaleDamageComponents}from"./chunk-4OTQBHQL.js";import{weaponMetrics,combinedRateOfFire}from"./chunk-37JIMWLK.js";import{builtInModuleBySymbol,getBulkheadsForShip}from"./chunk-3LZXB2MC.js";import{getPreEngineeredVariants}from"./chunk-PL75RTA2.js";import{CORE_MODULES}from"./chunk-FA5JVXVG.js";import{getExperimentalEffect}from"./chunk-77I24V6B.js";import{getDefaultLoadout}from"./chunk-GRIK3EDH.js";import{fieldForLabel,scaleForLabel,labelsForField,capabilityValueForLabel,damageTypeForLabel}from"./chunk-CJQ37JII.js";import{ammunitionCapacity}from"./chunk-AA3K5XUE.js";import{parseSlotName,SLOT_RESTRICTION_LABELS,enumerateSlots}from"./chunk-RAO35XDF.js";import{normalizeKey}from"./chunk-BKWLI44T.js";import{truncate,requireString,describeValue,requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";var MILITARY_PREFIXES=["int_hullreinforcement","int_metaalloyhullreinforcement","int_modulereinforcement","int_shieldcellbank","int_guardianhullreinforcement","int_guardianmodulereinforcement","int_guardianshieldreinforcement"];var MINING_PREFIXES=["hpt_mininglaser","hpt_mining_abrblstr","hpt_mining_seismchrgwarhd","hpt_mining_subsurfdispmisle","hpt_human_extraction","hpt_miningtoolv2"];var CARGO_PREFIXES=["int_cargorack","int_largecargorack","int_corrosionproofcargorack","int_fueltank"];var RESTRICTED_SLOT_PREFIXES={mining:MINING_PREFIXES,military:MILITARY_PREFIXES,cargo:CARGO_PREFIXES,limpetController:["int_dronecontrol","int_multidronecontrol"],vesselHangar:["int_fighterbay"],passenger:["int_passengercabin","int_mkii_passengercabin"],planetaryApproachSuite:["int_planetapproachsuite"]};var problem=(constraint,message,params)=>({constraint:constraint,message:message,...params===void 0?{}:{params:params}});function restrictionProblem(slot,symbol){const restriction=slot.restriction;if(!restriction)return null;if(RESTRICTED_SLOT_PREFIXES[restriction].some(prefix=>symbol.startsWith(prefix))){return null}return problem("restrictedMount",`slot only takes ${SLOT_RESTRICTION_LABELS[restriction]}`,{restriction:restriction})}function moduleSlotProblem(slot,module){const required=module.restrictedToSlot;if(!required||slot.restriction===required)return null;return problem("restrictedMount",`module only fits a mount that takes ${SLOT_RESTRICTION_LABELS[required]}`,{restriction:required})}function moduleFitProblem(shipSymbol,slot,module){if(slot.kind==="cargoHatch"){return problem("immutableSlot","the cargoHatch slot cannot be changed")}if(slot.kind==="armour"){const hull=getShipBySymbol(shipSymbol);if(module.slot!=="armour"||module.ship===void 0){return problem("armourRequired","not a ship armour module")}if(!hull||module.ship.toLowerCase()!==hull.name.toLowerCase()){const armourHull=getShipByName(module.ship);return problem("wrongHullArmour",`armour belongs to ${truncate(module.ship)}, not ${truncate(hull?.name??shipSymbol)}`,{armourShipName:module.ship,...armourHull===null?{}:{armourShipSymbol:armourHull.symbol},shipSymbol:shipSymbol,...hull===null?{}:{shipName:hull.name}})}return null}const restricted=module.restrictedToShips;if(restricted&&!restricted.some(symbol2=>symbol2.toLowerCase()===shipSymbol.toLowerCase())){const allowedShipNames=restricted.map(symbol2=>{const hull=getShipBySymbol(symbol2);return hull?.name??symbol2});const labels=restricted.map((symbol2,index)=>{const name=allowedShipNames[index];return name===symbol2?symbol2:`${name} (${symbol2})`});return problem("restrictedHull",`module is restricted to ${truncate(labels.join(", "))}`,{allowedShipNames:allowedShipNames,allowedShipSymbols:[...restricted],shipSymbol:shipSymbol})}const wrongMount=moduleSlotProblem(slot,module);if(wrongMount)return wrongMount;const symbol=module.symbol.toLowerCase();const moduleSlot=module.slot;switch(slot.kind){case"core":if(moduleSlot!==slot.core){return problem("wrongCoreType",`not a ${slot.core} module`,{requiredCore:slot.core,moduleSlot:moduleSlot??"none"})}break;case"hardpoint":{if(module.category!=="hardpoint"){return problem("hardpointRequired","not a hardpoint weapon")}const restricted2=restrictionProblem(slot,symbol);if(restricted2)return restricted2;break}case"utility":if(module.category!=="utility"){return problem("utilityRequired","not a utility module")}return null;case"optional":{const isFuelTank=moduleSlot==="fuelTank";if(module.category!=="internal"&&!isFuelTank){return problem("optionalInternalRequired","not an optional-internal module")}if(moduleSlot&&!isFuelTank){return problem("coreModuleInOptionalSlot","a core module only fits its core slot")}const restricted2=restrictionProblem(slot,symbol);if(restricted2)return restricted2;break}}return module.class>slot.size?problem("oversized",`module size ${truncate(module.class)} exceeds slot size ${slot.size}`,{moduleClass:module.class,slotSize:slot.size}):null}function moduleFitError(shipSymbol,slot,module){return moduleFitProblem(shipSymbol,slot,module)?.message??null}function preEngineeredVariantFor(module){return identifyPreEngineeredVariant(module)??(module.Engineering?unrollableFixedArticle(module.Item,module.Engineering):null)}function captureLoadoutEvent(event){const modules=event.Modules;const shipName=event.ShipName;const shipIdent=event.ShipIdent;const hullValue=event.HullValue;const modulesValue=event.ModulesValue;const rebuy=event.Rebuy;const unladenMass=event.UnladenMass;const cargoCapacity=event.CargoCapacity;const fuelCapacity=event.FuelCapacity;return{Ship:event.Ship,Modules:Array.isArray(modules)?captureEach(modules,captureModule):modules,...shipName===void 0?{}:{ShipName:shipName},...shipIdent===void 0?{}:{ShipIdent:shipIdent},...hullValue===void 0?{}:{HullValue:hullValue},...modulesValue===void 0?{}:{ModulesValue:modulesValue},...rebuy===void 0?{}:{Rebuy:rebuy},...unladenMass===void 0?{}:{UnladenMass:unladenMass},...cargoCapacity===void 0?{}:{CargoCapacity:cargoCapacity},...fuelCapacity===void 0?{}:{FuelCapacity:{...fuelCapacity}}}}function captureEach(values,capture){const captured=[];const{length:length}=values;for(let index=0;index<length;index++)captured.push(capture(values[index]));return captured}function captureModule(module){if(module===null||typeof module!=="object")return module;const on=module.On;const priority=module.Priority;const health=module.Health;const value=module.Value;const engineering=module.Engineering;return{Slot:module.Slot,Item:module.Item,...on===void 0?{}:{On:on},...priority===void 0?{}:{Priority:priority},...health===void 0?{}:{Health:health},...value===void 0?{}:{Value:value},...engineering===void 0?{}:{Engineering:captureEngineering(engineering)}}}function captureEngineering(engineering){if(engineering===null||typeof engineering!=="object")return engineering;const experimental=engineering.ExperimentalEffect;const experimentalLocalised=engineering.ExperimentalEffect_Localised;const modifiers=engineering.Modifiers;return{BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:engineering.Quality,...experimental===void 0?{}:{ExperimentalEffect:experimental},...experimentalLocalised===void 0?{}:{ExperimentalEffect_Localised:experimentalLocalised},...modifiers===void 0?{}:{Modifiers:Array.isArray(modifiers)?captureEach(modifiers,modifier=>modifier!==null&&typeof modifier==="object"?{...modifier}:modifier):modifiers}}}function hullLayout(shipSymbol){const slots=getShipSlots(shipSymbol);return slots?enumerateSlots(slots):[]}function fixedMountRejects(shipSymbol,layout,slot,stats){const mount=layout.find(candidate=>candidate.key.toLowerCase()===slot.toLowerCase());return mount!==void 0&&moduleFitProblem(shipSymbol,mount,stats)!==null}function normalizeLoadoutEvent(rawEvent){const event=captureLoadoutEvent(rawEvent);requireString(event.Ship,"ShipLoadout.fromLoadout: event.Ship");if(!Array.isArray(event.Modules)){throw new TypeError(`ShipLoadout.fromLoadout: event.Modules must be an array, received ${describeValue(event.Modules)}`)}const modules=/* @__PURE__ */new Map;const slots=/* @__PURE__ */new Set;for(const module of event.Modules){if(module===null||typeof module!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: event.Modules[] must hold module objects, received ${describeValue(module)}`)}requireString(module.Slot,"ShipLoadout.fromLoadout: module.Slot");requireString(module.Item,"ShipLoadout.fromLoadout: module.Item");if(module.Engineering!==void 0){if(module.Engineering===null||typeof module.Engineering!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering must be an object, received ${describeValue(module.Engineering)}`)}requireStringIfPresent(module.Engineering.BlueprintName,"ShipLoadout.fromLoadout: module.Engineering.BlueprintName");requireStringIfPresent(module.Engineering.ExperimentalEffect,"ShipLoadout.fromLoadout: module.Engineering.ExperimentalEffect");if(module.Engineering.Modifiers!==void 0&&!Array.isArray(module.Engineering.Modifiers)){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering.Modifiers must be an array, received ${describeValue(module.Engineering.Modifiers)}`)}for(const[index,modifier]of(module.Engineering.Modifiers??[]).entries()){if(modifier===null||typeof modifier!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering.Modifiers[${index}] must be an object, received ${describeValue(modifier)}`)}requireString(modifier.Label,`ShipLoadout.fromLoadout: module.Engineering.Modifiers[${index}].Label`)}}const normalizedSlot=module.Slot.toLowerCase();if(slots.has(normalizedSlot)){throw new TypeError(`ShipLoadout.fromLoadout: duplicate slot "${truncate(module.Slot)}"`)}slots.add(normalizedSlot);modules.set(module.Slot,cloneLoadoutModule(module))}const top={};if(event.ShipName!==void 0)top.ShipName=event.ShipName;if(event.ShipIdent!==void 0)top.ShipIdent=event.ShipIdent;if(event.HullValue!==void 0)top.HullValue=event.HullValue;if(event.ModulesValue!==void 0)top.ModulesValue=event.ModulesValue;if(event.Rebuy!==void 0)top.Rebuy=event.Rebuy;if(event.UnladenMass!==void 0)top.UnladenMass=event.UnladenMass;if(event.CargoCapacity!==void 0)top.CargoCapacity=event.CargoCapacity;if(event.FuelCapacity!==void 0)top.FuelCapacity={...event.FuelCapacity};let invalidatesAggregates=false;const outcomes=[];const defaults=getDefaultLoadout(event.Ship)?.modules??[];let layout;for(const[slot,module]of modules){if(isNonOutfittingSlot(slot)||isBuiltInHullModule(module))continue;const stats=builtInModuleBySymbol(module.Item,"ShipLoadout.fromLoadout: module.Item");const slotKind=parseSlotName(slot)?.kind;const fallback=slotKind==="core"||slotKind==="armour"||slotKind==="cargoHatch"?defaults.find(candidate=>candidate.slot.toLowerCase()===slot.toLowerCase()):void 0;const rejected=fallback!==void 0&&(stats===null||slotKind==="cargoHatch"||fixedMountRejects(event.Ship,layout??=hullLayout(event.Ship),slot,stats));if(stats!==null&&!rejected)continue;if(fallback){modules.set(slot,{Slot:slot,Item:fallback.symbol,...module.On===void 0?{}:{On:module.On},...module.Priority===void 0?{}:{Priority:module.Priority},...module.Health===void 0?{}:{Health:module.Health}});outcomes.push({action:"defaulted",slot:slot,sourceSymbol:module.Item,replacementSymbol:fallback.symbol})}else{modules.delete(slot);outcomes.push({action:"emptied",slot:slot,sourceSymbol:module.Item})}invalidatesAggregates=true}for(const fallback of defaults){const slotKind=parseSlotName(fallback.slot)?.kind;if(slotKind!=="core"&&slotKind!=="armour"&&slotKind!=="cargoHatch"||matchingKeyIn(modules,fallback.slot)!==null){continue}const slot=ownKeyIn(modules,fallback.slot);modules.set(slot,{Slot:slot,Item:fallback.symbol});outcomes.push({action:"defaulted",slot:slot,sourceSymbol:null,replacementSymbol:fallback.symbol});if(slotKind==="core")invalidatesAggregates=true}if(invalidatesAggregates){delete top.ModulesValue;delete top.Rebuy;delete top.UnladenMass;delete top.CargoCapacity;delete top.FuelCapacity}const moduleStats=/* @__PURE__ */new Map;const primitiveModifiers=/* @__PURE__ */new Map;for(const module of modules.values()){const engineering=module.Engineering;const variant=preEngineeredVariantFor(module);const catalogueVariantStats=variant?getPreEngineeredStats(variant):null;let variantStats=catalogueVariantStats;const retainsBakedExperimental=variant?.experimentalEffectSymbol!==void 0&&typeof engineering?.ExperimentalEffect==="string"&&variant.experimentalEffectSymbol.trim().toLowerCase()===engineering.ExperimentalEffect.trim().toLowerCase();if(variant&&catalogueVariantStats&&!catalogueVariantStats.engineeringLocked&&!retainsBakedExperimental){const{experimentalEffectSymbol:originalExperimental,...withoutExperimental}=variant;const currentExperimental=engineering?.ExperimentalEffect;const currentVariant=typeof currentExperimental==="string"?{...withoutExperimental,experimentalEffectSymbol:currentExperimental}:withoutExperimental;variantStats=getPreEngineeredStats(withoutExperimental);primitiveModifiers.set(module.Slot,[...engineering?.Modifiers??[],...getPreEngineeredModifiers(currentVariant)])}if(variantStats)moduleStats.set(module.Slot,cloneModuleStats(variantStats));const guardianFinal=typeof engineering?.BlueprintName==="string"&&isFinalGuardianWeaponEngineering(module.Item,engineering.BlueprintName);if(variantStats?.engineeringLocked||typeof engineering?.BlueprintName!=="string"||!guardianFinal){continue}const normalizedBlueprint=normalizeKey(engineering.BlueprintName,"ShipLoadout.fromLoadout: module.Engineering.BlueprintName");const normalizedExperimental=normalizeKey(engineering.ExperimentalEffect,"ShipLoadout.fromLoadout: module.Engineering.ExperimentalEffect");const variants=getPreEngineeredVariants(module.Item);const exact=variants.find(candidate=>candidate.engineeringLocked===true&&candidate.blueprintSymbol.toLowerCase()===normalizedBlueprint&&candidate.grade===engineering.Level&&candidate.experimentalEffectSymbol?.toLowerCase()===normalizedExperimental);const guardianBase=variants.find(candidate=>candidate.engineeringLocked===true&&candidate.blueprintSymbol.toLowerCase()===normalizedBlueprint&&candidate.grade===engineering.Level&&candidate.experimentalEffectSymbol===void 0);const stats=exact?getPreEngineeredStats(exact):guardianBase&&engineering.ExperimentalEffect!==void 0?getPreEngineeredStats({...guardianBase,experimentalEffectSymbol:engineering.ExperimentalEffect}):builtInModuleBySymbol(module.Item,"ShipLoadout.fromLoadout: module.Item");if(stats){moduleStats.set(module.Slot,cloneModuleStats({...stats,engineeringLocked:true}))}}return{shipSymbol:event.Ship,modules:modules,moduleStats:moduleStats,primitiveModifiers:primitiveModifiers,top:top,sourcePurchase:sourcePurchaseFromLoadout(event),outcomes:deepFreeze(outcomes)}}var NO_ISSUES=Object.freeze([]);function completeResult(value){return Object.freeze({value:value,complete:true,issues:NO_ISSUES})}function incompleteResult(issues){return Object.freeze({value:null,complete:false,issues:Object.freeze(issues.map(issue=>Object.freeze({...issue,...issue.params?{params:Object.freeze({...issue.params})}:{}})))})}var PREFIX={powerPlant:["int_powerplant","int_guardianpowerplant"],thrusters:["int_engine","int_mkiiagileboost_engine"],frameShiftDrive:["int_hyperdrive"],powerDistributor:["int_powerdistributor","int_guardianpowerdistributor"],shieldGenerator:["int_shieldgenerator"],shieldCellBank:["int_shieldcellbank"],shieldBooster:["hpt_shieldbooster"],shieldReinforcement:["int_guardianshieldreinforcement"],hullReinforcement:["int_hullreinforcement","int_guardianhullreinforcement","int_metaalloyhullreinforcement"],moduleReinforcement:["int_modulereinforcement","int_guardianmodulereinforcement"]};var startsWithAny=(symbol,prefixes)=>prefixes.some(prefix=>symbol.toLowerCase().startsWith(prefix));function isPowerDistributor(module,stats){return stats?.slot?stats.slot==="powerDistributor":startsWithAny(module.Item,PREFIX.powerDistributor)}function isPowerPlant(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="powerPlant")return true;return stats?.slot?stats.slot==="powerPlant":startsWithAny(module.Item,PREFIX.powerPlant)}function isThruster(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="thrusters")return true;return stats?.slot?stats.slot==="thrusters":startsWithAny(module.Item,PREFIX.thrusters)}function isFrameShiftDrive(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="frameShiftDrive")return true;return stats?.slot?stats.slot==="frameShiftDrive":startsWithAny(module.Item,PREFIX.frameShiftDrive)}function isEnabled(module){return module.On!==false}function priorityOf(module){return(module.Priority??0)+1}function effectiveStat(module,field,stats){const stated=statedModifier(module,field);if(stated!==void 0)return stated;const base=stats?.[field];return typeof base==="number"?base:void 0}function statedModifier(module,field){for(const label of labelsForField(field)){if(capabilityValueForLabel(label)!==null)continue;const modified=getLoadoutModifier(module,label);if(modified!==null)return modified/scaleForLabel(label)}return void 0}function effectiveCapability(module,field,stats){for(const label of labelsForField(field)){if(capabilityValueForLabel(label)===null)continue;if(module.Engineering?.Modifiers?.some(modifier=>modifier.Label.toLowerCase()===label.toLowerCase())){return true}}const base=stats[field];return typeof base==="boolean"?base:void 0}function effectiveDamageDistribution(module,stats){const fromEffect=module.Engineering?.ExperimentalEffect?getExperimentalEffect(module.Engineering.ExperimentalEffect)?.damageDistribution:void 0;const distribution={...fromEffect??stats.damageDistribution};let resolved=fromEffect!==void 0||stats.damageDistribution!==void 0;const seen=/* @__PURE__ */new Set;for(const modifier of module.Engineering?.Modifiers??[]){const type=damageTypeForLabel(modifier.Label);if(type===null||seen.has(type))continue;seen.add(type);if(modifier.Value===void 0)continue;distribution[type]=modifier.Value/scaleForLabel(modifier.Label);resolved=true}return resolved?distribution:void 0}function convertsDamage(module){if(module.Engineering?.ExperimentalEffect&&getExperimentalEffect(module.Engineering.ExperimentalEffect)?.damageDistribution){return true}return(module.Engineering?.Modifiers??[]).some(modifier=>damageTypeForLabel(modifier.Label)!==null)}function modifierRatio(module,stats,field){const base=stats?.[field];if(typeof base!=="number"||base===0)return 1;const effective=effectiveStat(module,field,stats);return effective===void 0?1:effective/base}function relatedStat(module,stats,field,ratio){const stated=statedModifier(module,field);if(stated!==void 0)return stated;const base=stats?.[field];return typeof base==="number"?base*ratio:void 0}function effectiveModule(module,stats){if(!stats||!module.Engineering)return stats;const merged={...stats};const fields=new Set(Object.keys(stats));for(const modifier of module.Engineering.Modifiers??[]){const field=fieldForLabel(modifier.Label,stats);if(field)fields.add(field)}for(const key of fields){const capability=effectiveCapability(module,key,stats);if(capability!==void 0){merged[key]=capability;continue}const value=effectiveStat(module,key,stats);if(value!==void 0)merged[key]=value}if(stats.engineeringGroup==="thrusters"){const massRatio=modifierRatio(module,stats,"optMass");const minMass=relatedStat(module,stats,"minMass",massRatio);const maxMass=relatedStat(module,stats,"maxMass",massRatio);if(minMass!==void 0)merged.minMass=minMass;if(maxMass!==void 0)merged.maxMass=maxMass}if(stats.engineeringGroup==="thrusters"||stats.engineeringGroup==="shieldGenerators"){const performanceRatio=modifierRatio(module,stats,"optMultiplier");const minMultiplier=relatedStat(module,stats,"minMultiplier",performanceRatio);const maxMultiplier=relatedStat(module,stats,"maxMultiplier",performanceRatio);if(minMultiplier!==void 0)merged.minMultiplier=minMultiplier;if(maxMultiplier!==void 0)merged.maxMultiplier=maxMultiplier;if(stats.engineeringGroup==="thrusters"){for(const field of["minSpeedMultiplier","optSpeedMultiplier","maxSpeedMultiplier","minRotationMultiplier","optRotationMultiplier","maxRotationMultiplier"]){const value=stats[field];if(value!==void 0)merged[field]=value*performanceRatio}}}const damageDistribution=effectiveDamageDistribution(module,stats);if(damageDistribution)merged.damageDistribution=damageDistribution;if(stats.category==="hardpoint")normalizeEffectiveWeapon(module,merged);if(convertsDamage(module)){delete merged.damageComponents}else if(stats.damageComponents){merged.damageComponents=scaleDamageComponents(stats.damageComponents,stats.damage,typeof merged.damage==="number"?merged.damage:void 0)}return merged}function powerConsumerFor(module,stats){const draw=effectiveStat(module,"powerDraw",stats);if(draw===void 0||draw===0)return null;const mounted=stats?.category==="hardpoint"||stats?.category==="utility";return{draw:draw,priority:priorityOf(module),enabled:isEnabled(module),deployedOnly:mounted&&stats?.alwaysPowered!==true,label:module.Slot,symbol:module.Item}}function powerAvailable(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(!isPowerPlant(module,stats))continue;if(!isEnabled(module))return 0;return effectiveStat(module,"powerCapacity",stats)??0}return 0}var DEFAULT_SLOT={powerCapacity:"PowerPlant",heatEfficiency:"PowerPlant",thrusters:"MainEngines",powerDistributor:"PowerDistributor"};var UNRESOLVED_FACT={thrusters:"thruster stats",shieldGenerator:"shield-generator stats",powerCapacity:"power capacity",heatEfficiency:"heat efficiency",powerDistributor:"power-distributor stats"};var NOTHING_FITTED={powerCapacity:"PowerPlant: no power plant is fitted",heatEfficiency:"PowerPlant: no power plant is fitted",thrusters:"MainEngines: no thrusters are fitted",powerDistributor:"PowerDistributor: no power distributor is fitted"};function metricIssue(field,reason,module){const defaultSlot=DEFAULT_SLOT[field];const slot=module?.Slot??defaultSlot;const symbol=module?.Item;const params={field:field,reason:reason,...slot===void 0?{}:{slot:slot},...symbol===void 0?{}:{symbol:symbol}};let message;if(reason==="missing"){message=NOTHING_FITTED[field]??"no shield generator is fitted"}else if(reason==="unresolved"){const unavailable=UNRESOLVED_FACT[field]??field;message=`${truncate(slot??field)}: ${unavailable} unavailable for ${truncate(symbol??field)}`}else if(reason==="disabled"){message=`${truncate(slot??field)}: ${truncate(symbol??field)} is switched off`}else if(reason==="invalid"){message=`${truncate(slot??field)}: ${truncate(symbol??field)} has invalid ${field}`}else{message=`${truncate(slot??field)}: ${truncate(symbol??field)} is not powered with hardpoints retracted`}return{field:field,reason:reason,...slot===void 0?{}:{slot:slot},...symbol===void 0?{}:{symbol:symbol},message:message,params:params}}function powerPlantIssueFor(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(!isPowerPlant(module,stats))continue;if(!isEnabled(module))return metricIssue("powerCapacity","disabled",module);const capacity=effectiveStat(module,"powerCapacity",stats);if(capacity===void 0)return metricIssue("powerCapacity","unresolved",module);return!Number.isFinite(capacity)||capacity<=0?metricIssue("powerCapacity","invalid",module):null}return metricIssue("powerCapacity","missing")}function powerDrawIssueFor(modules,statsFor){for(const module of modules){const consumer=powerConsumerFor(module,statsFor(module));if(consumer&&(!Number.isFinite(consumer.draw)||consumer.draw<0)){return metricIssue("powerDraw","invalid",module)}}return null}function poweredMetricBudgetFor(field,module,stats,modules,getBudget,statsFor){if(!isEnabled(module))return incompleteResult([metricIssue(field,"disabled",module)]);const plantIssue=powerPlantIssueFor(modules,statsFor);if(plantIssue)return incompleteResult([plantIssue]);const drawIssue=powerDrawIssueFor(modules,statsFor);if(drawIssue)return incompleteResult([drawIssue]);const budget=getBudget();return budget.available>0&&poweredStates(module,stats,budget).retracted?completeResult(budget):incompleteResult([metricIssue(field,"shed",module)])}function poweredShieldGeneratorResultFor(modules,getBudget,statsFor){for(const module of modules){if(!startsWithAny(module.Item,PREFIX.shieldGenerator))continue;const stats=statsFor(module);const powered=poweredMetricBudgetFor("shieldGenerator",module,stats,modules,getBudget,statsFor);if(!powered.complete)return powered;return stats===null?incompleteResult([metricIssue("shieldGenerator","unresolved",module)]):completeResult({module:module,budget:powered.value})}return incompleteResult([metricIssue("shieldGenerator","missing")])}function mapResistanceFields(read){return{kineticResistance:read("kineticResistance")??0,thermalResistance:read("thermalResistance")??0,explosiveResistance:read("explosiveResistance")??0,causticResistance:read("causticResistance")??0}}function resistancesOf(module,stats){return mapResistanceFields(field=>effectiveStat(module,field,stats))}function shieldInputFor(ship,modules,budget,statsFor){let generator=null;const boosters=[];let reinforcement=0;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!(budget.available>0&&poweredStates(module,stats,budget).retracted))continue;if(!generator&&startsWithAny(module.Item,PREFIX.shieldGenerator)){const massRatio=modifierRatio(module,stats,"optMass");const strengthRatio=modifierRatio(module,stats,"optMultiplier");const optMass=effectiveStat(module,"optMass",stats);const minMass=relatedStat(module,stats,"minMass",massRatio);const maxMass=relatedStat(module,stats,"maxMass",Math.max(1,massRatio));const optMultiplier=effectiveStat(module,"optMultiplier",stats);const minMultiplier=relatedStat(module,stats,"minMultiplier",strengthRatio);const maxMultiplier=relatedStat(module,stats,"maxMultiplier",strengthRatio);generator={...optMass===void 0?{}:{optMass:optMass},...minMass===void 0?{}:{minMass:minMass},...maxMass===void 0?{}:{maxMass:maxMass},...optMultiplier===void 0?{}:{optMultiplier:optMultiplier},...minMultiplier===void 0?{}:{minMultiplier:minMultiplier},...maxMultiplier===void 0?{}:{maxMultiplier:maxMultiplier},...resistancesOf(module,stats)}}else if(startsWithAny(module.Item,PREFIX.shieldBooster)){boosters.push({shieldBoost:effectiveStat(module,"shieldBoost",stats)??0,...resistancesOf(module,stats)})}else if(startsWithAny(module.Item,PREFIX.shieldReinforcement)){reinforcement+=effectiveStat(module,"shieldAddition",stats)??0}}return{hullMass:ship.hullMass,baseShieldStrength:ship.baseShieldStrength,generator:generator,boosters:boosters,reinforcement:reinforcement}}function shieldInputResultFor(ship,modules,getBudget,statsFor){const fitted=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!fitted.complete)return fitted;return completeResult(shieldInputFor(ship,modules,fitted.value.budget,statsFor))}function shieldCapacitorInputResultFor(ship,modules,getBudget,systemsPips,statsFor){const fitted=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!fitted.complete)return fitted;const budget=fitted.value.budget;const capacitor=systemsCapacitorResultFor(modules,budget,statsFor);if(!capacitor.complete)return capacitor;const shields=shieldMetrics(shieldInputFor(ship,modules,budget,statsFor));return completeResult({strength:shields.strength,resistances:shields.resistances,systemsCapacity:capacitor.value.systemsCapacity,systemsRecharge:capacitor.value.systemsRecharge,systemsPips:systemsPips})}function systemsCapacitorResultFor(modules,budget,statsFor){let distributor=null;for(const module of modules){const stats2=statsFor(module);if(isPowerDistributor(module,stats2)&&isEnabled(module)&&budget.available>0&&poweredStates(module,stats2,budget).retracted)distributor=module}if(!distributor)return completeResult({systemsCapacity:0,systemsRecharge:0});const stats=statsFor(distributor);const systemsCapacity=effectiveStat(distributor,"systemsCapacity",stats);const systemsRecharge=effectiveStat(distributor,"systemsRecharge",stats);return systemsCapacity===void 0||systemsRecharge===void 0?incompleteResult([metricIssue("powerDistributor","unresolved",distributor)]):completeResult({systemsCapacity:systemsCapacity,systemsRecharge:systemsRecharge})}function thrusterCurveFor(module,stats){const effective=effectiveModule(module,stats);const minMass=effective?.minMass;const optMass=effective?.optMass;const maxMass=effective?.maxMass;const minMultiplier=effective?.minMultiplier;const optMultiplier=effective?.optMultiplier;const maxMultiplier=effective?.maxMultiplier;if(minMass===void 0||optMass===void 0||maxMass===void 0||minMultiplier===void 0||optMultiplier===void 0||maxMultiplier===void 0){return null}return{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:minMultiplier,optMultiplier:optMultiplier,maxMultiplier:maxMultiplier,...effective?.optSpeedMultiplier===void 0?{}:{speedCurve:{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:effective.minSpeedMultiplier??minMultiplier,optMultiplier:effective.optSpeedMultiplier,maxMultiplier:effective.maxSpeedMultiplier??maxMultiplier}},...effective?.optRotationMultiplier===void 0?{}:{rotationCurve:{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:effective.minRotationMultiplier??minMultiplier,optMultiplier:effective.optRotationMultiplier,maxMultiplier:effective.maxRotationMultiplier??maxMultiplier}}}}function fittedThrusterParamsFor(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(isThruster(module,stats))return thrusterCurveFor(module,stats)}return null}function mobilityInputResultFor(ship,modules,getBudget,mass,statsFor){let thrusters=null;for(const module of modules){const stats=statsFor(module);if(!isThruster(module,stats))continue;const powered=poweredMetricBudgetFor("thrusters",module,stats,modules,getBudget,statsFor);if(!powered.complete)return powered;thrusters=thrusterCurveFor(module,stats);if(!thrusters)return incompleteResult([metricIssue("thrusters","unresolved",module)]);break}if(!thrusters)return incompleteResult([metricIssue("thrusters","missing")]);return completeResult({minimumSpeed:ship.minimumSpeed,maximumSpeed:ship.maximumSpeed,boost:ship.boost,minPitch:ship.minPitch,pitch:ship.pitch,minRoll:ship.minRoll,roll:ship.roll,minYaw:ship.minYaw,yaw:ship.yaw,mass:typeof mass==="function"?mass():mass,thrusters:thrusters})}function shieldRecoveryInputResultFor(ship,modules,getBudget,systemsPips,statsFor){const generator=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!generator.complete)return generator;const{module:generatorModule,budget:budget}=generator.value;const generatorStats=statsFor(generatorModule);const distributorDraw=effectiveStat(generatorModule,"distributorDraw",generatorStats);const regenRate=effectiveStat(generatorModule,"shieldRegenRate",generatorStats);const brokenRegenRate=effectiveStat(generatorModule,"shieldBrokenRegenRate",generatorStats);if(distributorDraw===void 0||regenRate===void 0||brokenRegenRate===void 0){return incompleteResult([metricIssue("shieldGenerator","unresolved",generatorModule)])}const capacitor=systemsCapacitorResultFor(modules,budget,statsFor);if(!capacitor.complete)return capacitor;const strength=shieldMetrics(shieldInputFor(ship,modules,budget,statsFor)).strength;return completeResult({strength:strength,regenRate:regenRate,brokenRegenRate:brokenRegenRate,distributorDraw:distributorDraw,systemsCapacity:capacitor.value.systemsCapacity,systemsRecharge:capacitor.value.systemsRecharge,systemsPips:systemsPips})}function weaponsCapacitorInputFor(modules,weaponsPips,budget,statsFor){let weaponsCapacity=0;let weaponsRecharge=0;let sustainedEnergyPerSecond=0;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!poweredStates(module,stats,budget).deployed)continue;if(isPowerDistributor(module,stats)){weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats)??0;weaponsRecharge=effectiveStat(module,"weaponsRecharge",stats)??0}const weapon=weaponStatsFor(module,stats);if(weapon){sustainedEnergyPerSecond+=weaponMetrics(weapon).sustainedEnergyPerSecond}}return{weaponsCapacity:weaponsCapacity,weaponsRecharge:weaponsRecharge,sustainedEnergyPerSecond:sustainedEnergyPerSecond,weaponsPips:weaponsPips}}function distributorInputResultFor(modules,pips,budget,statsFor){let disabled=null;for(const module of modules){const stats=statsFor(module);if(!isPowerDistributor(module,stats))continue;if(!isEnabled(module)){disabled??=module;continue}if(!poweredStates(module,stats,budget).retracted){return incompleteResult([metricIssue("powerDistributor","shed",module)])}const systemsCapacity=effectiveStat(module,"systemsCapacity",stats);const systemsRecharge=effectiveStat(module,"systemsRecharge",stats);const enginesCapacity=effectiveStat(module,"enginesCapacity",stats);const enginesRecharge=effectiveStat(module,"enginesRecharge",stats);const weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats);const weaponsRecharge=effectiveStat(module,"weaponsRecharge",stats);if(systemsCapacity===void 0||systemsRecharge===void 0||enginesCapacity===void 0||enginesRecharge===void 0||weaponsCapacity===void 0||weaponsRecharge===void 0){return incompleteResult([metricIssue("powerDistributor","unresolved",module)])}return completeResult({systemsCapacity:systemsCapacity,systemsRecharge:systemsRecharge,enginesCapacity:enginesCapacity,enginesRecharge:enginesRecharge,weaponsCapacity:weaponsCapacity,weaponsRecharge:weaponsRecharge,...pips})}return incompleteResult([disabled===null?metricIssue("powerDistributor","missing"):metricIssue("powerDistributor","disabled",disabled)])}function heatInputResultFor(ship,modules,budget,statsFor){let plant=null;let heatEfficiency;let thrusterHeatRate=0;let deployedThrusterHeatRate=0;let fsdHeatRate=0;let weaponsCapacity=0;const weapons=[];for(const module of modules){const stats=statsFor(module);if(isPowerPlant(module,stats)){if(!isEnabled(module)){return incompleteResult([metricIssue("powerCapacity","disabled",module)])}plant=module;heatEfficiency=effectiveStat(module,"heatEfficiency",stats);continue}if(!isEnabled(module))continue;const running=poweredStates(module,stats,budget);if(isThruster(module,stats)){const heat=effectiveStat(module,"engineHeatRate",stats)??0;if(running.retracted)thrusterHeatRate+=heat;if(running.deployed)deployedThrusterHeatRate+=heat}else if(isFrameShiftDrive(module,stats)){if(running.retracted)fsdHeatRate+=effectiveStat(module,"fsdHeatRate",stats)??0}else if(isPowerDistributor(module,stats)){if(running.deployed){weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats)??0}}const weapon=weaponStatsFor(module,stats);if(!running.deployed)continue;if(!weapon)continue;weapons.push({heatPerSecond:weaponMetrics(weapon).sustainedHeatPerSecond,distributorDraw:weapon.distributorDraw??0})}if(heatEfficiency===void 0){return incompleteResult([plant===null?metricIssue("powerCapacity","missing"):metricIssue("heatEfficiency","unresolved",plant)])}return completeResult({heatCapacity:ship.heatCapacity,heatDissipation:ship.heatDissipation,heatEfficiency:heatEfficiency,retractedPowerDraw:poweredDraw(budget,"retracted"),deployedPowerDraw:poweredDraw(budget,"deployed"),thrusterHeatRate:thrusterHeatRate,deployedThrusterHeatRate:deployedThrusterHeatRate,fsdHeatRate:fsdHeatRate,weaponsCapacity:weaponsCapacity,weapons:weapons})}function poweredDraw(budget,state){const powered=state==="retracted"?"poweredRetracted":"poweredDeployed";return budget.bands.reduce((total,band)=>band[powered]?total+band[state]:total,0)}function poweredStates(module,stats,budget){const draw=effectiveStat(module,"powerDraw",stats);if(draw===void 0||draw===0)return{retracted:true,deployed:true};const band=budget.bands[Math.min(budget.bands.length,Math.max(1,priorityOf(module)))-1];if(!band)return{retracted:true,deployed:true};return{retracted:band.poweredRetracted,deployed:band.poweredDeployed}}function cellBankInputsFor(modules,budget,statsFor){const banks=[];for(const module of modules){if(!startsWithAny(module.Item,PREFIX.shieldCellBank))continue;const stats=statsFor(module);const effective=effectiveModule(module,stats);const ammunition=effective?ammunitionCapacity(effective):null;banks.push({slot:module.Slot,symbol:module.Item,reinforcementRate:effective?.shieldBankReinforcement??0,cells:ammunition?.total??0,spinUp:effective?.shieldBankSpinUp??0,duration:effective?.shieldBankDuration??0,heat:effective?.shieldBankHeat??0,powered:budget.available>0&&isEnabled(module)&&poweredStates(module,stats,budget).deployed})}return banks}function stockBulkhead(ship){const variants=getBulkheadsForShip(ship.name,CORE_MODULES);return variants.find(v=>v.symbol.toLowerCase().endsWith("_default"))??variants.find(v=>v.mass===0)??variants[0]??null}function armourInputFor(ship,modules,statsFor){const reinforcements=[];const moduleReinforcements=[];let bulkhead=null;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(module.Slot.toLowerCase()==="armour"){bulkhead={hullBoost:effectiveStat(module,"hullBoost",stats)??0,...resistancesOf(module,stats)}}else if(startsWithAny(module.Item,PREFIX.hullReinforcement)){const boost=getLoadoutModifier(module,"DefenceModifierHealthMultiplier");reinforcements.push({hullReinforcement:effectiveStat(module,"hullReinforcement",stats)??0,hullBoost:boost===null?0:boost/scaleForLabel("DefenceModifierHealthMultiplier"),...resistancesOf(module,stats)})}else if(startsWithAny(module.Item,PREFIX.moduleReinforcement)){moduleReinforcements.push({moduleProtection:effectiveStat(module,"moduleProtection",stats)??0,integrity:effectiveStat(module,"integrity",stats)??0})}}if(!bulkhead){const stock=stockBulkhead(ship);bulkhead=stock?{hullBoost:stock.hullBoost??0,...mapResistanceFields(field=>stock[field])}:null}return{baseArmour:ship.baseArmour,bulkhead:bulkhead,reinforcements:reinforcements,moduleReinforcements:moduleReinforcements}}var WEAPON_FIELDS=["damage","roundsPerShot","rateOfFire","burstInterval","burstRounds","burstRateOfFire","chargeTime","clipSize","ammoMaximum","reloadTime","distributorDraw","thermalLoad","powerDraw","maximumRange","falloffRange","armourPiercing"];function weaponStatsFor(module,stats){if(!stats||stats.category!=="hardpoint")return null;const weapon={};for(const field of WEAPON_FIELDS){const value=effectiveStat(module,field,stats);if(value!==void 0)weapon[field]=value}normalizeEffectiveWeapon(module,weapon);const damageDistribution=effectiveDamageDistribution(module,stats);if(damageDistribution)weapon.damageDistribution=damageDistribution;if(stats.damageComponents&&!convertsDamage(module)){weapon.damageComponents=scaleDamageComponents(stats.damageComponents,stats.damage,typeof weapon.damage==="number"?weapon.damage:void 0)}if(stats.projectileRange)weapon.projectileRange={...stats.projectileRange};return weapon}function burstAdjustedRateOfFire(module,weapon){if(getLoadoutModifier(module,"RateOfFire")!==null)return void 0;const touched=["BurstSize","BurstRateOfFire","BurstInterval"].some(label=>getLoadoutModifier(module,label)!==null);if(!touched)return void 0;return combinedRateOfFire(weapon)}function normalizeEffectiveWeapon(module,weapon){const rate=burstAdjustedRateOfFire(module,weapon);if(rate!==void 0)weapon.rateOfFire=rate;const statedDamagePerSecond=getLoadoutModifier(module,"DamagePerSecond");const firingFactor=Number(weapon.roundsPerShot??1)*Number(weapon.rateOfFire??1);if(statedDamagePerSecond!==null&&firingFactor>0){weapon.damage=statedDamagePerSecond/firingFactor}const{maximumRange:maximumRange,falloffRange:falloffRange}=weapon;if(maximumRange!==void 0&&falloffRange!==void 0&&falloffRange>maximumRange){weapon.falloffRange=maximumRange}}var INTERNALS=/* @__PURE__ */new WeakMap;function publishLoadoutInternals(build,internals){INTERNALS.set(build,internals)}function loadoutInternals(build,label){const internals=typeof build==="object"&&build!==null?INTERNALS.get(build):void 0;if(internals===void 0){throw new TypeError(`${label} must be a ShipLoadout, received ${describeValue(build)}`)}return internals}export{armourInputFor,cellBankInputsFor,completeResult,distributorInputResultFor,effectiveModule,fittedThrusterParamsFor,heatInputResultFor,incompleteResult,loadoutInternals,mobilityInputResultFor,moduleFitError,moduleFitProblem,normalizeLoadoutEvent,powerAvailable,powerConsumerFor,preEngineeredVariantFor,publishLoadoutInternals,shieldCapacitorInputResultFor,shieldInputResultFor,shieldRecoveryInputResultFor,weaponStatsFor,weaponsCapacitorInputFor};//# sourceMappingURL=chunk-SS6XK336.js.map
1
+ import{shieldMetrics}from"./chunk-5VWACBTN.js";import{getShipBySymbol,getShipByName,getShipSlots}from"./chunk-6UNAD74Z.js";import{getLoadoutModifier}from"./chunk-T4MKUKYS.js";import{sourcePurchaseFromLoadout}from"./chunk-NIURLW2F.js";import{identifyPreEngineeredVariant,unrollableFixedArticle,cloneLoadoutModule,isNonOutfittingSlot,isBuiltInHullModule,matchingKeyIn,ownKeyIn,getPreEngineeredStats,getPreEngineeredModifiers,cloneModuleStats,isFinalGuardianWeaponEngineering,scaleDamageComponents}from"./chunk-SC6Z2TV7.js";import{weaponMetrics,combinedRateOfFire}from"./chunk-37JIMWLK.js";import{builtInModuleBySymbol,getBulkheadsForShip}from"./chunk-3LZXB2MC.js";import{getPreEngineeredVariants}from"./chunk-KPJ77VPS.js";import{CORE_MODULES}from"./chunk-FA5JVXVG.js";import{getExperimentalEffect}from"./chunk-77I24V6B.js";import{getDefaultLoadout}from"./chunk-GRIK3EDH.js";import{fieldForLabel,scaleForLabel,labelsForField,capabilityValueForLabel,damageTypeForLabel}from"./chunk-CJQ37JII.js";import{ammunitionCapacity}from"./chunk-AA3K5XUE.js";import{parseSlotName,SLOT_RESTRICTION_LABELS,enumerateSlots}from"./chunk-RAO35XDF.js";import{normalizeKey}from"./chunk-BKWLI44T.js";import{truncate,requireString,describeValue,requireStringIfPresent}from"./chunk-PKWVG2JY.js";import{deepFreeze}from"./chunk-DURKO7JU.js";var MILITARY_PREFIXES=["int_hullreinforcement","int_metaalloyhullreinforcement","int_modulereinforcement","int_shieldcellbank","int_guardianhullreinforcement","int_guardianmodulereinforcement","int_guardianshieldreinforcement"];var MINING_PREFIXES=["hpt_mininglaser","hpt_mining_abrblstr","hpt_mining_seismchrgwarhd","hpt_mining_subsurfdispmisle","hpt_human_extraction","hpt_miningtoolv2"];var CARGO_PREFIXES=["int_cargorack","int_largecargorack","int_corrosionproofcargorack","int_fueltank"];var RESTRICTED_SLOT_PREFIXES={mining:MINING_PREFIXES,military:MILITARY_PREFIXES,cargo:CARGO_PREFIXES,limpetController:["int_dronecontrol","int_multidronecontrol"],vesselHangar:["int_fighterbay"],passenger:["int_passengercabin","int_mkii_passengercabin"],planetaryApproachSuite:["int_planetapproachsuite"]};var problem=(constraint,message,params)=>({constraint:constraint,message:message,...params===void 0?{}:{params:params}});function restrictionProblem(slot,symbol){const restriction=slot.restriction;if(!restriction)return null;if(RESTRICTED_SLOT_PREFIXES[restriction].some(prefix=>symbol.startsWith(prefix))){return null}return problem("restrictedMount",`slot only takes ${SLOT_RESTRICTION_LABELS[restriction]}`,{restriction:restriction})}function moduleSlotProblem(slot,module){const required=module.restrictedToSlot;if(!required||slot.restriction===required)return null;return problem("restrictedMount",`module only fits a mount that takes ${SLOT_RESTRICTION_LABELS[required]}`,{restriction:required})}function moduleFitProblem(shipSymbol,slot,module){if(slot.kind==="cargoHatch"){return problem("immutableSlot","the cargoHatch slot cannot be changed")}if(slot.kind==="armour"){const hull=getShipBySymbol(shipSymbol);if(module.slot!=="armour"||module.ship===void 0){return problem("armourRequired","not a ship armour module")}if(!hull||module.ship.toLowerCase()!==hull.name.toLowerCase()){const armourHull=getShipByName(module.ship);return problem("wrongHullArmour",`armour belongs to ${truncate(module.ship)}, not ${truncate(hull?.name??shipSymbol)}`,{armourShipName:module.ship,...armourHull===null?{}:{armourShipSymbol:armourHull.symbol},shipSymbol:shipSymbol,...hull===null?{}:{shipName:hull.name}})}return null}const restricted=module.restrictedToShips;if(restricted&&!restricted.some(symbol2=>symbol2.toLowerCase()===shipSymbol.toLowerCase())){const allowedShipNames=restricted.map(symbol2=>{const hull=getShipBySymbol(symbol2);return hull?.name??symbol2});const labels=restricted.map((symbol2,index)=>{const name=allowedShipNames[index];return name===symbol2?symbol2:`${name} (${symbol2})`});return problem("restrictedHull",`module is restricted to ${truncate(labels.join(", "))}`,{allowedShipNames:allowedShipNames,allowedShipSymbols:[...restricted],shipSymbol:shipSymbol})}const wrongMount=moduleSlotProblem(slot,module);if(wrongMount)return wrongMount;const symbol=module.symbol.toLowerCase();const moduleSlot=module.slot;switch(slot.kind){case"core":if(moduleSlot!==slot.core){return problem("wrongCoreType",`not a ${slot.core} module`,{requiredCore:slot.core,moduleSlot:moduleSlot??"none"})}break;case"hardpoint":{if(module.category!=="hardpoint"){return problem("hardpointRequired","not a hardpoint weapon")}const restricted2=restrictionProblem(slot,symbol);if(restricted2)return restricted2;break}case"utility":if(module.category!=="utility"){return problem("utilityRequired","not a utility module")}return null;case"optional":{const isFuelTank=moduleSlot==="fuelTank";if(module.category!=="internal"&&!isFuelTank){return problem("optionalInternalRequired","not an optional-internal module")}if(moduleSlot&&!isFuelTank){return problem("coreModuleInOptionalSlot","a core module only fits its core slot")}const restricted2=restrictionProblem(slot,symbol);if(restricted2)return restricted2;break}}return module.class>slot.size?problem("oversized",`module size ${truncate(module.class)} exceeds slot size ${slot.size}`,{moduleClass:module.class,slotSize:slot.size}):null}function moduleFitError(shipSymbol,slot,module){return moduleFitProblem(shipSymbol,slot,module)?.message??null}function preEngineeredVariantFor(module){return identifyPreEngineeredVariant(module)??(module.Engineering?unrollableFixedArticle(module.Item,module.Engineering):null)}function captureLoadoutEvent(event){const modules=event.Modules;const shipName=event.ShipName;const shipIdent=event.ShipIdent;const hullValue=event.HullValue;const modulesValue=event.ModulesValue;const rebuy=event.Rebuy;const unladenMass=event.UnladenMass;const cargoCapacity=event.CargoCapacity;const fuelCapacity=event.FuelCapacity;return{Ship:event.Ship,Modules:Array.isArray(modules)?captureEach(modules,captureModule):modules,...shipName===void 0?{}:{ShipName:shipName},...shipIdent===void 0?{}:{ShipIdent:shipIdent},...hullValue===void 0?{}:{HullValue:hullValue},...modulesValue===void 0?{}:{ModulesValue:modulesValue},...rebuy===void 0?{}:{Rebuy:rebuy},...unladenMass===void 0?{}:{UnladenMass:unladenMass},...cargoCapacity===void 0?{}:{CargoCapacity:cargoCapacity},...fuelCapacity===void 0?{}:{FuelCapacity:{...fuelCapacity}}}}function captureEach(values,capture){const captured=[];const{length:length}=values;for(let index=0;index<length;index++)captured.push(capture(values[index]));return captured}function captureModule(module){if(module===null||typeof module!=="object")return module;const on=module.On;const priority=module.Priority;const health=module.Health;const value=module.Value;const engineering=module.Engineering;return{Slot:module.Slot,Item:module.Item,...on===void 0?{}:{On:on},...priority===void 0?{}:{Priority:priority},...health===void 0?{}:{Health:health},...value===void 0?{}:{Value:value},...engineering===void 0?{}:{Engineering:captureEngineering(engineering)}}}function captureEngineering(engineering){if(engineering===null||typeof engineering!=="object")return engineering;const experimental=engineering.ExperimentalEffect;const experimentalLocalised=engineering.ExperimentalEffect_Localised;const modifiers=engineering.Modifiers;return{BlueprintName:engineering.BlueprintName,Level:engineering.Level,Quality:engineering.Quality,...experimental===void 0?{}:{ExperimentalEffect:experimental},...experimentalLocalised===void 0?{}:{ExperimentalEffect_Localised:experimentalLocalised},...modifiers===void 0?{}:{Modifiers:Array.isArray(modifiers)?captureEach(modifiers,modifier=>modifier!==null&&typeof modifier==="object"?{...modifier}:modifier):modifiers}}}function hullLayout(shipSymbol){const slots=getShipSlots(shipSymbol);return slots?enumerateSlots(slots):[]}function fixedMountRejects(shipSymbol,layout,slot,stats){const mount=layout.find(candidate=>candidate.key.toLowerCase()===slot.toLowerCase());return mount!==void 0&&moduleFitProblem(shipSymbol,mount,stats)!==null}function normalizeLoadoutEvent(rawEvent){const event=captureLoadoutEvent(rawEvent);requireString(event.Ship,"ShipLoadout.fromLoadout: event.Ship");if(!Array.isArray(event.Modules)){throw new TypeError(`ShipLoadout.fromLoadout: event.Modules must be an array, received ${describeValue(event.Modules)}`)}const modules=/* @__PURE__ */new Map;const slots=/* @__PURE__ */new Set;for(const module of event.Modules){if(module===null||typeof module!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: event.Modules[] must hold module objects, received ${describeValue(module)}`)}requireString(module.Slot,"ShipLoadout.fromLoadout: module.Slot");requireString(module.Item,"ShipLoadout.fromLoadout: module.Item");if(module.Engineering!==void 0){if(module.Engineering===null||typeof module.Engineering!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering must be an object, received ${describeValue(module.Engineering)}`)}requireStringIfPresent(module.Engineering.BlueprintName,"ShipLoadout.fromLoadout: module.Engineering.BlueprintName");requireStringIfPresent(module.Engineering.ExperimentalEffect,"ShipLoadout.fromLoadout: module.Engineering.ExperimentalEffect");if(module.Engineering.Modifiers!==void 0&&!Array.isArray(module.Engineering.Modifiers)){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering.Modifiers must be an array, received ${describeValue(module.Engineering.Modifiers)}`)}for(const[index,modifier]of(module.Engineering.Modifiers??[]).entries()){if(modifier===null||typeof modifier!=="object"){throw new TypeError(`ShipLoadout.fromLoadout: module.Engineering.Modifiers[${index}] must be an object, received ${describeValue(modifier)}`)}requireString(modifier.Label,`ShipLoadout.fromLoadout: module.Engineering.Modifiers[${index}].Label`)}}const normalizedSlot=module.Slot.toLowerCase();if(slots.has(normalizedSlot)){throw new TypeError(`ShipLoadout.fromLoadout: duplicate slot "${truncate(module.Slot)}"`)}slots.add(normalizedSlot);modules.set(module.Slot,cloneLoadoutModule(module))}const top={};if(event.ShipName!==void 0)top.ShipName=event.ShipName;if(event.ShipIdent!==void 0)top.ShipIdent=event.ShipIdent;if(event.HullValue!==void 0)top.HullValue=event.HullValue;if(event.ModulesValue!==void 0)top.ModulesValue=event.ModulesValue;if(event.Rebuy!==void 0)top.Rebuy=event.Rebuy;if(event.UnladenMass!==void 0)top.UnladenMass=event.UnladenMass;if(event.CargoCapacity!==void 0)top.CargoCapacity=event.CargoCapacity;if(event.FuelCapacity!==void 0)top.FuelCapacity={...event.FuelCapacity};let invalidatesAggregates=false;const outcomes=[];const defaults=getDefaultLoadout(event.Ship)?.modules??[];let layout;for(const[slot,module]of modules){if(isNonOutfittingSlot(slot)||isBuiltInHullModule(module))continue;const stats=builtInModuleBySymbol(module.Item,"ShipLoadout.fromLoadout: module.Item");const slotKind=parseSlotName(slot)?.kind;const fallback=slotKind==="core"||slotKind==="armour"||slotKind==="cargoHatch"?defaults.find(candidate=>candidate.slot.toLowerCase()===slot.toLowerCase()):void 0;const rejected=fallback!==void 0&&(stats===null||slotKind==="cargoHatch"||fixedMountRejects(event.Ship,layout??=hullLayout(event.Ship),slot,stats));if(stats!==null&&!rejected)continue;if(fallback){modules.set(slot,{Slot:slot,Item:fallback.symbol,...module.On===void 0?{}:{On:module.On},...module.Priority===void 0?{}:{Priority:module.Priority},...module.Health===void 0?{}:{Health:module.Health}});outcomes.push({action:"defaulted",slot:slot,sourceSymbol:module.Item,replacementSymbol:fallback.symbol})}else{modules.delete(slot);outcomes.push({action:"emptied",slot:slot,sourceSymbol:module.Item})}invalidatesAggregates=true}for(const fallback of defaults){const slotKind=parseSlotName(fallback.slot)?.kind;if(slotKind!=="core"&&slotKind!=="armour"&&slotKind!=="cargoHatch"||matchingKeyIn(modules,fallback.slot)!==null){continue}const slot=ownKeyIn(modules,fallback.slot);modules.set(slot,{Slot:slot,Item:fallback.symbol});outcomes.push({action:"defaulted",slot:slot,sourceSymbol:null,replacementSymbol:fallback.symbol});if(slotKind==="core")invalidatesAggregates=true}if(invalidatesAggregates){delete top.ModulesValue;delete top.Rebuy;delete top.UnladenMass;delete top.CargoCapacity;delete top.FuelCapacity}const moduleStats=/* @__PURE__ */new Map;const primitiveModifiers=/* @__PURE__ */new Map;for(const module of modules.values()){const engineering=module.Engineering;const variant=preEngineeredVariantFor(module);const catalogueVariantStats=variant?getPreEngineeredStats(variant):null;let variantStats=catalogueVariantStats;const retainsBakedExperimental=variant?.experimentalEffectSymbol!==void 0&&typeof engineering?.ExperimentalEffect==="string"&&variant.experimentalEffectSymbol.trim().toLowerCase()===engineering.ExperimentalEffect.trim().toLowerCase();if(variant&&catalogueVariantStats&&!catalogueVariantStats.engineeringLocked&&!retainsBakedExperimental){const{experimentalEffectSymbol:originalExperimental,...withoutExperimental}=variant;const currentExperimental=engineering?.ExperimentalEffect;const currentVariant=typeof currentExperimental==="string"?{...withoutExperimental,experimentalEffectSymbol:currentExperimental}:withoutExperimental;variantStats=getPreEngineeredStats(withoutExperimental);primitiveModifiers.set(module.Slot,[...engineering?.Modifiers??[],...getPreEngineeredModifiers(currentVariant)])}if(variantStats)moduleStats.set(module.Slot,cloneModuleStats(variantStats));const guardianFinal=typeof engineering?.BlueprintName==="string"&&isFinalGuardianWeaponEngineering(module.Item,engineering.BlueprintName);if(variantStats?.engineeringLocked||typeof engineering?.BlueprintName!=="string"||!guardianFinal){continue}const normalizedBlueprint=normalizeKey(engineering.BlueprintName,"ShipLoadout.fromLoadout: module.Engineering.BlueprintName");const normalizedExperimental=normalizeKey(engineering.ExperimentalEffect,"ShipLoadout.fromLoadout: module.Engineering.ExperimentalEffect");const variants=getPreEngineeredVariants(module.Item);const exact=variants.find(candidate=>candidate.engineeringLocked===true&&candidate.blueprintSymbol.toLowerCase()===normalizedBlueprint&&candidate.grade===engineering.Level&&candidate.experimentalEffectSymbol?.toLowerCase()===normalizedExperimental);const guardianBase=variants.find(candidate=>candidate.engineeringLocked===true&&candidate.blueprintSymbol.toLowerCase()===normalizedBlueprint&&candidate.grade===engineering.Level&&candidate.experimentalEffectSymbol===void 0);const stats=exact?getPreEngineeredStats(exact):guardianBase&&engineering.ExperimentalEffect!==void 0?getPreEngineeredStats({...guardianBase,experimentalEffectSymbol:engineering.ExperimentalEffect}):builtInModuleBySymbol(module.Item,"ShipLoadout.fromLoadout: module.Item");if(stats){moduleStats.set(module.Slot,cloneModuleStats({...stats,engineeringLocked:true}))}}return{shipSymbol:event.Ship,modules:modules,moduleStats:moduleStats,primitiveModifiers:primitiveModifiers,top:top,sourcePurchase:sourcePurchaseFromLoadout(event),outcomes:deepFreeze(outcomes)}}var NO_ISSUES=Object.freeze([]);function completeResult(value){return Object.freeze({value:value,complete:true,issues:NO_ISSUES})}function incompleteResult(issues){return Object.freeze({value:null,complete:false,issues:Object.freeze(issues.map(issue=>Object.freeze({...issue,...issue.params?{params:Object.freeze({...issue.params})}:{}})))})}var PREFIX={powerPlant:["int_powerplant","int_guardianpowerplant"],thrusters:["int_engine","int_mkiiagileboost_engine"],frameShiftDrive:["int_hyperdrive"],powerDistributor:["int_powerdistributor","int_guardianpowerdistributor"],shieldGenerator:["int_shieldgenerator"],shieldCellBank:["int_shieldcellbank"],shieldBooster:["hpt_shieldbooster"],shieldReinforcement:["int_guardianshieldreinforcement"],hullReinforcement:["int_hullreinforcement","int_guardianhullreinforcement","int_metaalloyhullreinforcement"],moduleReinforcement:["int_modulereinforcement","int_guardianmodulereinforcement"]};var startsWithAny=(symbol,prefixes)=>prefixes.some(prefix=>symbol.toLowerCase().startsWith(prefix));function isPowerDistributor(module,stats){return stats?.slot?stats.slot==="powerDistributor":startsWithAny(module.Item,PREFIX.powerDistributor)}function isPowerPlant(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="powerPlant")return true;return stats?.slot?stats.slot==="powerPlant":startsWithAny(module.Item,PREFIX.powerPlant)}function isThruster(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="thrusters")return true;return stats?.slot?stats.slot==="thrusters":startsWithAny(module.Item,PREFIX.thrusters)}function isFrameShiftDrive(module,stats){const parsed=parseSlotName(module.Slot);if(parsed?.kind==="core"&&parsed.core==="frameShiftDrive")return true;return stats?.slot?stats.slot==="frameShiftDrive":startsWithAny(module.Item,PREFIX.frameShiftDrive)}function isEnabled(module){return module.On!==false}function priorityOf(module){return(module.Priority??0)+1}function effectiveStat(module,field,stats){const stated=statedModifier(module,field);if(stated!==void 0)return stated;const base=stats?.[field];return typeof base==="number"?base:void 0}function statedModifier(module,field){for(const label of labelsForField(field)){if(capabilityValueForLabel(label)!==null)continue;const modified=getLoadoutModifier(module,label);if(modified!==null)return modified/scaleForLabel(label)}return void 0}function effectiveCapability(module,field,stats){for(const label of labelsForField(field)){if(capabilityValueForLabel(label)===null)continue;if(module.Engineering?.Modifiers?.some(modifier=>modifier.Label.toLowerCase()===label.toLowerCase())){return true}}const base=stats[field];return typeof base==="boolean"?base:void 0}function effectiveDamageDistribution(module,stats){const fromEffect=module.Engineering?.ExperimentalEffect?getExperimentalEffect(module.Engineering.ExperimentalEffect)?.damageDistribution:void 0;const distribution={...fromEffect??stats.damageDistribution};let resolved=fromEffect!==void 0||stats.damageDistribution!==void 0;const seen=/* @__PURE__ */new Set;for(const modifier of module.Engineering?.Modifiers??[]){const type=damageTypeForLabel(modifier.Label);if(type===null||seen.has(type))continue;seen.add(type);if(modifier.Value===void 0)continue;distribution[type]=modifier.Value/scaleForLabel(modifier.Label);resolved=true}return resolved?distribution:void 0}function convertsDamage(module){if(module.Engineering?.ExperimentalEffect&&getExperimentalEffect(module.Engineering.ExperimentalEffect)?.damageDistribution){return true}return(module.Engineering?.Modifiers??[]).some(modifier=>damageTypeForLabel(modifier.Label)!==null)}function modifierRatio(module,stats,field){const base=stats?.[field];if(typeof base!=="number"||base===0)return 1;const effective=effectiveStat(module,field,stats);return effective===void 0?1:effective/base}function relatedStat(module,stats,field,ratio){const stated=statedModifier(module,field);if(stated!==void 0)return stated;const base=stats?.[field];return typeof base==="number"?base*ratio:void 0}function effectiveModule(module,stats){if(!stats||!module.Engineering)return stats;const merged={...stats};const fields=new Set(Object.keys(stats));for(const modifier of module.Engineering.Modifiers??[]){const field=fieldForLabel(modifier.Label,stats);if(field)fields.add(field)}for(const key of fields){const capability=effectiveCapability(module,key,stats);if(capability!==void 0){merged[key]=capability;continue}const value=effectiveStat(module,key,stats);if(value!==void 0)merged[key]=value}if(stats.engineeringGroup==="thrusters"){const massRatio=modifierRatio(module,stats,"optMass");const minMass=relatedStat(module,stats,"minMass",massRatio);const maxMass=relatedStat(module,stats,"maxMass",massRatio);if(minMass!==void 0)merged.minMass=minMass;if(maxMass!==void 0)merged.maxMass=maxMass}if(stats.engineeringGroup==="thrusters"||stats.engineeringGroup==="shieldGenerators"){const performanceRatio=modifierRatio(module,stats,"optMultiplier");const minMultiplier=relatedStat(module,stats,"minMultiplier",performanceRatio);const maxMultiplier=relatedStat(module,stats,"maxMultiplier",performanceRatio);if(minMultiplier!==void 0)merged.minMultiplier=minMultiplier;if(maxMultiplier!==void 0)merged.maxMultiplier=maxMultiplier;if(stats.engineeringGroup==="thrusters"){for(const field of["minSpeedMultiplier","optSpeedMultiplier","maxSpeedMultiplier","minRotationMultiplier","optRotationMultiplier","maxRotationMultiplier"]){const value=stats[field];if(value!==void 0)merged[field]=value*performanceRatio}}}const damageDistribution=effectiveDamageDistribution(module,stats);if(damageDistribution)merged.damageDistribution=damageDistribution;if(stats.category==="hardpoint")normalizeEffectiveWeapon(module,merged);if(convertsDamage(module)){delete merged.damageComponents}else if(stats.damageComponents){merged.damageComponents=scaleDamageComponents(stats.damageComponents,stats.damage,typeof merged.damage==="number"?merged.damage:void 0)}return merged}function powerConsumerFor(module,stats){const draw=effectiveStat(module,"powerDraw",stats);if(draw===void 0||draw===0)return null;const mounted=stats?.category==="hardpoint"||stats?.category==="utility";return{draw:draw,priority:priorityOf(module),enabled:isEnabled(module),deployedOnly:mounted&&stats?.alwaysPowered!==true,label:module.Slot,symbol:module.Item}}function powerAvailable(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(!isPowerPlant(module,stats))continue;if(!isEnabled(module))return 0;return effectiveStat(module,"powerCapacity",stats)??0}return 0}var DEFAULT_SLOT={powerCapacity:"PowerPlant",heatEfficiency:"PowerPlant",thrusters:"MainEngines",powerDistributor:"PowerDistributor"};var UNRESOLVED_FACT={thrusters:"thruster stats",shieldGenerator:"shield-generator stats",powerCapacity:"power capacity",heatEfficiency:"heat efficiency",powerDistributor:"power-distributor stats"};var NOTHING_FITTED={powerCapacity:"PowerPlant: no power plant is fitted",heatEfficiency:"PowerPlant: no power plant is fitted",thrusters:"MainEngines: no thrusters are fitted",powerDistributor:"PowerDistributor: no power distributor is fitted"};function metricIssue(field,reason,module){const defaultSlot=DEFAULT_SLOT[field];const slot=module?.Slot??defaultSlot;const symbol=module?.Item;const params={field:field,reason:reason,...slot===void 0?{}:{slot:slot},...symbol===void 0?{}:{symbol:symbol}};let message;if(reason==="missing"){message=NOTHING_FITTED[field]??"no shield generator is fitted"}else if(reason==="unresolved"){const unavailable=UNRESOLVED_FACT[field]??field;message=`${truncate(slot??field)}: ${unavailable} unavailable for ${truncate(symbol??field)}`}else if(reason==="disabled"){message=`${truncate(slot??field)}: ${truncate(symbol??field)} is switched off`}else if(reason==="invalid"){message=`${truncate(slot??field)}: ${truncate(symbol??field)} has invalid ${field}`}else{message=`${truncate(slot??field)}: ${truncate(symbol??field)} is not powered with hardpoints retracted`}return{field:field,reason:reason,...slot===void 0?{}:{slot:slot},...symbol===void 0?{}:{symbol:symbol},message:message,params:params}}function powerPlantIssueFor(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(!isPowerPlant(module,stats))continue;if(!isEnabled(module))return metricIssue("powerCapacity","disabled",module);const capacity=effectiveStat(module,"powerCapacity",stats);if(capacity===void 0)return metricIssue("powerCapacity","unresolved",module);return!Number.isFinite(capacity)||capacity<=0?metricIssue("powerCapacity","invalid",module):null}return metricIssue("powerCapacity","missing")}function powerDrawIssueFor(modules,statsFor){for(const module of modules){const consumer=powerConsumerFor(module,statsFor(module));if(consumer&&(!Number.isFinite(consumer.draw)||consumer.draw<0)){return metricIssue("powerDraw","invalid",module)}}return null}function poweredMetricBudgetFor(field,module,stats,modules,getBudget,statsFor){if(!isEnabled(module))return incompleteResult([metricIssue(field,"disabled",module)]);const plantIssue=powerPlantIssueFor(modules,statsFor);if(plantIssue)return incompleteResult([plantIssue]);const drawIssue=powerDrawIssueFor(modules,statsFor);if(drawIssue)return incompleteResult([drawIssue]);const budget=getBudget();return budget.available>0&&poweredStates(module,stats,budget).retracted?completeResult(budget):incompleteResult([metricIssue(field,"shed",module)])}function poweredShieldGeneratorResultFor(modules,getBudget,statsFor){for(const module of modules){if(!startsWithAny(module.Item,PREFIX.shieldGenerator))continue;const stats=statsFor(module);const powered=poweredMetricBudgetFor("shieldGenerator",module,stats,modules,getBudget,statsFor);if(!powered.complete)return powered;return stats===null?incompleteResult([metricIssue("shieldGenerator","unresolved",module)]):completeResult({module:module,budget:powered.value})}return incompleteResult([metricIssue("shieldGenerator","missing")])}function mapResistanceFields(read){return{kineticResistance:read("kineticResistance")??0,thermalResistance:read("thermalResistance")??0,explosiveResistance:read("explosiveResistance")??0,causticResistance:read("causticResistance")??0}}function resistancesOf(module,stats){return mapResistanceFields(field=>effectiveStat(module,field,stats))}function shieldInputFor(ship,modules,budget,statsFor){let generator=null;const boosters=[];let reinforcement=0;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!(budget.available>0&&poweredStates(module,stats,budget).retracted))continue;if(!generator&&startsWithAny(module.Item,PREFIX.shieldGenerator)){const massRatio=modifierRatio(module,stats,"optMass");const strengthRatio=modifierRatio(module,stats,"optMultiplier");const optMass=effectiveStat(module,"optMass",stats);const minMass=relatedStat(module,stats,"minMass",massRatio);const maxMass=relatedStat(module,stats,"maxMass",Math.max(1,massRatio));const optMultiplier=effectiveStat(module,"optMultiplier",stats);const minMultiplier=relatedStat(module,stats,"minMultiplier",strengthRatio);const maxMultiplier=relatedStat(module,stats,"maxMultiplier",strengthRatio);generator={...optMass===void 0?{}:{optMass:optMass},...minMass===void 0?{}:{minMass:minMass},...maxMass===void 0?{}:{maxMass:maxMass},...optMultiplier===void 0?{}:{optMultiplier:optMultiplier},...minMultiplier===void 0?{}:{minMultiplier:minMultiplier},...maxMultiplier===void 0?{}:{maxMultiplier:maxMultiplier},...resistancesOf(module,stats)}}else if(startsWithAny(module.Item,PREFIX.shieldBooster)){boosters.push({shieldBoost:effectiveStat(module,"shieldBoost",stats)??0,...resistancesOf(module,stats)})}else if(startsWithAny(module.Item,PREFIX.shieldReinforcement)){reinforcement+=effectiveStat(module,"shieldAddition",stats)??0}}return{hullMass:ship.hullMass,baseShieldStrength:ship.baseShieldStrength,generator:generator,boosters:boosters,reinforcement:reinforcement}}function shieldInputResultFor(ship,modules,getBudget,statsFor){const fitted=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!fitted.complete)return fitted;return completeResult(shieldInputFor(ship,modules,fitted.value.budget,statsFor))}function shieldCapacitorInputResultFor(ship,modules,getBudget,systemsPips,statsFor){const fitted=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!fitted.complete)return fitted;const budget=fitted.value.budget;const capacitor=systemsCapacitorResultFor(modules,budget,statsFor);if(!capacitor.complete)return capacitor;const shields=shieldMetrics(shieldInputFor(ship,modules,budget,statsFor));return completeResult({strength:shields.strength,resistances:shields.resistances,systemsCapacity:capacitor.value.systemsCapacity,systemsRecharge:capacitor.value.systemsRecharge,systemsPips:systemsPips})}function systemsCapacitorResultFor(modules,budget,statsFor){let distributor=null;for(const module of modules){const stats2=statsFor(module);if(isPowerDistributor(module,stats2)&&isEnabled(module)&&budget.available>0&&poweredStates(module,stats2,budget).retracted)distributor=module}if(!distributor)return completeResult({systemsCapacity:0,systemsRecharge:0});const stats=statsFor(distributor);const systemsCapacity=effectiveStat(distributor,"systemsCapacity",stats);const systemsRecharge=effectiveStat(distributor,"systemsRecharge",stats);return systemsCapacity===void 0||systemsRecharge===void 0?incompleteResult([metricIssue("powerDistributor","unresolved",distributor)]):completeResult({systemsCapacity:systemsCapacity,systemsRecharge:systemsRecharge})}function thrusterCurveFor(module,stats){const effective=effectiveModule(module,stats);const minMass=effective?.minMass;const optMass=effective?.optMass;const maxMass=effective?.maxMass;const minMultiplier=effective?.minMultiplier;const optMultiplier=effective?.optMultiplier;const maxMultiplier=effective?.maxMultiplier;if(minMass===void 0||optMass===void 0||maxMass===void 0||minMultiplier===void 0||optMultiplier===void 0||maxMultiplier===void 0){return null}return{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:minMultiplier,optMultiplier:optMultiplier,maxMultiplier:maxMultiplier,...effective?.optSpeedMultiplier===void 0?{}:{speedCurve:{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:effective.minSpeedMultiplier??minMultiplier,optMultiplier:effective.optSpeedMultiplier,maxMultiplier:effective.maxSpeedMultiplier??maxMultiplier}},...effective?.optRotationMultiplier===void 0?{}:{rotationCurve:{minMass:minMass,optMass:optMass,maxMass:maxMass,minMultiplier:effective.minRotationMultiplier??minMultiplier,optMultiplier:effective.optRotationMultiplier,maxMultiplier:effective.maxRotationMultiplier??maxMultiplier}}}}function fittedThrusterParamsFor(modules,statsFor){for(const module of modules){const stats=statsFor(module);if(isThruster(module,stats))return thrusterCurveFor(module,stats)}return null}function mobilityInputResultFor(ship,modules,getBudget,mass,statsFor){let thrusters=null;for(const module of modules){const stats=statsFor(module);if(!isThruster(module,stats))continue;const powered=poweredMetricBudgetFor("thrusters",module,stats,modules,getBudget,statsFor);if(!powered.complete)return powered;thrusters=thrusterCurveFor(module,stats);if(!thrusters)return incompleteResult([metricIssue("thrusters","unresolved",module)]);break}if(!thrusters)return incompleteResult([metricIssue("thrusters","missing")]);return completeResult({minimumSpeed:ship.minimumSpeed,maximumSpeed:ship.maximumSpeed,boost:ship.boost,minPitch:ship.minPitch,pitch:ship.pitch,minRoll:ship.minRoll,roll:ship.roll,minYaw:ship.minYaw,yaw:ship.yaw,mass:typeof mass==="function"?mass():mass,thrusters:thrusters})}function shieldRecoveryInputResultFor(ship,modules,getBudget,systemsPips,statsFor){const generator=poweredShieldGeneratorResultFor(modules,getBudget,statsFor);if(!generator.complete)return generator;const{module:generatorModule,budget:budget}=generator.value;const generatorStats=statsFor(generatorModule);const distributorDraw=effectiveStat(generatorModule,"distributorDraw",generatorStats);const regenRate=effectiveStat(generatorModule,"shieldRegenRate",generatorStats);const brokenRegenRate=effectiveStat(generatorModule,"shieldBrokenRegenRate",generatorStats);if(distributorDraw===void 0||regenRate===void 0||brokenRegenRate===void 0){return incompleteResult([metricIssue("shieldGenerator","unresolved",generatorModule)])}const capacitor=systemsCapacitorResultFor(modules,budget,statsFor);if(!capacitor.complete)return capacitor;const strength=shieldMetrics(shieldInputFor(ship,modules,budget,statsFor)).strength;return completeResult({strength:strength,regenRate:regenRate,brokenRegenRate:brokenRegenRate,distributorDraw:distributorDraw,systemsCapacity:capacitor.value.systemsCapacity,systemsRecharge:capacitor.value.systemsRecharge,systemsPips:systemsPips})}function weaponsCapacitorInputFor(modules,weaponsPips,budget,statsFor){let weaponsCapacity=0;let weaponsRecharge=0;let sustainedEnergyPerSecond=0;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(!poweredStates(module,stats,budget).deployed)continue;if(isPowerDistributor(module,stats)){weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats)??0;weaponsRecharge=effectiveStat(module,"weaponsRecharge",stats)??0}const weapon=weaponStatsFor(module,stats);if(weapon){sustainedEnergyPerSecond+=weaponMetrics(weapon).sustainedEnergyPerSecond}}return{weaponsCapacity:weaponsCapacity,weaponsRecharge:weaponsRecharge,sustainedEnergyPerSecond:sustainedEnergyPerSecond,weaponsPips:weaponsPips}}function distributorInputResultFor(modules,pips,budget,statsFor){let disabled=null;for(const module of modules){const stats=statsFor(module);if(!isPowerDistributor(module,stats))continue;if(!isEnabled(module)){disabled??=module;continue}if(!poweredStates(module,stats,budget).retracted){return incompleteResult([metricIssue("powerDistributor","shed",module)])}const systemsCapacity=effectiveStat(module,"systemsCapacity",stats);const systemsRecharge=effectiveStat(module,"systemsRecharge",stats);const enginesCapacity=effectiveStat(module,"enginesCapacity",stats);const enginesRecharge=effectiveStat(module,"enginesRecharge",stats);const weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats);const weaponsRecharge=effectiveStat(module,"weaponsRecharge",stats);if(systemsCapacity===void 0||systemsRecharge===void 0||enginesCapacity===void 0||enginesRecharge===void 0||weaponsCapacity===void 0||weaponsRecharge===void 0){return incompleteResult([metricIssue("powerDistributor","unresolved",module)])}return completeResult({systemsCapacity:systemsCapacity,systemsRecharge:systemsRecharge,enginesCapacity:enginesCapacity,enginesRecharge:enginesRecharge,weaponsCapacity:weaponsCapacity,weaponsRecharge:weaponsRecharge,...pips})}return incompleteResult([disabled===null?metricIssue("powerDistributor","missing"):metricIssue("powerDistributor","disabled",disabled)])}function heatInputResultFor(ship,modules,budget,statsFor){let plant=null;let heatEfficiency;let thrusterHeatRate=0;let deployedThrusterHeatRate=0;let fsdHeatRate=0;let weaponsCapacity=0;const weapons=[];for(const module of modules){const stats=statsFor(module);if(isPowerPlant(module,stats)){if(!isEnabled(module)){return incompleteResult([metricIssue("powerCapacity","disabled",module)])}plant=module;heatEfficiency=effectiveStat(module,"heatEfficiency",stats);continue}if(!isEnabled(module))continue;const running=poweredStates(module,stats,budget);if(isThruster(module,stats)){const heat=effectiveStat(module,"engineHeatRate",stats)??0;if(running.retracted)thrusterHeatRate+=heat;if(running.deployed)deployedThrusterHeatRate+=heat}else if(isFrameShiftDrive(module,stats)){if(running.retracted)fsdHeatRate+=effectiveStat(module,"fsdHeatRate",stats)??0}else if(isPowerDistributor(module,stats)){if(running.deployed){weaponsCapacity=effectiveStat(module,"weaponsCapacity",stats)??0}}const weapon=weaponStatsFor(module,stats);if(!running.deployed)continue;if(!weapon)continue;weapons.push({heatPerSecond:weaponMetrics(weapon).sustainedHeatPerSecond,distributorDraw:weapon.distributorDraw??0})}if(heatEfficiency===void 0){return incompleteResult([plant===null?metricIssue("powerCapacity","missing"):metricIssue("heatEfficiency","unresolved",plant)])}return completeResult({heatCapacity:ship.heatCapacity,heatDissipation:ship.heatDissipation,heatEfficiency:heatEfficiency,retractedPowerDraw:poweredDraw(budget,"retracted"),deployedPowerDraw:poweredDraw(budget,"deployed"),thrusterHeatRate:thrusterHeatRate,deployedThrusterHeatRate:deployedThrusterHeatRate,fsdHeatRate:fsdHeatRate,weaponsCapacity:weaponsCapacity,weapons:weapons})}function poweredDraw(budget,state){const powered=state==="retracted"?"poweredRetracted":"poweredDeployed";return budget.bands.reduce((total,band)=>band[powered]?total+band[state]:total,0)}function poweredStates(module,stats,budget){const draw=effectiveStat(module,"powerDraw",stats);if(draw===void 0||draw===0)return{retracted:true,deployed:true};const band=budget.bands[Math.min(budget.bands.length,Math.max(1,priorityOf(module)))-1];if(!band)return{retracted:true,deployed:true};return{retracted:band.poweredRetracted,deployed:band.poweredDeployed}}function cellBankInputsFor(modules,budget,statsFor){const banks=[];for(const module of modules){if(!startsWithAny(module.Item,PREFIX.shieldCellBank))continue;const stats=statsFor(module);const effective=effectiveModule(module,stats);const ammunition=effective?ammunitionCapacity(effective):null;banks.push({slot:module.Slot,symbol:module.Item,reinforcementRate:effective?.shieldBankReinforcement??0,cells:ammunition?.total??0,spinUp:effective?.shieldBankSpinUp??0,duration:effective?.shieldBankDuration??0,heat:effective?.shieldBankHeat??0,powered:budget.available>0&&isEnabled(module)&&poweredStates(module,stats,budget).deployed})}return banks}function stockBulkhead(ship){const variants=getBulkheadsForShip(ship.name,CORE_MODULES);return variants.find(v=>v.symbol.toLowerCase().endsWith("_default"))??variants.find(v=>v.mass===0)??variants[0]??null}function armourInputFor(ship,modules,statsFor){const reinforcements=[];const moduleReinforcements=[];let bulkhead=null;for(const module of modules){if(!isEnabled(module))continue;const stats=statsFor(module);if(module.Slot.toLowerCase()==="armour"){bulkhead={hullBoost:effectiveStat(module,"hullBoost",stats)??0,...resistancesOf(module,stats)}}else if(startsWithAny(module.Item,PREFIX.hullReinforcement)){const boost=getLoadoutModifier(module,"DefenceModifierHealthMultiplier");reinforcements.push({hullReinforcement:effectiveStat(module,"hullReinforcement",stats)??0,hullBoost:boost===null?0:boost/scaleForLabel("DefenceModifierHealthMultiplier"),...resistancesOf(module,stats)})}else if(startsWithAny(module.Item,PREFIX.moduleReinforcement)){moduleReinforcements.push({moduleProtection:effectiveStat(module,"moduleProtection",stats)??0,integrity:effectiveStat(module,"integrity",stats)??0})}}if(!bulkhead){const stock=stockBulkhead(ship);bulkhead=stock?{hullBoost:stock.hullBoost??0,...mapResistanceFields(field=>stock[field])}:null}return{baseArmour:ship.baseArmour,bulkhead:bulkhead,reinforcements:reinforcements,moduleReinforcements:moduleReinforcements}}var WEAPON_FIELDS=["damage","roundsPerShot","rateOfFire","burstInterval","burstRounds","burstRateOfFire","chargeTime","clipSize","ammoMaximum","reloadTime","distributorDraw","thermalLoad","powerDraw","maximumRange","falloffRange","armourPiercing"];function weaponStatsFor(module,stats){if(!stats||stats.category!=="hardpoint")return null;const weapon={};for(const field of WEAPON_FIELDS){const value=effectiveStat(module,field,stats);if(value!==void 0)weapon[field]=value}normalizeEffectiveWeapon(module,weapon);const damageDistribution=effectiveDamageDistribution(module,stats);if(damageDistribution)weapon.damageDistribution=damageDistribution;if(stats.damageComponents&&!convertsDamage(module)){weapon.damageComponents=scaleDamageComponents(stats.damageComponents,stats.damage,typeof weapon.damage==="number"?weapon.damage:void 0)}if(stats.projectileRange)weapon.projectileRange={...stats.projectileRange};return weapon}function burstAdjustedRateOfFire(module,weapon){if(getLoadoutModifier(module,"RateOfFire")!==null)return void 0;const touched=["BurstSize","BurstRateOfFire","BurstInterval"].some(label=>getLoadoutModifier(module,label)!==null);if(!touched)return void 0;return combinedRateOfFire(weapon)}var FIRING_RATE_LABELS=["RateOfFire","BurstRateOfFire","BurstSize","BurstInterval","RoundsPerShot","Rounds"];function readsDamageFromPerSecond(module){return getLoadoutModifier(module,"Damage")===null&&FIRING_RATE_LABELS.every(label=>getLoadoutModifier(module,label)===null)}function normalizeEffectiveWeapon(module,weapon){const rate=burstAdjustedRateOfFire(module,weapon);if(rate!==void 0)weapon.rateOfFire=rate;if(readsDamageFromPerSecond(module)){const statedDamagePerSecond=getLoadoutModifier(module,"DamagePerSecond");const firingFactor=Number(weapon.roundsPerShot??1)*Number(weapon.rateOfFire??1);if(statedDamagePerSecond!==null&&firingFactor>0){weapon.damage=statedDamagePerSecond/firingFactor}}const{maximumRange:maximumRange,falloffRange:falloffRange}=weapon;if(maximumRange!==void 0&&falloffRange!==void 0&&falloffRange>maximumRange){weapon.falloffRange=maximumRange}}var INTERNALS=/* @__PURE__ */new WeakMap;function publishLoadoutInternals(build,internals){INTERNALS.set(build,internals)}function loadoutInternals(build,label){const internals=typeof build==="object"&&build!==null?INTERNALS.get(build):void 0;if(internals===void 0){throw new TypeError(`${label} must be a ShipLoadout, received ${describeValue(build)}`)}return internals}export{armourInputFor,cellBankInputsFor,completeResult,distributorInputResultFor,effectiveModule,fittedThrusterParamsFor,heatInputResultFor,incompleteResult,loadoutInternals,mobilityInputResultFor,moduleFitError,moduleFitProblem,normalizeLoadoutEvent,powerAvailable,powerConsumerFor,preEngineeredVariantFor,publishLoadoutInternals,shieldCapacitorInputResultFor,shieldInputResultFor,shieldRecoveryInputResultFor,weaponStatsFor,weaponsCapacitorInputFor};//# sourceMappingURL=chunk-FD74K27A.js.map