Function bodies 443 total
buildMergedGearPool function · typescript · L61-L84 (24 LOC)src/data/merged-loaders.ts
export function buildMergedGearPool(
getters: MergedGetters,
enabledIds: EnabledIds,
): GearPool {
const equipment = extractItems(getters.getMergedEquipment(), enabledIds.equipment);
const enchantments = extractItems(getters.getMergedEnchantments(), enabledIds.enchantments);
const modifiers = extractItems(getters.getMergedModifiers(), enabledIds.modifiers);
const gems = extractItems(getters.getMergedGems(), enabledIds.gems);
// Partition equipment by slot type
const isAccessory = (e: EquipmentPiece): boolean =>
e.slot === "accessory" ||
e.slot === "accessory-H" ||
e.slot === "accessory-A";
return {
chestplates: equipment.filter((e) => e.slot === "chestplate"),
leggings: equipment.filter((e) => e.slot === "leggings"),
accessories: equipment.filter(isAccessory),
enchantments,
modifiers,
gems,
};
}mergeItems function · typescript · L40-L86 (47 LOC)src/data/merge-user-data.ts
export function mergeItems<T extends { readonly id: string }>(
bundled: readonly T[],
userRecords: readonly UserItemRecord<T>[],
): readonly MergedItem<T>[] {
const recordMap = createRecordMap(userRecords);
const bundledIds = new Set(bundled.map((b) => b.id));
const result: MergedItem<T>[] = [];
// Process bundled items
for (const item of bundled) {
const record = recordMap.get(item.id);
// Skip if user deleted this bundled item
if (record?.deleted) continue;
// Use user's modified data if present, otherwise bundled
if (record?.data !== undefined) {
result.push({
item: record.data,
source: "bundled",
isModified: true,
isDeleted: false,
});
} else {
result.push({
item,
source: "bundled",
isModified: false,
isDeleted: false,
});
}
}
// Add user-created items (not overrides of bundled)
for (const record of userRecords) {
if (!bundledIds.has(recordgetDeletedItems function · typescript · L95-L115 (21 LOC)src/data/merge-user-data.ts
export function getDeletedItems<T extends { readonly id: string }>(
bundled: readonly T[],
userRecords: readonly UserItemRecord<T>[],
): readonly MergedItem<T>[] {
const recordMap = createRecordMap(userRecords);
const result: MergedItem<T>[] = [];
for (const item of bundled) {
const record = recordMap.get(item.id);
if (record?.deleted) {
result.push({
item,
source: "bundled",
isModified: false,
isDeleted: true,
});
}
}
return result;
}toVariantTypesRecord function · typescript · L207-L216 (10 LOC)src/data/merge-user-data.ts
export function toVariantTypesRecord(
merged: readonly MergedItem<VariantTypeEntry & { readonly key: string }>[],
): VariantTypes {
const result: Record<string, VariantTypeEntry> = {};
for (const { item } of merged) {
const { key, ...entry } = item;
result[key] = entry;
}
return result;
}normalizeItemName function · typescript · L23-L31 (9 LOC)src/data/sync-utils.ts
export function normalizeItemName(name: string): string {
return name
.toLowerCase()
.trim()
.replace(/'s\b/g, "") // Remove possessive 's (e.g., "Cernyx's" → "Cernyx")
.replace(/'\s/g, " ") // Remove apostrophe before space (e.g., "Cernyx' " → "Cernyx ")
.replace(/\s+/g, " ") // Collapse multiple spaces
.trim(); // Trim again after replacements
}detectEquipmentDuplicates function · typescript · L61-L92 (32 LOC)src/data/sync-utils.ts
export function detectEquipmentDuplicates(
userRecords: readonly UserItemRecord<EquipmentPiece>[],
bundledItems: readonly EquipmentPiece[]
): DuplicateMatch[] {
const matches: DuplicateMatch[] = [];
// Build lookup map: normalized "name|slot" → bundled item
const bundledLookup = new Map<string, EquipmentLikeItem>();
for (const item of bundledItems) {
const key = `${normalizeItemName(item.name)}|${item.slot}`;
bundledLookup.set(key, item);
}
// Check each contribution record
for (const record of userRecords) {
if (record.deleted === true) continue;
if (record.data === undefined) continue;
if (getEffectivePurpose(record) !== "contribution") continue;
const key = `${normalizeItemName(record.data.name)}|${record.data.slot}`;
const bundled = bundledLookup.get(key);
if (bundled !== undefined) {
matches.push({
userItemId: record.id,
bundledItemId: bundled.id,
bundledItemName: bundled.name,
});
}
}
detectNamedDuplicates function · typescript · L97-L126 (30 LOC)src/data/sync-utils.ts
export function detectNamedDuplicates<T extends NamedItem>(
userRecords: readonly UserItemRecord<T>[],
bundledItems: readonly T[]
): DuplicateMatch[] {
const matches: DuplicateMatch[] = [];
// Build lookup map: normalized name → bundled item
const bundledLookup = new Map<string, NamedItem>();
for (const item of bundledItems) {
bundledLookup.set(normalizeItemName(item.name), item);
}
// Check each contribution record
for (const record of userRecords) {
if (record.deleted === true) continue;
if (record.data === undefined) continue;
if (getEffectivePurpose(record) !== "contribution") continue;
const bundled = bundledLookup.get(normalizeItemName(record.data.name));
if (bundled !== undefined) {
matches.push({
userItemId: record.id,
bundledItemId: bundled.id,
bundledItemName: bundled.name,
});
}
}
return matches;
}Repobility (the analyzer behind this table) · https://repobility.com
computeBundledDiff function · typescript · L152-L181 (30 LOC)src/data/sync-utils.ts
export function computeBundledDiff<T extends NamedItem>(
oldItems: readonly T[],
newItems: readonly T[]
): BundledDiff<T> {
const oldMap = new Map(oldItems.map((item) => [item.id, item]));
const newMap = new Map(newItems.map((item) => [item.id, item]));
const added: T[] = [];
const modified: T[] = [];
const removed: T[] = [];
// Find added and modified
for (const [id, newItem] of newMap) {
const oldItem = oldMap.get(id);
if (oldItem === undefined) {
added.push(newItem);
} else if (!itemsEqual(oldItem, newItem)) {
modified.push(newItem);
}
}
// Find removed
for (const [id, oldItem] of oldMap) {
if (!newMap.has(id)) {
removed.push(oldItem);
}
}
return { added, modified, removed };
}categorizeUserItems function · typescript · L208-L234 (27 LOC)src/data/sync-utils.ts
export function categorizeUserItems<T extends NamedItem>(
userRecords: readonly UserItemRecord<T>[],
duplicateIds: ReadonlySet<string>
): CategorizedUserItems<T> {
const duplicates: UserItemRecord<T>[] = [];
const orphanContributions: UserItemRecord<T>[] = [];
const customItems: UserItemRecord<T>[] = [];
for (const record of userRecords) {
// Skip delete markers (no data)
if (record.data === undefined) continue;
// Skip soft-deleted items
if (record.deleted === true) continue;
const purpose = getEffectivePurpose(record);
if (purpose === "custom") {
customItems.push(record);
} else if (duplicateIds.has(record.id)) {
duplicates.push(record);
} else {
orphanContributions.push(record);
}
}
return { duplicates, orphanContributions, customItems };
}buildSyncSummary function · typescript · L258-L276 (19 LOC)src/data/sync-utils.ts
export function buildSyncSummary(
bundledDiff: BundledDiff<NamedItem>,
categorized: CategorizedUserItems<NamedItem>,
changelog: ChangelogEntry | undefined
): SyncSummary {
return {
bundledChanges: {
added: bundledDiff.added.length,
modified: bundledDiff.modified.length,
removed: bundledDiff.removed.length,
},
userItems: {
duplicates: categorized.duplicates.length,
orphanContributions: categorized.orphanContributions.length,
customItems: categorized.customItems.length,
},
changelog,
};
}createUserItemRecordSchema function · typescript · L37-L49 (13 LOC)src/data/user-data-schemas.ts
function createUserItemRecordSchema<T extends z.ZodTypeAny>(itemSchema: T) {
return z
.object({
id: z.string(),
deleted: z.boolean().optional(),
data: itemSchema.optional(),
baseVersion: z.number().int().optional(),
purpose: itemPurposeSchema.optional(),
createdAt: z.number(),
updatedAt: z.number(),
})
.readonly();
}useVersionCheck function · typescript · L14-L20 (7 LOC)src/hooks/use-version-check.ts
export function useVersionCheck(): UseVersionCheckResult {
const checkBundledUpdate = useUserDataStore((s) => s.checkBundledUpdate);
// Initialize state based on version check - runs once on mount
const [showConflict, setShowConflict] = useState(() => checkBundledUpdate());
return { showConflict, setShowConflict };
}getPieceStats function · typescript · L72-L77 (6 LOC)src/search/constraints.ts
export function getPieceStats(piece: EquipmentPiece | ExpandedEquipment): Partial<Stats> {
if ("effectiveStats" in piece) {
return piece.effectiveStats;
}
return piece.baseStats;
}computeSlotStats function · typescript · L80-L92 (13 LOC)src/search/constraints.ts
export function computeSlotStats(slot: EquippedSlot): Partial<Stats> {
const sources: readonly Partial<Stats>[] = [
getPieceStats(slot.piece),
...(slot.enchantment ? [slot.enchantment.stats] : []),
...(slot.modifier ? [slot.modifier.stats] : []),
...slot.gems.map((g) => g.stats),
// Atlantean modifier contributes insanity as a real stat
...(slot.modifier?.atlanteanBehavior != null
? [{ insanity: slot.modifier.atlanteanBehavior.insanity } as Partial<Stats>]
: []),
];
return sumStatBlocks(sources);
}sumStatBlocks function · typescript · L98-L115 (18 LOC)src/search/constraints.ts
function sumStatBlocks(
blocks: readonly Partial<Stats>[],
): Partial<Stats> {
const result: Partial<Stats> = {};
for (const name of STAT_NAMES) {
let total = 0;
let found = false;
for (const block of blocks) {
const val = block[name] ?? 0;
if (val !== 0) found = true;
total += val;
}
if (found) {
(result as Record<string, number>)[name] = total;
}
}
return result;
}Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
checkSlotComposition function · typescript · L126-L150 (25 LOC)src/search/constraints.ts
function checkSlotComposition(
loadout: Loadout,
constraints: HardConstraints,
): readonly ConstraintViolation[] {
const violations: ConstraintViolation[] = [];
let chestCount = 0;
let legCount = 0;
let accCount = 0;
for (const slot of loadout.slots) {
const t = slot.piece.slot;
if (t === "chestplate") chestCount++;
else if (t === "leggings") legCount++;
else accCount++;
}
if (chestCount !== 1) {
violations.push(violation("slot-composition", `Expected 1 chestplate, got ${String(chestCount)}`));
}
if (legCount !== 1) {
violations.push(violation("slot-composition", `Expected 1 leggings, got ${String(legCount)}`));
}
if (accCount !== constraints.totalAccessories) {
violations.push(violation("slot-composition", `Expected ${String(constraints.totalAccessories)} accessories, got ${String(accCount)}`));
}
return violations;
}checkHelmetLimit function · typescript · L153-L162 (10 LOC)src/search/constraints.ts
function checkHelmetLimit(
loadout: Loadout,
constraints: HardConstraints,
): readonly ConstraintViolation[] {
const count = loadout.slots.filter((s) => s.piece.slot === "accessory-H").length;
if (count > constraints.maxHelmetAccessories) {
return [violation("helmet-limit", `Max ${String(constraints.maxHelmetAccessories)} helmet accessory, got ${String(count)}`)];
}
return [];
}checkAmuletLimit function · typescript · L165-L174 (10 LOC)src/search/constraints.ts
function checkAmuletLimit(
loadout: Loadout,
constraints: HardConstraints,
): readonly ConstraintViolation[] {
const count = loadout.slots.filter((s) => s.piece.slot === "accessory-A").length;
if (count > constraints.maxAmuletAccessories) {
return [violation("amulet-limit", `Max ${String(constraints.maxAmuletAccessories)} amulet accessory, got ${String(count)}`)];
}
return [];
}checkNoDuplicates function · typescript · L177-L191 (15 LOC)src/search/constraints.ts
function checkNoDuplicates(
loadout: Loadout,
constraints: HardConstraints,
): readonly ConstraintViolation[] {
if (!constraints.noDuplicateItems) return [];
const seen = new Set<string>();
const violations: ConstraintViolation[] = [];
for (const slot of loadout.slots) {
if (seen.has(slot.piece.id)) {
violations.push(violation("no-duplicates", `Duplicate equipment: ${slot.piece.name} (${slot.piece.id})`));
}
seen.add(slot.piece.id);
}
return violations;
}checkAtlanteanConflict function · typescript · L194-L212 (19 LOC)src/search/constraints.ts
function checkAtlanteanConflict(
loadout: Loadout,
constraints: HardConstraints,
): readonly ConstraintViolation[] {
const violations: ConstraintViolation[] = [];
for (const slot of loadout.slots) {
if (!slot.enchantment || !slot.modifier?.atlanteanBehavior) continue;
const isIncompat = constraints.atlanteanIncompatibleWith.includes(slot.enchantment.id);
if (isIncompat) {
violations.push(
violation(
"atlantean-conflict",
`${slot.enchantment.name} enchantment conflicts with Atlantean modifier on ${slot.piece.name}`,
),
);
}
}
return violations;
}checkSingleEnchantment function · typescript · L215-L221 (7 LOC)src/search/constraints.ts
function checkSingleEnchantment(
_loadout: Loadout,
): readonly ConstraintViolation[] {
// The type system enforces at most 1 enchantment via `enchantment?: Enchantment`.
// This validator exists for defense-in-depth; nothing to check at runtime.
return [];
}checkGemCount function · typescript · L224-L237 (14 LOC)src/search/constraints.ts
function checkGemCount(
loadout: Loadout,
): readonly ConstraintViolation[] {
const violations: ConstraintViolation[] = [];
for (const slot of loadout.slots) {
const maxGems = slot.piece.socketCount + (slot.modifier?.grantsSocket === true ? 1 : 0);
if (slot.gems.length > maxGems) {
violations.push(
violation("gem-count", `${slot.piece.name} has ${String(slot.gems.length)} gems but max is ${String(maxGems)}`),
);
}
}
return violations;
}validateLoadout function · typescript · L251-L265 (15 LOC)src/search/constraints.ts
export function validateLoadout(
loadout: Loadout,
constraints: HardConstraints,
): ValidationResult {
const violations: readonly ConstraintViolation[] = [
...checkSlotComposition(loadout, constraints),
...checkHelmetLimit(loadout, constraints),
...checkAmuletLimit(loadout, constraints),
...checkNoDuplicates(loadout, constraints),
...checkAtlanteanConflict(loadout, constraints),
...checkSingleEnchantment(loadout),
...checkGemCount(loadout),
];
return { valid: violations.length === 0, violations };
}Open data scored by Repobility · https://repobility.com
mergeResults function · typescript · L47-L65 (19 LOC)src/search/coordinator-core.ts
export function mergeResults(
allResults: readonly (readonly SearchResult[])[],
maxResults: number,
): readonly SearchResult[] {
const merged = allResults.flat();
merged.sort((a, b) => b.score - a.score);
// Dedupe by loadout fingerprint (piece IDs only)
const seen = new Set<string>();
const unique: SearchResult[] = [];
for (const r of merged) {
const key = r.loadout.slots.map((s) => s.piece.id).join(",");
if (seen.has(key)) continue;
seen.add(key);
unique.push(r);
if (unique.length >= maxResults) break;
}
return unique;
}CoordinatorCore.start method · typescript · L129-L141 (13 LOC)src/search/coordinator-core.ts
start(config: CoordinatorConfig, callbacks: CoordinatorCallbacks): void {
this.config = config;
this.callbacks = callbacks;
this.islands.clear();
const generations = config.generations ?? 1000;
this.totalGenerations = generations * this.islandCount;
// Spawn islands
for (let islandId = 0; islandId < this.islandCount; islandId++) {
this.spawnIsland(islandId, config, generations);
}
}CoordinatorCore.stop method · typescript · L144-L150 (7 LOC)src/search/coordinator-core.ts
stop(): void {
for (const state of this.islands.values()) {
state.handle.stop();
}
this.islands.clear();
this.callbacks = null;
}CoordinatorCore.spawnIsland method · typescript · L157-L204 (48 LOC)src/search/coordinator-core.ts
private spawnIsland(islandId: number, config: CoordinatorConfig, generations: number): void {
const islandCallbacks: IslandCallbacks = {
onProgress: (gen, bestScore, topResults) => {
this.handleProgress(islandId, gen, bestScore, topResults);
},
onStagnating: () => {
this.handleStagnating(islandId);
},
onMigrants: (individuals) => {
this.handleMigrants(islandId, individuals);
},
onComplete: (results, exitReason, finalGeneration) => {
this.handleComplete(islandId, results, exitReason, finalGeneration);
},
onError: (message) => {
this.callbacks?.onError(`Island ${String(islandId)}: ${message}`);
this.stop();
},
};
const handle = this.islandFactory(islandId, islandCallbacks);
const state: IslandState = {
handle,
generation: 0,
bestScore: -Infinity,
topResults: [],
completed: false,
finalResults: [],
exitReason: "complete",CoordinatorCore.handleProgress method · typescript · L206-L220 (15 LOC)src/search/coordinator-core.ts
private handleProgress(
islandId: number,
generation: number,
bestScore: number,
topResults: readonly SearchResult[],
): void {
const state = this.islands.get(islandId);
if (state == null) return;
state.generation = generation;
state.bestScore = bestScore;
state.topResults = topResults;
this.emitAggregatedProgress();
}CoordinatorCore.handleStagnating method · typescript · L222-L229 (8 LOC)src/search/coordinator-core.ts
private handleStagnating(islandId: number): void {
// Request migrants from ring neighbor
const neighborId = (islandId + 1) % this.islandCount;
const neighborState = this.islands.get(neighborId);
if (neighborState == null || neighborState.completed) return;
neighborState.handle.requestMigrants(MIGRATION_COUNT);
}CoordinatorCore.handleMigrants method · typescript · L231-L238 (8 LOC)src/search/coordinator-core.ts
private handleMigrants(islandId: number, individuals: Chromosome[]): void {
// Forward migrants to the stagnating island (ring predecessor)
const recipientId = (islandId - 1 + this.islandCount) % this.islandCount;
const recipientState = this.islands.get(recipientId);
if (recipientState == null || recipientState.completed) return;
recipientState.handle.receiveMigrants(individuals);
}CoordinatorCore.handleComplete method · typescript · L240-L262 (23 LOC)src/search/coordinator-core.ts
private handleComplete(
islandId: number,
results: readonly SearchResult[],
exitReason: GAExitReason,
finalGeneration: number,
): void {
const state = this.islands.get(islandId);
if (state == null) return;
state.completed = true;
state.finalResults = results;
state.exitReason = exitReason;
state.finalGeneration = finalGeneration;
// Update progress to show completion
this.emitAggregatedProgress();
// Check if all islands are done
const allComplete = Array.from(this.islands.values()).every((s) => s.completed);
if (allComplete) {
this.finalizeResults();
}
}Repobility · open methodology · https://repobility.com/research/
CoordinatorCore.emitAggregatedProgress method · typescript · L264-L279 (16 LOC)src/search/coordinator-core.ts
private emitAggregatedProgress(): void {
let totalGeneration = 0;
let bestScore = -Infinity;
const allTopResults: SearchResult[][] = [];
for (const state of this.islands.values()) {
totalGeneration += state.generation;
if (state.bestScore > bestScore) bestScore = state.bestScore;
if (state.topResults.length > 0) {
allTopResults.push([...state.topResults]);
}
}
const aggregatedResults = mergeResults(allTopResults, this.config?.maxResults ?? 20);
this.callbacks?.onProgress(totalGeneration, this.totalGenerations, bestScore, aggregatedResults);
}CoordinatorCore.finalizeResults method · typescript · L281-L302 (22 LOC)src/search/coordinator-core.ts
private finalizeResults(): void {
const allResults = Array.from(this.islands.values()).map((s) => s.finalResults);
const merged = mergeResults(allResults, this.config?.maxResults ?? 20);
// Determine aggregate exit reason
let finalGeneration = 0;
let totalGenerationsConfigured = 0;
let anyStagnation = false;
for (const state of this.islands.values()) {
finalGeneration += state.finalGeneration;
totalGenerationsConfigured += this.config?.generations ?? 1000;
if (state.exitReason === "stagnation") anyStagnation = true;
}
const exitMetadata: ExitMetadata = {
reason: anyStagnation ? "stagnation" : "complete",
finalGeneration,
totalGenerations: totalGenerationsConfigured,
};
this.callbacks?.onComplete(merged, exitMetadata);
}computeEfficiencyScore function · typescript · L52-L71 (20 LOC)src/search/efficiency-scoring.ts
export function computeEfficiencyScore(
stats: Stats,
weights: Readonly<Record<StatName, number>>,
): number {
let score = 0;
for (const stat of STAT_NAMES) {
const value = stats[stat];
const ratio = STAT_EFFICIENCY_RATIOS[stat];
const weight = weights[stat];
// Skip stats with zero weight
if (weight === 0) continue;
// Efficiency contribution: value / ratio * (weight / 100)
score += (value / ratio) * (weight / 100);
}
return score;
}getApplicableEnchantments function · typescript · L48-L53 (6 LOC)src/search/enhance.ts
function getApplicableEnchantments(
category: SlotCategory,
enchantments: readonly Enchantment[],
): readonly Enchantment[] {
return enchantments.filter((e) => e.applicableTo.includes(category));
}getApplicableModifiers function · typescript · L59-L67 (9 LOC)src/search/enhance.ts
function getApplicableModifiers(
piece: EquipmentPiece,
modifiers: readonly Modifier[],
): readonly Modifier[] {
if (piece.atlanteanOnly !== false) {
return modifiers.filter((m) => m.atlanteanBehavior != null);
}
return modifiers;
}isAtlanteanCompatible function · typescript · L73-L80 (8 LOC)src/search/enhance.ts
function isAtlanteanCompatible(
enchantment: Enchantment | undefined,
modifier: Modifier | undefined,
hardConstraints: HardConstraints,
): boolean {
if (enchantment == null || modifier?.atlanteanBehavior == null) return true;
return !hardConstraints.atlanteanIncompatibleWith.includes(enchantment.id);
}getSocketCount function · typescript · L86-L91 (6 LOC)src/search/enhance.ts
function getSocketCount(
slot: EquippedSlot,
modifier: Modifier | undefined,
): number {
return slot.piece.socketCount + (modifier?.grantsSocket === true ? 1 : 0);
}assignGemsWithinBudget function · typescript · L107-L140 (34 LOC)src/search/enhance.ts
function assignGemsWithinBudget(params: GemAssignParams): readonly Gem[] {
const { baseStats, availableGems, socketCount, fitness, maxDrawback, scoringMode, statWeights } = params;
if (socketCount <= 0 || availableGems.length === 0) return [];
const gems: Gem[] = [];
let currentStats = baseStats;
let usedDrawback = 0;
for (let s = 0; s < socketCount; s++) {
let bestGem: Gem | undefined;
let bestScore = -Infinity;
for (const gem of availableGems) {
// Skip gems that would exceed drawback budget
const gemDrawback = gem.stats.drawback ?? 0;
if (usedDrawback + gemDrawback > maxDrawback) continue;
const trialStats = sumStats(currentStats, gem.stats);
const score = computeFitness(trialStats, fitness, scoringMode, statWeights);
if (score > bestScore) {
bestScore = score;
bestGem = gem;
}
}
if (bestGem != null) {
gems.push(bestGem);
currentStats = sumStats(currentStats, bestGem.stats);
Repobility (the analyzer behind this table) · https://repobility.com
subtractStats function · typescript · L146-L152 (7 LOC)src/search/enhance.ts
function subtractStats(a: Stats, b: Stats): Stats {
const result = emptyStats();
for (const name of STAT_NAMES) {
result[name] = a[name] - b[name];
}
return result;
}computeEnhancedSlotContribution function · typescript · L154-L166 (13 LOC)src/search/enhance.ts
function computeEnhancedSlotContribution(
slot: EquippedSlot,
atlanteanChoice: StatName | null,
): Stats {
const slotStats = sumStats(computeSlotStats(slot));
if (atlanteanChoice != null && slot.modifier?.atlanteanBehavior != null) {
const bonus = ATLANTEAN_BONUS_VALUES[atlanteanChoice];
if (bonus !== 0) {
slotStats[atlanteanChoice] += bonus;
}
}
return slotStats;
}computeLoadoutStatsWithSlot function · typescript · L172-L188 (17 LOC)src/search/enhance.ts
function computeLoadoutStatsWithSlot(
otherSlotStats: Stats,
slot: EquippedSlot,
atlanteanChoice: StatName | null,
): Stats {
const slotStats = computeSlotStats(slot);
const result = sumStats(otherSlotStats, slotStats);
if (atlanteanChoice != null && slot.modifier?.atlanteanBehavior != null) {
const bonus = ATLANTEAN_BONUS_VALUES[atlanteanChoice];
if (bonus !== 0) {
result[atlanteanChoice] += bonus;
}
}
return result;
}evaluateEnchantModPair function · typescript · L216-L261 (46 LOC)src/search/enhance.ts
function evaluateEnchantModPair(
ctx: EvalContext,
enchantment: Enchantment | undefined,
modifier: Modifier | undefined,
): SlotCandidate {
const sockets = getSocketCount(ctx.slot, modifier);
const enhancedSlot: EquippedSlot = {
piece: ctx.slot.piece,
enchantment,
modifier,
gems: [],
};
// Calculate drawback used by enchant+modifier, remaining goes to gems
const enchModDrawback =
(enchantment?.stats.drawback ?? 0) + (modifier?.stats.drawback ?? 0);
const gemBudget = Math.max(0, ctx.gemDrawbackBudget - enchModDrawback);
const baseSlotStats = computeSlotStats(enhancedSlot);
const baseTotal = sumStats(ctx.otherSlotStats, baseSlotStats);
const gems = assignGemsWithinBudget({
baseStats: baseTotal,
availableGems: ctx.pool.gems,
socketCount: sockets,
fitness: ctx.fitness,
maxDrawback: gemBudget,
scoringMode: ctx.scoringMode,
statWeights: ctx.statWeights,
});
const fullSlot: EquippedSlot = {
piece: ctx.slot.piecapplyEnhancement function · typescript · L281-L291 (11 LOC)src/search/enhance.ts
function applyEnhancement(
slot: EquippedSlot,
candidate: SlotCandidate,
): EquippedSlot {
return {
piece: slot.piece,
enchantment: candidate.enchantment,
modifier: candidate.modifier,
gems: candidate.gems,
};
}initSlotState function · typescript · L304-L319 (16 LOC)src/search/enhance.ts
function initSlotState(loadout: Loadout): SlotAssignState {
const slots = [...loadout.slots] as [
EquippedSlot, EquippedSlot, EquippedSlot, EquippedSlot, EquippedSlot,
];
const atlanteanChoices = new Map<number, StatName>();
let runningTotal = emptyStats();
const contributions: Stats[] = [];
for (const slot of slots) {
const stats = sumStats(computeSlotStats(slot));
contributions.push(stats);
runningTotal = sumStats(runningTotal, stats);
}
return { slots, atlanteanChoices, runningTotal, contributions };
}updateSlotState function · typescript · L321-L344 (24 LOC)src/search/enhance.ts
function updateSlotState(
state: SlotAssignState,
index: number,
best: SlotCandidate,
): void {
const oldContribution = state.contributions[index];
if (oldContribution == null) return;
const currentSlot = state.slots[index];
if (currentSlot == null) return;
state.slots[index] = applyEnhancement(currentSlot, best);
if (best.atlanteanChoice != null) {
state.atlanteanChoices.set(index, best.atlanteanChoice);
}
const newContribution = computeEnhancedSlotContribution(
state.slots[index], best.atlanteanChoice,
);
state.runningTotal = sumStats(
subtractStats(state.runningTotal, oldContribution),
newContribution,
);
state.contributions[index] = newContribution;
}extractBudgetCaps function · typescript · L369-L386 (18 LOC)src/search/enhance.ts
function extractBudgetCaps(
fitness: readonly SoftConstraint[],
_hardConstraints: HardConstraints,
): BudgetCaps {
let maxDrawback = Infinity;
let maxInsanity = Infinity;
for (const c of fitness) {
if (c.stat === "drawback" && c.type === "atMost") {
maxDrawback = c.value ?? maxDrawback;
}
if (c.stat === "insanity" && c.type === "atMost") {
maxInsanity = c.value ?? maxInsanity;
}
}
return { maxDrawback, maxInsanity };
}Citation: Repobility (2026). State of AI-Generated Code. https://repobility.com/research/
budgetAwareAssign function · typescript · L402-L426 (25 LOC)src/search/enhance.ts
export function budgetAwareAssign(options: BudgetAssignOptions): EnhancedLoadoutResult {
const { loadout, pool, hardConstraints, fitness, scoringMode, statWeights } = options;
const state = initSlotState(loadout);
const caps = extractBudgetCaps(fitness, hardConstraints);
// Account for base equipment drawback when initializing enhancement budget
const baseDrawback = state.runningTotal.drawback;
let remainingDrawback = Math.max(0, caps.maxDrawback - baseDrawback);
for (let i = 0; i < state.slots.length; i++) {
const slot = state.slots[i];
if (slot == null) continue;
const contribution = state.contributions[i];
if (contribution == null) continue;
const otherStats = subtractStats(state.runningTotal, contribution);
const best = findBestBudgetSlot({
slot, pool, hardConstraints, otherSlotStats: otherStats, fitness, scoringMode, statWeights,
}, state.runningTotal, remainingDrawback, caps.maxInsanity);
updateSlotState(state, i, best);
findBestBudgetSlot function · typescript · L432-L462 (31 LOC)src/search/enhance.ts
function findBestBudgetSlot(
params: FindBestParams,
currentStats: Stats,
drawbackBudget: number,
insanityCap: number,
): SlotCandidate {
const { slot, pool, hardConstraints, otherSlotStats, fitness, scoringMode, statWeights } = params;
const category = slotCategory(slot);
const enchantments = getApplicableEnchantments(category, pool.enchantments);
const applicableMods = getApplicableModifiers(slot.piece, pool.modifiers);
const ctx: EvalContext = {
slot, pool, otherSlotStats, fitness, gemDrawbackBudget: drawbackBudget, scoringMode, statWeights,
};
let best: SlotCandidate = {
enchantment: undefined, modifier: undefined,
gems: [], atlanteanChoice: null, score: -Infinity,
};
for (const ench of [undefined, ...enchantments]) {
for (const mod of [undefined, ...applicableMods]) {
if (!isAtlanteanCompatible(ench, mod, hardConstraints)) continue;
const candidate = evaluateEnchantModPair(ctx, ench, mod);
if (!insanityWithinBudget(candsumStatFromSources function · typescript · L468-L480 (13 LOC)src/search/enhance.ts
function sumStatFromSources(
stat: StatName,
ench: Enchantment | undefined,
mod: Modifier | undefined,
gems: readonly Gem[],
): number {
let total = ench?.stats[stat] ?? 0;
total += mod?.stats[stat] ?? 0;
for (const gem of gems) {
total += gem.stats[stat] ?? 0;
}
return total;
}