"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // src/electron/main.js var import_electron = __toESM(require("electron"), 1); var import_node_path20 = __toESM(require("node:path"), 1); // src/electron/khaos/desktopApplication.js var import_node_fs7 = __toESM(require("node:fs"), 1); var import_node_path19 = __toESM(require("node:path"), 1); var import_node_v8 = require("node:v8"); var import_node_vm = require("node:vm"); // src/electron/khaos/security.js var import_node_path = __toESM(require("node:path"), 1); var import_node_url = require("node:url"); function normalizeDir(dir) { return import_node_path.default.resolve(dir).replace(/[\\/]+$/, "").toLowerCase(); } function isAppUrl(url, { appDir, rendererUrl }) { let parsed; try { parsed = new URL(url); } catch { return false; } if (parsed.protocol === "file:") { if (!appDir) return false; let file2; try { file2 = import_node_path.default.resolve((0, import_node_url.fileURLToPath)(parsed)).toLowerCase(); } catch { return false; } const root = normalizeDir(appDir); return file2 === root || file2.startsWith(root + import_node_path.default.sep); } if (parsed.protocol === "http:" || parsed.protocol === "https:") { if (!rendererUrl) return false; try { return parsed.origin === new URL(rendererUrl).origin; } catch { return false; } } return false; } function isExternalWebUrl(url) { try { return new URL(url).protocol === "https:"; } catch { return false; } } function isTrustedIpcSender(event, options) { const frame = event?.senderFrame; if (!frame || frame.parent) return false; return isAppUrl(frame.url, options); } function installKhaosElectronGuards(electron2, options) { const { app, ipcMain, shell } = electron2; const log = options.log ?? ((message3) => console.warn(message3)); app.on("web-contents-created", (_event, contents) => { contents.setWindowOpenHandler(({ url }) => { if (isExternalWebUrl(url)) { shell.openExternal(url).catch(() => { }); } return { action: "deny" }; }); contents.on("will-navigate", (event, url) => { if (!isAppUrl(url, options)) { event.preventDefault(); log(`[khaos-security] blocked navigation to ${String(url).slice(0, 200)}`); } }); contents.on("will-attach-webview", (event) => event.preventDefault()); }); const guard = (channel2, listener, refuse2) => channel2.startsWith("desktop:") ? (event, ...args) => { if (!isTrustedIpcSender(event, options)) { log(`[khaos-security] refused ${channel2} from ${event?.senderFrame?.url ?? "a destroyed frame"}`); return refuse2(event); } return listener(event, ...args); } : listener; const handle = ipcMain.handle.bind(ipcMain); const on = ipcMain.on.bind(ipcMain); ipcMain.handle = (channel2, listener) => handle(channel2, guard(channel2, listener, () => Promise.reject(new Error("untrusted sender")))); ipcMain.on = (channel2, listener) => on(channel2, guard(channel2, listener, (event) => { event.returnValue = null; })); } // src/electron/khaos/desktopSettings.js var import_promises = __toESM(require("node:fs/promises"), 1); var import_node_path2 = __toESM(require("node:path"), 1); var import_node_crypto = require("node:crypto"); // src/renderer/khaos/settings/keyboardLayouts.js var shortcutCategories = Object.fromEntries( ["Common", "Menu", "Tooltip", "Chat", "Option", "Fight", "QuickSlot", "Misc"].map((name) => [name, name[0].toLowerCase() + name.slice(1)]) ); var categoryIds = new Set(Object.values(shortcutCategories)); var defaultLayoutId = "frFR"; var frenchNumberRow = [...`&\xE9"'(-\xE8_\xE7\xE0)=`]; var frenchShiftedRow = [..."1234567890\xB0+"]; var belgianNumberRow = [...`&\xE9"'(\xA7\xE8!\xE7\xE0)-`]; var belgianShiftedRow = [..."1234567890\xB0_"]; var latinNumbers = [..."1234567890-="]; var latinShifted = [..."!@#$%^&*()_+"]; var numberCodes = [...Array.from({ length: 9 }, (_, index) => `Digit${index + 1}`), "Digit0", "Minus", "Equal"]; function keyBinding(code, label, modifiers2 = {}) { const value = { code, label }; for (const name of ["ctrl", "alt", "shift", "meta"]) value[name] = modifiers2[name] === true; return value; } var backquoteBinding = (label, modifiers2) => keyBinding("Backquote", label, modifiers2); var letter = (value, modifiers2) => { const label = value.toLocaleUpperCase("en-US"); return keyBinding(`Key${label}`, label, modifiers2); }; function layoutContract(id, labelKey, overrides = {}) { const contract = { id, labelKey }; contract.numberRow = latinNumbers; contract.shiftedNumberRow = latinShifted; contract.fullscreen = letter("f", { ctrl: true }); contract.compareItems = keyBinding("IntlBackslash", "<"); for (const [slot, modifiers2] of [["console", void 0], ["toggleHud", { alt: true }]]) contract[slot] = backquoteBinding("`", modifiers2); return Object.assign(contract, overrides); } var menuKeys = { openOptions: "o", openCharacteristics: "c", openSpells: "s", openInventory: "i", openQuests: "q", openWorldMap: "m", openSocial: "f", openGuild: "g", openAlliance: "a", openAchievements: "u", openShopGifts: "r", openEncyclopedia: "b", openBreeding: "d", openBuilds: "e", openHavenbag: "h", openKolizeum: "k", openBreach: "t", openSanctuary: "j", openCompanions: "v", toggleEntityNames: "p", toggleActorTooltips: "z", toggleInteractives: "y", previewFightStartCells: "l", togglePingMode: "w" }; var modifiedLetters = { toggleMute: ["m", "ctrl"], openProfile: ["p", "shift"], openSpouse: ["q", "ctrl"], openCosmetics: ["c", "shift"], toggleChannelFight: ["b", "ctrl"], showCell: ["s", "ctrl"] }; var physicalKeys = [ ["closeUi", "Escape", "\xC9chap"], ["validUi", "Enter", "Entr\xE9e"], ["upArrow", "ArrowUp", "Fl\xE8che haut"], ["downArrow", "ArrowDown", "Fl\xE8che bas"], ["focusChat", "Space", "Espace"], ["autoComplete", "Tab", "Tab"], ["nextChatTab", "PageDown", "Page suivante", "ctrl"], ["previousChatTab", "PageUp", "Page pr\xE9c\xE9dente", "ctrl"], ["shiftCloseUi", "Escape", "\xC9chap", "shift"], ["shiftUp", "ArrowUp", "Fl\xE8che haut", "shift"], ["shiftDown", "ArrowDown", "Fl\xE8che bas", "shift"], ["shiftValid", "Enter", "Entr\xE9e", "shift"], ["ctrlAltValid", "Enter", "Entr\xE9e", "ctrl", "alt"], ["ctrlValid", "Enter", "Entr\xE9e", "ctrl"], ["toggleChatHeight", "NumpadAdd", "+"], ["endFightTurn", "F1", "F1"], ["actionBarPreviousPage", "PageUp", "Page pr\xE9c\xE9dente"], ["actionBarNextPage", "PageDown", "Page suivante"] ]; function numberedKey(layout, index, modifiers2) { const labels = modifiers2.shift ? layout.shiftedNumberRow : layout.numberRow; if (numberCodes[index] === void 0 || labels[index] === void 0) throw new RangeError(`Unknown number-row position ${index}`); return keyBinding(numberCodes[index], labels[index], modifiers2); } function buildLayoutBindings(layout) { const bindings = Object.fromEntries(Object.entries(menuKeys).map(([action, key]) => [action, letter(key)])); for (const [action, [key, modifier]] of Object.entries(modifiedLetters)) bindings[action] = letter(key, { [modifier]: true }); for (const [action, code, label, ...modifiers2] of physicalKeys) { bindings[action] = keyBinding(code, label, Object.fromEntries(modifiers2.map((name) => [name, true]))); } Object.assign(bindings, { toggleHud: layout.toggleHud, toggleConsole: layout.console, compareItems: layout.compareItems, showTheoreticalEffects: keyBinding("", "Ctrl", { ctrl: true }) }); for (const [action, index] of [["toggleGrid", 0], ["toggleTransparentActors", 1], ["toggleCreatureMode", 4]]) { bindings[action] = numberedKey(layout, index, { shift: true }); } for (let slot = 0; slot < 36; slot++) { bindings[`actionBarSlot:${slot}`] = numberedKey(layout, slot % 12, { ctrl: slot >= 12, shift: slot >= 24 }); } for (let page2 = 1; page2 <= 5; page2++) bindings[`actionBarPage${page2}`] = numberedKey(layout, page2 - 1, { alt: true }); return bindings; } var layoutSpecs = [ ["deDE", "^"], ["enUK", "`"], ["enUS", "`"], ["esES", "\xB0"], ["frBE", "@", belgianNumberRow, belgianShiftedRow], ["frCA", "#"], ["frCH", "\xA7"], ["frFR", "\xB2", frenchNumberRow, frenchShiftedRow], ["itIT", "\\"], ["jaJP", "`", null, null, "\xB2"], ["nlNL", "\xA7"], ["ptBR", "'"], ["ptPT", "\\"], ["ruRU", "`", null, null, "\xB2"] ]; var keyboardLayouts = layoutSpecs.map(([id, consoleLabel, numbers, shifted, hudLabel = consoleLabel]) => { const locale = `${id.slice(0, 2)}_${id.slice(2).toLowerCase()}`; const layout = layoutContract(id, `options.shortcut.layout.${locale}`, { console: backquoteBinding(consoleLabel), toggleHud: backquoteBinding(hudLabel, { alt: true }), ...numbers ? { numberRow: numbers, shiftedNumberRow: shifted } : {}, ...id === "enUS" ? { compareItems: keyBinding("Comma", "<", { shift: true }) } : {}, ...id === "ruRU" ? { fullscreen: keyBinding("F11", "F11") } : {} }); return { id, labelKey: layout.labelKey, bindings: { ...buildLayoutBindings(layout), toggleFullscreen: layout.fullscreen } }; }); var keyboardLayoutIndex = new Map(keyboardLayouts.map((layout) => [layout.id, layout])); var isKeyboardLayout = (value) => keyboardLayoutIndex.has(value); var accountIdPattern = /^[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/iu; function accountKey(input) { if (typeof input !== "string" || !accountIdPattern.test(input)) throw new Error("Game account id must be a UUID"); return input.toLowerCase(); } // src/renderer/khaos/settings/optionDefaults.js var optionDefaults = { "allowHitAnim": true, "allowSpellEffects": true, "alterationFavoriteIds": [], "ambianceMuted": false, "ambianceVolume": 1, "antiAliasingMode": "msaa", "antiAliasingQuality": "4x", "audioDefaultsVersion": 3, "auraMode": "always", "autoEnableFrontAura": false, "backgroundFpsLimit": 30, "buffsWindowAutoResize": true, "cameraShakeEnabled": true, "chatAllianceSound": false, "chatChannelColors": {}, "chatFontSize": 16, "chatGroupSound": true, "chatGuildSound": true, "chatKeepLastChannel": false, "chatPrivateMessageSound": true, "chatShowTimestamps": false, "chatTeamSound": false, "chatUseChannelShortcuts": false, "chatUseInfoChannelPrefix": true, "combatAfkChatWarning": true, "combatAnimatePreviewTooltips": true, "combatAnimationSpeed": 1, "combatAutoOpenMechanicHints": true, "combatBringWindowToFront": "never", "combatChatDamageDetail": true, "combatConsecutivePassDelay": true, "combatHideFullLifeBars": false, "combatHoldToCast": true, "combatLifeBarsDisplay": "hover", "combatPersistentTargetTooltips": false, "combatShowAlignmentWings": false, "combatShowBossHealthBar": true, "combatShowDamageElementIcons": true, "combatShowInactivityPopup": true, "combatShowMovementDistance": false, "combatShowMovementPreview": true, "combatShowMovementZone": true, "combatShowPermanentPings": true, "combatShowSpellEffectPreview": true, "combatShowStateTurnCounter": true, "combatShowTurnOrder": false, "combatShowTurnStartIllustration": true, "combatShowUsedPointsFloatingText": false, "combatSpectatorAutoFighterInfo": true, "combatStatesDisplay": "always", "combatTacticalMode": false, "combatTimelineAutoResize": true, "combatTimelineFolded": false, "combatTimelineFollowTurn": false, "combatTimelineGaugesSide": "left", "combatTimelineOrientation": "leftToRight", "combatTimelinePortraitSize": "large", "combatTooltipHealthGauge": true, "combatTurnStartSound": true, "creatureLimit": 0, "creatureMode": false, "displayMode": "windowed", "dofus3Theme": "khaos", "doomScreenTint": true, "environmentEffectsAuto": true, "environmentEffectsEnabled": true, "experienceBarColors": {}, "experienceBarDisplayMode": "values", "experienceBarTrackedJobId": null, "experienceBarVisibleJobIds": [], "experienceBarVisibleSpecialGauges": [], "externalNotificationCorner": "bottom-right", "externalNotificationMaxCount": 5, "favoriteAuraEmoteIds": [], "favoriteCosmeticGids": [], "favoriteItemGids": [], "favoriteOrnamentIds": [], "favoriteTitleIds": [], "footstepVolume": 0, "forceDefaultTacticalModeTemplate": false, "fpsLimit": 0, "freezeStaticAnimations": false, "gameAlwaysShowTheoreticalEffects": false, "gameClassWindowPicto": false, "gameConfirmItemDrop": true, "gameHdvAvailableOnly": true, "gameHdvBuySortByCategory": { "equipment": { "column": "name", "ascending": true }, "consumables": { "column": "name", "ascending": true }, "resources": { "column": "name", "ascending": true }, "runes": { "column": "name", "ascending": true }, "soul-stones": { "column": "name", "ascending": true }, "creatures": { "column": "name", "ascending": true }, "cosmetics": { "column": "name", "ascending": true }, "other": { "column": "name", "ascending": true } }, "gameHdvFirstBuyConfirm": true, "gameHdvMultiOpenCount": 1, "gameHdvPriceChangeConfirm": "far-frozen", "gameObvijevanSpeech": true, "gameShowDungeonComplete": true, "gameShowLevelUp": true, "gameShowOmegaUnderOrnaments": true, "globalVolume": 1, "graphicsPreset": null, "hideDeadFighters": true, "hideSummonedFighters": false, "interfaceLanguage": "fr", "internalNotificationCorner": "middle-left", "keepDefaultUiSize": true, "magneticGapDistance": 0, "magneticSnapDistance": 12, "mapSwipeChange": true, "mapSwipeInvertHorizontal": false, "mapSwipeInvertVertical": false, "mapSwipeSensitivity": 50, "menuMusicMuted": false, "minimapHintFilters": null, "minimapShowGrid": false, "missionTrackerFontSize": 16, "missionTrackerOpacity": 0.9, "musicFavoriteGuids": [], "musicMuted": false, "musicPlaylists": [], "musicVolume": 0.1, "muteAll": false, "nightmareWeatherEnabled": true, "notificationDefaultsVersion": 3, "notificationDurationSeconds": 5, "notificationOverrides": {}, "notificationReduceOpacity": false, "notificationTrigger": "focus-lost", "notifyNewAnomaly": false, "partyAutoFollowMap": false, "partyAutoJoinFights": false, "partyAutoReady": false, "partyDisplayLines": 8, "partyDisplayOrientation": "vertical", "partyDisplayPortraitSize": "large", "partyLeaderAutoFollow": false, "quality": "high", "qualityAuto": true, "questListAutoResize": true, "questListFollowOnStarted": true, "questListFontSize": 16, "questListManualHeight": 370, "questListMaxFollowedQuests": 10, "questListOpacity": 0.7, "renderScalePercent": 100, "sfxMuted": false, "sfxVolume": 0.2, "showEveryMonsters": true, "showFps": false, "showGrid": false, "showInteractives": false, "skipFightAnimations": false, "socialAllianceMotd": false, "socialEpicDeathNotice": false, "socialFriendAchievementNotice": false, "socialFriendConnectionNotice": true, "socialFriendLevelUpNotice": false, "socialGuildMotd": true, "socialHideDisconnectedContacts": false, "socialShowConnectionStatus": true, "socialTaxCollectorAttackWarning": true, "specialTransitions": false, "spellTooltipShowShortcuts": true, "spellTooltipStackBonuses": false, "tacticalDefaultsVersion": 4, "tacticalMode": false, "timelineDeadVisibilityDefaultsVersion": 1, "tooltipShowAvgPrice": true, "tooltipShowDelayMs": 400, "tooltipShowDescription": true, "tooltipShowShortcuts": true, "transitionMode": "fade", "transparentActorsMode": false, "uiScalePercent": 100, "useNewTacticalMode": true, "voteReminders": true, "vsync": true, "khaosChatSoundDefaultsVersion": 1, "khaosCreatureLimitDefaultsVersion": 1, "khaosgameDesktopNotice": true, "khaosgameDesktopNoticeFocused": false, "khaosFightMarkEdgeGlow": true, "khaosFightMarkTeamColors": false, "khaosHavenBagMusic": "fluffworld", "khaosRoleplayTacticalResetVersion": 1, "khaosThemeDefaultsVersion": 1 }; // src/renderer/khaos/settings/settingsDefaults.js var shortcutProfileVersion = 3; var specialGauges = ["guild", "honor", "pods", "energy"]; var alterationFavoriteLimit = 3; var jobRows = { gathering: [[26, "flask"], [2, "axe"], [41, "bigKnife"], [24, "pickaxe"], [28, "scythe"], [36, "hook"]], crafting: [[16, "ringInclined"], [65, "spanner"], [15, "boots"], [60, "shield"], [11, "weapon"], [13, "bow"], [27, "helmet"]], forgemagie: [[62, "starBoot"], [64, "starHat"], [74, "starShield"], [44, "starSword"], [63, "starRing"], [48, "starBow"]] }; var professionCategories = Object.fromEntries(Object.entries(jobRows).map(([category2, rows]) => [category2, rows.map(([id]) => id)])); var professionMetadata = Object.fromEntries(Object.entries(jobRows).flatMap(([category2, rows]) => rows.map(([id, icon]) => [id, { icon, category: category2 }]))); var professionIds = new Set(Object.keys(professionMetadata).map(Number)); var professionTitles = Object.fromEntries(Object.keys(jobRows).map((category2) => [category2, `experience.job_category.${category2}`])); function defaultHudLayout(panels = {}) { return { profiles: [{ id: "default", name: "D\xE9faut", panels: { ...panels }, visibility: {}, modulesLocked: false, interfaceHidden: false }], activeProfileId: "default", combatProfileId: null, khaosCombatProfileReleased: true }; } var mapFields = [ "lastServerByAccount", "shortcutProfilesByAccount", "panels", "windowOffsets", "hudHpDisplayModes", "actionBarStateByCharacter", "taxiStateByCharacter", "characterSheetStateByCharacter", "shortcutCategoryEnabledByCharacter", "questFlagVisibilityByCharacter", "hiddenQuestsByCharacter", "minimapCustomMarkersByCharacter", "minimapCameraByWorld", "chatTabsByCharacter", "chatDetachedTabsByCharacter", "chatCombatTabByCharacter" ]; function createDefaultSettings() { const result = Object.fromEntries(mapFields.map((name) => [name, {}])); Object.assign(result, { windowWidth: 1280, windowHeight: 800, windowX: null, windowY: null, isMaximized: false, isFullscreen: false, lastMapId: null, pendingShortcutBindingsMigration: null, shortcutProfileMigrationVersion: shortcutProfileVersion, bannerMenuOrder: [], minimapOpenedSuperAreas: [], spellbookShowAllObtentionLevels: false, fightResultExpanded: false, predownloadSpeedProfile: "eco", chatHeightNormal: 244, chatHeightMaximized: 500, chatMaximized: false, chatAwayMessageHistory: [], multiAccount: { slotShortcuts: Array.from({ length: 8 }, (_, index) => `F${index + 1}`), globalScope: false, autoSwitchOnTurn: false, flashOnTurn: true, showDock: false }, hudLayout: defaultHudLayout(), options: structuredClone(optionDefaults) }); return result; } var settingsDefaults = createDefaultSettings(); // src/renderer/khaos/core/logging.js var LEVELS = { debug: 10, info: 20, warn: 30, error: 40, off: 99 }; var STORAGE_KEY = "khaos.logctl"; var LEGACY_KEY = "dofus3.logctl"; var wildcard = (pattern, scope) => { const prefix = pattern.replace(/\*$/, ""); return pattern.endsWith("*") ? scope.slice(0, prefix.length) === prefix : scope === pattern; }; function cleanRules(input) { return Array.isArray(input) ? input.filter((rule) => rule && typeof rule.pattern === "string" && Object.hasOwn(LEVELS, rule.level)).map(({ pattern, level }) => ({ pattern, level })) : []; } var LogStore = class { constructor(options = {}) { this.capacity = options.capacity ?? 8192; this.clock = options.clock ?? Date.now; this.sink = options.console ?? console; try { this.storage = "storage" in options ? options.storage : globalThis.localStorage; } catch { this.storage = null; } this.debug = options.debug ?? ["localhost", "127.0.0.1", "[::1]"].includes(globalThis.location?.hostname); this.history = /* @__PURE__ */ new Map(); this.counts = /* @__PURE__ */ new Map(); this.listeners = /* @__PURE__ */ new Set(); this.thresholdCache = /* @__PURE__ */ new Map(); this.sequence = 0; this.paused = false; this.last = null; this.reset(false); try { const persisted = JSON.parse(this.storage?.getItem(STORAGE_KEY) ?? this.storage?.getItem(LEGACY_KEY) ?? "null"); for (const target of ["capture", "console"]) { const rules = cleanRules(persisted?.[target]); if (rules.length || Array.isArray(persisted?.[target]) && persisted[target].length === 0) this.rules[target] = rules; } } catch { } } reset(persist = true) { this.rules = { capture: [{ pattern: "*", level: this.debug ? "debug" : "info" }], console: [{ pattern: "*", level: "warn" }] }; this.thresholdCache.clear(); if (persist) try { this.storage?.removeItem(STORAGE_KEY); this.storage?.removeItem(LEGACY_KEY); } catch { } } thresholds(scope) { if (!this.thresholdCache.has(scope)) { const resolved = {}; for (const target of ["capture", "console"]) { let value = target === "capture" ? LEVELS.info : LEVELS.warn; for (const rule of this.rules[target]) if (wildcard(rule.pattern, scope)) value = LEVELS[rule.level]; resolved[target] = value; } this.thresholdCache.set(scope, resolved); } return this.thresholdCache.get(scope); } configure(target, pattern, level) { if (!Object.hasOwn(this.rules, target) || typeof pattern !== "string" || !Object.hasOwn(LEVELS, level)) throw new TypeError("Invalid log rule"); this.rules[target].push({ pattern, level }); this.thresholdCache.clear(); try { this.storage?.setItem(STORAGE_KEY, JSON.stringify(this.rules)); } catch { } } enabled(level, scope = "*") { const minimum = this.thresholds(scope); return LEVELS[level] >= minimum.console || !this.paused && LEVELS[level] >= minimum.capture; } notify() { for (const listener of this.listeners) { try { listener(); } catch { } } } write(scope, level, message3, args) { const minimum = this.thresholds(scope); const capture = !this.paused && LEVELS[level] >= minimum.capture; const print = LEVELS[level] >= minimum.console; if (!capture && !print) return; const wallTime = this.clock(); message3 = String(message3); if (capture) { if (this.last?.scope === scope && this.last.level === level && this.last.message === message3 && wallTime - this.last.wallTime < 1e3) { this.last.repeat++; this.last.wallTime = wallTime; this.last.args = args; this.notify(); return; } const entry = { seq: this.sequence++, wallTime, scope, level, message: message3, args, repeat: 1 }; this.last = entry; this.history.set(entry.seq, entry); if (this.history.size > this.capacity) this.history.delete(this.history.keys().next().value); if (!this.counts.has(scope)) this.counts.set(scope, { debug: 0, info: 0, warn: 0, error: 0 }); this.counts.get(scope)[level]++; this.notify(); } if (print) this.sink[level]?.(`[${scope}]`, message3, ...args); } logger(scope) { return Object.fromEntries(["debug", "info", "warn", "error"].map((level) => [level, (message3, ...args) => this.write(scope, level, message3, args)])); } records(options) { const { level = "debug", scope, text: text3, count: count2 } = options ?? {}; const search = text3?.toLowerCase(); const entries2 = [...this.history.values()].filter((entry) => LEVELS[entry.level] >= LEVELS[level] && (!scope || wildcard(scope, entry.scope)) && (!search || entry.message.toLowerCase().includes(search) || entry.scope.toLowerCase().includes(search))); if (count2 === void 0) return entries2; return count2 <= 0 ? [] : entries2.slice(-count2); } clear() { this.history.clear(); this.counts.clear(); this.last = null; this.notify(); } subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); } config() { return { capture: this.rules.capture.map((rule) => ({ ...rule })), console: this.rules.console.map((rule) => ({ ...rule })), paused: this.paused }; } }; var store = new LogStore(); var createLogger = (scope) => store.logger(scope); // src/renderer/khaos/core/localeRuntime.js var INTERFACE_LANGUAGES = Object.freeze(["fr", "en", "es"]); var isInterfaceLanguage = (value) => INTERFACE_LANGUAGES.includes(value); var tags = Object.freeze({ fr: "fr-FR", en: "en-GB", es: "es-ES" }); var constructors = { number: Intl.NumberFormat, date: Intl.DateTimeFormat, plural: Intl.PluralRules, collator: Intl.Collator }; var IntlFormatterPool = class { entries = /* @__PURE__ */ new Map(); constructor(capacity = 128) { this.capacity = capacity; } key(kind, locale, options) { if (options === void 0) return JSON.stringify([kind, locale]); if (options === null || typeof options !== "object") return null; const prototype = Object.getPrototypeOf(options); if (prototype !== Object.prototype && prototype !== null) return null; const descriptors = Object.getOwnPropertyDescriptors(options), entries2 = []; for (const name of Object.keys(descriptors).sort()) { const property = descriptors[name]; if (!Object.hasOwn(property, "value")) return null; const value = property.value; if (value === void 0) continue; if (value !== null && !["string", "number", "boolean"].includes(typeof value) || typeof value === "number" && !Number.isFinite(value)) return null; entries2.push([name, value]); } return JSON.stringify([kind, locale, entries2]); } get(kind, locale, options) { const key = this.key(kind, locale, options); if (key !== null && this.entries.has(key)) { const formatter2 = this.entries.get(key); this.entries.delete(key); this.entries.set(key, formatter2); return formatter2; } const formatter = new constructors[kind](locale, options); if (key !== null && this.capacity > 0) { this.entries.set(key, formatter); while (this.entries.size > this.capacity) this.entries.delete(this.entries.keys().next().value); } return formatter; } }; var LocaleRuntime = class { language = "fr"; observers = /* @__PURE__ */ new Set(); revision = 0; constructor({ pool = new IntlFormatterPool(), logger = createLogger("KhaosLocale") } = {}) { this.pool = pool; this.logger = logger; } getLanguage() { return this.language; } localeTag() { return tags[this.language]; } setLanguage(value) { if (Object.is(value, this.language)) return; this.language = value; const revision = ++this.revision; for (const observer of [...this.observers]) { if (revision !== this.revision) break; try { observer(); } catch (error) { try { this.logger.warn("Language observer failed", { error }); } catch { } } } } subscribeLanguage(observer) { this.observers.add(observer); return () => this.observers.delete(observer); } pluralCategory(count2) { return this.pool.get("plural", this.localeTag()).select(count2); } formatNumber(value, options) { return this.pool.get("number", this.localeTag(), options).format(value); } formatDateTime(value, options) { return this.pool.get("date", this.localeTag(), options).format(value); } compareText(left, right) { return this.pool.get("collator", this.localeTag()).compare(left, right); } }; var localeRuntime = new LocaleRuntime(); var getLanguage = localeRuntime.getLanguage.bind(localeRuntime); var setLanguage = localeRuntime.setLanguage.bind(localeRuntime); var subscribeLanguage = localeRuntime.subscribeLanguage.bind(localeRuntime); var localeTag = localeRuntime.localeTag.bind(localeRuntime); var formatNumber = localeRuntime.formatNumber.bind(localeRuntime); var formatDateTime = localeRuntime.formatDateTime.bind(localeRuntime); var compareText = localeRuntime.compareText.bind(localeRuntime); // src/renderer/khaos/ui/tableSort.js var TABLE_SORTS_OPTION = "khaosTableSorts"; var DIRECTIONS = /* @__PURE__ */ new Set(["ascending", "descending"]); var TABLE_KEY = /^[a-z][\w.-]{0,63}$/iu; var MAX_TABLES = 100; var record = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var columnValue = (value) => typeof value === "string" && value.length > 0 && value.length <= 64 || Number.isSafeInteger(value); function readStoredSort(value) { if (!record(value) || !columnValue(value.column) || !DIRECTIONS.has(value.direction)) return void 0; return { column: value.column, direction: value.direction }; } function normalizeTableSorts(value) { const result = {}; if (!record(value)) return result; for (const [key, item] of Object.entries(value)) { const sort = TABLE_KEY.test(key) ? readStoredSort(item) : void 0; if (sort === void 0) continue; result[key] = sort; if (Object.keys(result).length === MAX_TABLES) break; } return result; } function sortShape(columnField, directionField, { flag, values = ["ascending", "descending"] } = {}) { const [ascendingValue, descendingValue] = values; return { encode(state) { if (!record(state) || !columnValue(state[columnField])) return null; const raw = state[directionField]; const descending = flag === "descending" ? raw === true : flag === "ascending" ? raw === false : raw === descendingValue; return { column: state[columnField], direction: descending ? "descending" : "ascending" }; }, decode(stored, fallback) { const descending = stored.direction === "descending"; const direction = flag === "descending" ? descending : flag === "ascending" ? !descending : descending ? descendingValue : ascendingValue; return { ...record(fallback) ? fallback : {}, [columnField]: stored.column, [directionField]: direction }; } }; } var COLUMN_DESCENDING = sortShape("column", "descending", { flag: "descending" }); var COLUMN_DIRECTION = sortShape("column", "direction"); var FIELD_DIRECTION = sortShape("field", "direction"); var KEY_DIRECTION = sortShape("key", "direction"); // src/renderer/khaos/smithmagic/hiddenStats.js var HIDDEN_STATS_OPTION = "khaosSmithmagicHiddenStats"; var TYPE_KEY = /^(t|g)\d{1,9}$/u; var MAX_TYPES = 200; var MAX_ACTIONS = 64; var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var actionId = (value) => Number.isSafeInteger(value) && value > 0; function normalizeHiddenStats(value) { const types = {}; const input = record2(value) && record2(value.types) ? value.types : {}; for (const [key, actions] of Object.entries(input)) { if (!TYPE_KEY.test(key) || !Array.isArray(actions)) continue; const ids = [...new Set(actions.filter(actionId))].slice(0, MAX_ACTIONS); if (ids.length === 0) continue; types[key] = ids; if (Object.keys(types).length === MAX_TYPES) break; } return { types, expanded: record2(value) && value.expanded === true }; } // src/renderer/khaos/itemTooltip/hoverDelay.js var ITEM_TOOLTIP_DELAY_OPTION = "tooltipShowDelayMs"; var ITEM_TOOLTIP_DELAYS_MS = Object.freeze([0, 400, 1e3, 1500, 2e3]); var DEFAULT_ITEM_TOOLTIP_DELAY_MS = 400; var RESHOW_WINDOW_MS = 300; function itemTooltipDelayMs(value) { return ITEM_TOOLTIP_DELAYS_MS.includes(value) ? value : DEFAULT_ITEM_TOOLTIP_DELAY_MS; } function createReshowTracker(now = () => performance.now()) { const showing = /* @__PURE__ */ new Set(); let closedAt = Number.NEGATIVE_INFINITY; return { set(source, isShowing) { if (isShowing) { showing.add(source); } else if (showing.delete(source)) { closedAt = now(); } }, isWarm() { return showing.size > 0 || now() - closedAt < RESHOW_WINDOW_MS; } }; } var hoverTooltipWarmth = createReshowTracker(); // src/renderer/khaos/banner/orientation.js var BANNER_MENU_PROFILE_FIELD = "khaosBannerMenu"; function normalizeBannerMenuOptions(value) { if (value === null || typeof value !== "object" || value.horizontal !== true) return void 0; const width = value.verticalWidth; return typeof width === "number" && Number.isFinite(width) && width > 0 ? { horizontal: true, verticalWidth: width } : { horizontal: true }; } // src/renderer/khaos/settings/normalizeSettings.js var record3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var finite = (value) => typeof value === "number" && Number.isFinite(value); var integerIds = (value) => Array.isArray(value) ? [...new Set(value.filter(finite).map(Math.trunc))] : []; var entries = (value) => record3(value) ? Object.entries(value) : []; var filteredRecord = (value, convert) => Object.fromEntries(entries(value).flatMap(([key, item]) => { const result = convert(item, key); return result === void 0 ? [] : [[key, result]]; })); var typedRecord = (value, kind) => filteredRecord(value, (item) => typeof item === kind ? item : void 0); var boolOr = (value, fallback) => typeof value === "boolean" ? value : fallback; var numberOr = (value, fallback) => finite(value) ? value : fallback; var boundedNumber = (value, fallback) => finite(value) && value >= 0 ? value : fallback; function normalizeBindings(value, migrateMount = false) { const result = filteredRecord(value, (item, key) => { if (!key || !record3(item) || typeof item.code !== "string" || typeof item.label !== "string") return void 0; return Object.fromEntries([ ["code", item.code], ["label", item.label], ...["ctrl", "alt", "shift", "meta"].filter((name) => typeof item[name] === "boolean").map((name) => [name, item[name]]) ]); }); if (migrateMount && Object.hasOwn(result, "openMount")) { if (!Object.hasOwn(result, "openBreeding")) result.openBreeding = result.openMount; delete result.openMount; } return result; } function normalizedAccounts(value, convert) { const pairs = []; for (const [key, item] of entries(value)) { let id; try { id = accountKey(key); } catch { continue; } const profile = convert(item); if (profile !== void 0) pairs.push([id, profile]); } return Object.fromEntries(pairs); } function shortcutMigration(input) { const current = Number.isSafeInteger(input.shortcutProfileMigrationVersion) ? input.shortcutProfileMigrationVersion : null; const oldBindingVersion = Number.isSafeInteger(input.shortcutBindingsMigrationVersion) ? input.shortcutBindingsMigrationVersion : null; const legacy = ["shortcutBindingsByAccount", "shortcutBindingsMigrationVersion"].some((key) => Object.hasOwn(input, key)) || Object.hasOwn(input.options ?? {}, "keybindings"); const pending = current === null ? legacy || Object.hasOwn(input, "pendingShortcutBindingsMigration") : current < shortcutProfileVersion; const migrateMount = oldBindingVersion === null || oldBindingVersion < 2; const oldProfiles = pending ? normalizedAccounts( input.shortcutBindingsByAccount, (bindings) => ({ layoutId: defaultLayoutId, bindings: normalizeBindings(bindings, migrateMount) }) ) : {}; const newProfiles = normalizedAccounts(input.shortcutProfilesByAccount, (item) => record3(item) && isKeyboardLayout(item.layoutId) && item.bindings !== void 0 ? { layoutId: item.layoutId, bindings: normalizeBindings(item.bindings) } : void 0); return { shortcutProfilesByAccount: { ...oldProfiles, ...newProfiles }, shortcutProfileMigrationVersion: pending ? 0 : shortcutProfileVersion, pendingShortcutBindingsMigration: !pending || input.pendingShortcutBindingsMigration === null ? null : normalizeBindings(input.pendingShortcutBindingsMigration === void 0 ? input.options?.keybindings : input.pendingShortcutBindingsMigration, migrateMount) }; } function normalizeDockAnchor(value) { if (!record3(value)) return void 0; if (["start", "end", "center"].includes(value.kind) && finite(value.offset)) return { kind: value.kind, offset: value.offset }; if (value.kind === "ratio" && finite(value.centerRatio)) return { kind: "ratio", centerRatio: value.centerRatio }; return void 0; } function normalizePanels(value) { return filteredRecord(value, (panel) => { if (!record3(panel) || !["x", "y", "width", "height"].every((key) => finite(panel[key]))) return void 0; const horizontal = normalizeDockAnchor(panel.dock?.horizontal), vertical = normalizeDockAnchor(panel.dock?.vertical); const result = { x: panel.x, y: panel.y, width: panel.width, height: panel.height, collapsed: boolOr(panel.collapsed, false), viewportWidth: finite(panel.viewportWidth) ? panel.viewportWidth : void 0, viewportHeight: finite(panel.viewportHeight) ? panel.viewportHeight : void 0, dock: horizontal && vertical ? { horizontal, vertical } : void 0 }; if (panel.khaosPlaced === true) result.khaosPlaced = true; return result; }); } function normalizeHudLayout(value, panels) { const profiles2 = (record3(value) && Array.isArray(value.profiles) ? value.profiles : []).flatMap((item) => { if (!record3(item) || typeof item.id !== "string" || typeof item.name !== "string") return []; const visibility = Object.fromEntries(entries(item.visibility).filter(([name, state]) => typeof item.interfaceHidden === "boolean" || !["mapInfo", "spells", "party", "treasureHunt", "multiAccount"].includes(name) || state !== false)); const profile = { id: item.id, name: item.name, panels: normalizePanels(item.panels), visibility, modulesLocked: boolOr(item.modulesLocked, false), interfaceHidden: boolOr(item.interfaceHidden, false), iconKey: typeof item.iconKey === "string" ? item.iconKey : void 0 }; const bannerMenu = normalizeBannerMenuOptions(item[BANNER_MENU_PROFILE_FIELD]); if (bannerMenu !== void 0) profile[BANNER_MENU_PROFILE_FIELD] = bannerMenu; return [profile]; }); if (!profiles2.length) return defaultHudLayout(panels); const ids = new Set(profiles2.map((item) => item.id)); let combatProfileId = ids.has(value.combatProfileId) ? value.combatProfileId : null; if (value.khaosCombatProfileReleased !== true && profiles2.find((item) => item.id === combatProfileId)?.name === "Combat") { combatProfileId = null; } return { profiles: profiles2, activeProfileId: ids.has(value.activeProfileId) ? value.activeProfileId : profiles2[0].id, combatProfileId, khaosCombatProfileReleased: true }; } var trackId = (value) => typeof value === "string" && /^[\da-f]{32}$/u.test(value); function musicPlaylists(value) { const result = [], seen = /* @__PURE__ */ new Set(); for (const item of Array.isArray(value) ? value : []) { if (!record3(item) || typeof item.id !== "string" || !item.id || seen.has(item.id) || typeof item.name !== "string" || !item.name.trim() || !Array.isArray(item.trackGuids)) continue; seen.add(item.id); result.push({ id: item.id, name: item.name.slice(0, 60), trackGuids: item.trackGuids.filter(trackId).slice(0, 500) }); if (result.length === 100) break; } return result; } function favoriteAlterations(value) { if (!Array.isArray(value) || value.length > alterationFavoriteLimit || value.some((id) => !Number.isSafeInteger(id) || id < 0) || new Set(value).size !== value.length) return []; return value.slice(); } var hardDefaults = [ "combatShowStateTurnCounter", "combatSpectatorAutoFighterInfo", "combatHideFullLifeBars", "combatShowAlignmentWings", "combatPersistentTargetTooltips", "combatAnimatePreviewTooltips", "combatTooltipHealthGauge", "useNewTacticalMode", "forceDefaultTacticalModeTemplate" ]; function normalizeOptions(value) { const input = record3(value) ? value : {}; const result = Object.fromEntries(Object.entries(input).filter(([name]) => !["keybindings", "youtubeEntries"].includes(name))); const output = { ...structuredClone(optionDefaults), ...result }; output.graphicsPreset = ["low", "medium", "high"].includes(input.graphicsPreset) ? input.graphicsPreset : null; for (const name of ["combatTacticalMode", "combatShowBossHealthBar", "gameHdvAvailableOnly", "menuMusicMuted"]) output[name] = boolOr(input[name], optionDefaults[name]); output.hideDeadFighters = (input.timelineDeadVisibilityDefaultsVersion ?? 0) < 1 ? optionDefaults.hideDeadFighters : boolOr(input.hideDeadFighters, optionDefaults.hideDeadFighters); if ((input.khaosChatSoundDefaultsVersion ?? 0) < 1) { for (const name of ["chatPrivateMessageSound", "chatGuildSound", "chatGroupSound"]) output[name] = optionDefaults[name]; } if ((input.khaosRoleplayTacticalResetVersion ?? 0) < 1) output.tacticalMode = optionDefaults.tacticalMode; if ((input.khaosCreatureLimitDefaultsVersion ?? 0) < 1) output.creatureLimit = optionDefaults.creatureLimit; for (const name of hardDefaults) output[name] = optionDefaults[name]; for (const name of [ "timelineDeadVisibilityDefaultsVersion", "khaosChatSoundDefaultsVersion", "khaosCreatureLimitDefaultsVersion", "khaosRoleplayTacticalResetVersion", "tacticalDefaultsVersion", "khaosThemeDefaultsVersion", "audioDefaultsVersion", "notificationDefaultsVersion" ]) output[name] = optionDefaults[name]; output.musicVolume = input.audioDefaultsVersion === void 0 && input.musicVolume === 1 ? optionDefaults.musicVolume : numberOr(input.musicVolume, optionDefaults.musicVolume); output.sfxVolume = (input.audioDefaultsVersion === void 0 || input.audioDefaultsVersion < 3) && input.sfxVolume === 1 ? optionDefaults.sfxVolume : numberOr(input.sfxVolume, optionDefaults.sfxVolume); output.dofus3Theme = (input.khaosThemeDefaultsVersion ?? 0) < 1 ? optionDefaults.dofus3Theme : input.dofus3Theme ?? optionDefaults.dofus3Theme; output.internalNotificationCorner = (input.notificationDefaultsVersion ?? 0) < 3 && ["bottom-right", "top-left"].includes(input.internalNotificationCorner) ? optionDefaults.internalNotificationCorner : input.internalNotificationCorner ?? optionDefaults.internalNotificationCorner; output.chatFontSize = [14, 16, 18].includes(input.chatFontSize) ? input.chatFontSize : optionDefaults.chatFontSize; output.interfaceLanguage = isInterfaceLanguage(input.interfaceLanguage) ? input.interfaceLanguage : optionDefaults.interfaceLanguage; output.fpsLimit = boundedNumber(input.fpsLimit, optionDefaults.fpsLimit); output.backgroundFpsLimit = boundedNumber(input.backgroundFpsLimit, optionDefaults.backgroundFpsLimit); output.freezeStaticAnimations = boolOr(input.freezeStaticAnimations, output.graphicsPreset === "low"); output.environmentEffectsAuto = boolOr(input.environmentEffectsAuto, input.environmentEffectsEnabled !== false); output.experienceBarVisibleJobIds = integerIds(input.experienceBarVisibleJobIds).filter((id) => professionIds.has(id)); output.experienceBarVisibleSpecialGauges = [...new Set(Array.isArray(input.experienceBarVisibleSpecialGauges) ? input.experienceBarVisibleSpecialGauges.filter((id) => specialGauges.includes(id)) : [])]; output.experienceBarColors = filteredRecord(input.experienceBarColors, (color) => { if (typeof color !== "string") return void 0; const hex = color.startsWith("#") ? color : `#${color}`; return /^#[\da-f]{6}$/iu.test(hex) ? hex.toUpperCase() : void 0; }); output.alterationFavoriteIds = favoriteAlterations(input.alterationFavoriteIds); output.musicPlaylists = musicPlaylists(input.musicPlaylists); output.musicFavoriteGuids = [...new Set(Array.isArray(input.musicFavoriteGuids) ? input.musicFavoriteGuids.filter(trackId) : [])].slice(0, 500); output.questListManualHeight = numberOr(input.questListManualHeight, optionDefaults.questListManualHeight); output.gameHdvBuySortByCategory = Object.fromEntries(Object.entries(optionDefaults.gameHdvBuySortByCategory).map(([name, fallback]) => { const sort = input.gameHdvBuySortByCategory?.[name]; return [name, record3(sort) && ["name", "level", "price"].includes(sort.column) && typeof sort.ascending === "boolean" ? { column: sort.column, ascending: sort.ascending } : { ...fallback }]; })); output[TABLE_SORTS_OPTION] = normalizeTableSorts(input[TABLE_SORTS_OPTION]); output[HIDDEN_STATS_OPTION] = normalizeHiddenStats(input[HIDDEN_STATS_OPTION]); output[ITEM_TOOLTIP_DELAY_OPTION] = itemTooltipDelayMs(input[ITEM_TOOLTIP_DELAY_OPTION]); return output; } function normalizeSettings(value) { const defaults = createDefaultSettings(); if (!record3(value)) return defaults; const result = { ...defaults, ...Object.fromEntries(Object.entries(value).filter(([name]) => !["shortcutBindingsByAccount", "shortcutBindingsMigrationVersion", "assetInstallMode"].includes(name))) }; result.options = normalizeOptions(value.options); Object.assign(result, shortcutMigration(value)); result.panels = normalizePanels(value.panels); result.hudLayout = normalizeHudLayout(value.hudLayout, result.panels); result.windowOffsets = filteredRecord(value.windowOffsets, (item) => record3(item) && finite(item.x) && finite(item.y) ? { x: item.x, y: item.y } : void 0); result.bannerMenuOrder = [...new Set(Array.isArray(value.bannerMenuOrder) ? value.bannerMenuOrder.filter((name) => typeof name === "string").map((name) => name === "mount" ? "paddock" : name) : [])]; result.characterSheetStateByCharacter = filteredRecord(value.characterSheetStateByCharacter, (item) => record3(item) ? { favoriteCharacteristicIds: integerIds(item.favoriteCharacteristicIds), openedCategoryIds: integerIds(item.openedCategoryIds) } : void 0); result.questFlagVisibilityByCharacter = filteredRecord(value.questFlagVisibilityByCharacter, (item) => record3(item) ? typedRecord(item, "boolean") : void 0); result.shortcutCategoryEnabledByCharacter = filteredRecord(value.shortcutCategoryEnabledByCharacter, (item, key) => { const ids = /^a([1-9]\d*):c([1-9]\d*)$/u.exec(key); return ids && ids.slice(1).every((id) => Number.isSafeInteger(Number(id))) && record3(item) ? Object.fromEntries(Object.entries(item).filter(([name, state]) => categoryIds.has(name) && typeof state === "boolean")) : void 0; }); result.hiddenQuestsByCharacter = filteredRecord(value.hiddenQuestsByCharacter, (item) => Array.isArray(item) ? item.filter(finite) : void 0); for (const name of ["spellbookShowAllObtentionLevels", "fightResultExpanded", "chatMaximized"]) result[name] = boolOr(value[name], defaults[name]); for (const name of ["chatHeightNormal", "chatHeightMaximized"]) result[name] = numberOr(value[name], defaults[name]); result.predownloadSpeedProfile = ["eco", "balanced", "max"].includes(value.predownloadSpeedProfile) ? value.predownloadSpeedProfile : "eco"; result.minimapOpenedSuperAreas = Array.isArray(value.minimapOpenedSuperAreas) ? value.minimapOpenedSuperAreas.slice() : []; result.chatAwayMessageHistory = Array.isArray(value.chatAwayMessageHistory) ? value.chatAwayMessageHistory.filter((item) => typeof item === "string") : []; const multi = defaults.multiAccount; if (record3(value.multiAccount)) { for (const name of ["globalScope", "autoSwitchOnTurn", "flashOnTurn", "showDock"]) multi[name] = boolOr(value.multiAccount[name], multi[name]); if (Array.isArray(value.multiAccount.slotShortcuts)) multi.slotShortcuts = value.multiAccount.slotShortcuts.filter((item) => typeof item === "string" && item.length > 0); } result.multiAccount = multi; for (const name of [ "hudHpDisplayModes", "lastServerByAccount", "actionBarStateByCharacter", "taxiStateByCharacter", "minimapCustomMarkersByCharacter", "minimapCameraByWorld", "chatTabsByCharacter", "chatDetachedTabsByCharacter", "chatCombatTabByCharacter" ]) { result[name] = record3(value[name]) ? Object.fromEntries(Object.entries(value[name])) : {}; } return result; } // src/electron/khaos/desktopSettings.js var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var modifiers = ["ctrl", "alt", "shift", "meta"]; var bindingFields = /* @__PURE__ */ new Set(["code", "label", ...modifiers]); function validBindings(value) { return object(value) && Object.entries(value).every(([action, binding]) => action.length > 0 && object(binding) && typeof binding.code === "string" && typeof binding.label === "string" && Object.keys(binding).every((field) => bindingFields.has(field)) && modifiers.every((field) => !Object.hasOwn(binding, field) || typeof binding[field] === "boolean")); } function settingsRecordPatch(key, patch) { if (!object(patch)) throw new Error("Settings patch requires a record"); if (!["lastServerByAccount", "shortcutProfilesByAccount", "shortcutCategoryEnabledByCharacter"].includes(key)) { throw new Error(`Cannot merge settings field ${String(key)}`); } const pairs = []; for (const [id, value] of Object.entries(patch)) { if (key === "shortcutCategoryEnabledByCharacter") { const match = /^a([1-9]\d*):c([1-9]\d*)$/u.exec(id); if (!match || !match.slice(1).every((part) => Number.isSafeInteger(Number(part))) || !object(value) || !Object.entries(value).every(([category2, enabled]) => categoryIds.has(category2) && typeof enabled === "boolean")) { throw new Error("Invalid character shortcut categories"); } pairs.push([id, structuredClone(value)]); } else { const normalized = accountKey(id); if (key === "lastServerByAccount" ? typeof value !== "string" : !object(value) || !isKeyboardLayout(value.layoutId) || !validBindings(value.bindings)) { throw new Error(`Invalid value for ${key}`); } pairs.push([normalized, structuredClone(value)]); } } return Object.fromEntries(pairs); } async function writeSettingsFile(filename, value, { files: files6 = import_promises.default, token: token2 = import_node_crypto.randomUUID, wait: wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) } = {}) { await files6.mkdir(import_node_path2.default.dirname(filename), { recursive: true }); const temporary = `${filename}.${token2()}.tmp`; let handle; let ownsTemporary = false; try { handle = await files6.open(temporary, "wx", 384); ownsTemporary = true; await handle.writeFile(JSON.stringify(value, null, 2), "utf8"); await handle.sync(); await handle.close(); handle = null; for (let attempt = 0; ; attempt++) { try { await files6.rename(temporary, filename); break; } catch (error) { if (attempt === 19 || !["EPERM", "EBUSY"].includes(error?.code)) throw error; await wait2(50); } } } finally { if (handle) await handle.close().catch(() => { }); if (ownsTemporary) await files6.rm(temporary, { force: true }).catch(() => { }); } } var DesktopSettings = class { constructor({ filename, files: files6 = import_promises.default, persist = writeSettingsFile } = {}) { this.filename = filename; this.files = files6; this.persist = persist; this.current = null; this.loading = null; this.writes = Promise.resolve(); this.ipcHosts = /* @__PURE__ */ new WeakSet(); } path() { return typeof this.filename === "function" ? this.filename() : this.filename; } option(name) { return this.current?.options?.[name]; } async readSnapshot() { if (this.current) return this.current; if (!this.loading) { this.loading = (async () => { let initial; try { initial = normalizeSettings(JSON.parse(await this.files.readFile(this.path(), "utf8"))); } catch { initial = createDefaultSettings(); } this.current = initial; return initial; })().finally(() => { this.loading = null; }); } return this.loading; } async load() { await this.writes; return structuredClone(await this.readSnapshot()); } mutate(operation) { const run = this.writes.then(async () => { const previous = structuredClone(await this.readSnapshot()); const next = normalizeSettings(operation(previous)); await this.persist(this.path(), next, { files: this.files }); this.current = next; return structuredClone(next); }); this.writes = run.catch(() => { }); return run; } saveKey(key, value) { if (typeof key !== "string" || !key.length) return Promise.reject(new Error("Settings field name is required")); const captured = structuredClone(value); return this.mutate((settings) => Object.fromEntries([...Object.entries(settings).filter(([name]) => name !== key), [key, captured]])); } mergeRecord(key, patch) { const captured = settingsRecordPatch(key, patch); return this.mutate((settings) => ({ ...settings, [key]: { ...settings[key], ...captured } })); } async bindAccount(id, layout) { const key = accountKey(id); if (!isKeyboardLayout(layout)) throw new Error("Unknown keyboard layout"); let profile; await this.mutate((settings) => { profile = settings.shortcutProfilesByAccount[key] ?? { layoutId: layout, bindings: {} }; if (settings.shortcutProfileMigrationVersion >= shortcutProfileVersion) return settings; profile = { layoutId: profile.layoutId, bindings: Object.fromEntries([...Object.entries(settings.pendingShortcutBindingsMigration ?? {}), ...Object.entries(profile.bindings)]) }; settings.shortcutProfilesByAccount[key] = profile; settings.shortcutProfileMigrationVersion = shortcutProfileVersion; settings.pendingShortcutBindingsMigration = null; return settings; }); return structuredClone(profile); } installIpc(ipc, { onMultiAccount } = {}) { if (this.ipcHosts.has(ipc)) return; this.ipcHosts.add(ipc); const actions = { load: () => this.load(), "merge-record-key": async (_event, key, patch) => { await this.mergeRecord(key, patch); }, "bind-shortcut-account": (_event, account, layout) => this.bindAccount(account, layout), "save-key": async (_event, key, value) => { const saved = await this.saveKey(key, value); if (key === "multiAccount") onMultiAccount?.(saved.multiAccount); } }; for (const [method, action] of Object.entries(actions)) ipc.handle(`desktop:settings:${method}`, action); } }; // src/electron/khaos/gameDataLocation.js var import_promises3 = __toESM(require("node:fs/promises"), 1); var import_node_path4 = __toESM(require("node:path"), 1); var import_node_crypto2 = require("node:crypto"); // src/electron/khaos/gameDataInstall.js var import_promises2 = __toESM(require("node:fs/promises"), 1); var import_node_path3 = __toESM(require("node:path"), 1); var INSTALL_STATE_FILE = "khaos-install-state.json"; var FIRST_DOWNLOAD_BYTES = 8 * 1073741824; var STATE_FORMAT = "khaos-game-data-install"; var RECEIPT_FORMAT = "khaos-required-assets-complete"; var DATA_DIRECTORIES = /* @__PURE__ */ new Set(["blobs", "packs", "sources", "asset-cache-invalidations"]); var DATA_FILES = /* @__PURE__ */ new Set(["sources.json", "asset-cache-generation.json", ".asset-completion.lock", INSTALL_STATE_FILE]); var TEMPORARY = /^(?:sources\.json|asset-cache-generation\.json|khaos-install-state\.json)\.(?:khaos-)?[0-9a-f-]{36}\.tmp$/u; var PROBE = /^\.khaos-write-test-[0-9a-f-]{36}$/u; function isKhaosDataEntry(name, directory) { return directory ? DATA_DIRECTORIES.has(name) : DATA_FILES.has(name) || TEMPORARY.test(name) || PROBE.test(name); } async function subdirectories(directory, io) { try { return (await io.readdir(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink()).map((entry) => entry.name); } catch { return []; } } async function readInstallState(root, { io = import_promises2.default } = {}) { try { const value = JSON.parse(await io.readFile(import_node_path3.default.join(root, INSTALL_STATE_FILE), "utf8")); if (value?.format !== STATE_FORMAT || value.version !== 1 || !["installing", "complete"].includes(value.state)) return null; return { state: value.state, chosen: value.chosen === true }; } catch { return null; } } async function hasRequiredReceipt(root, { io = import_promises2.default } = {}) { const sources = import_node_path3.default.join(root, "sources"); for (const key of await subdirectories(sources, io)) { const receipts = import_node_path3.default.join(sources, key, "install-receipts"); for (const profile of await subdirectories(receipts, io)) { let names = []; try { names = await io.readdir(import_node_path3.default.join(receipts, profile)); } catch { continue; } for (const name of names) { if (!/^[0-9a-f]{64}\.json$/u.test(name)) continue; try { if (JSON.parse(await io.readFile(import_node_path3.default.join(receipts, profile, name), "utf8"))?.format === RECEIPT_FORMAT) return true; } catch { } } } } return false; } async function installStatus(root, { io = import_promises2.default } = {}) { let entries2; try { entries2 = await io.readdir(root, { withFileTypes: true }); } catch (error) { if (error?.code === "ENOENT") return { state: "absent", chosen: false }; throw error; } const recorded = await readInstallState(root, { io }); if (recorded?.state === "complete") return { state: "complete", chosen: recorded.chosen }; if (!recorded && await hasRequiredReceipt(root, { io })) return { state: "complete", chosen: false }; const downloaded = entries2.some((entry) => !(entry.isFile() && (entry.name === INSTALL_STATE_FILE || PROBE.test(entry.name)))); return { state: downloaded ? "partial" : "empty", chosen: recorded?.chosen === true }; } async function dataBytes(root, { io = import_promises2.default, budgetMs = 4e3, now = Date.now } = {}) { const deadline = now() + budgetMs; let bytes = 0, exact = true; const visit = async (directory) => { let entries2; try { entries2 = await io.readdir(directory, { withFileTypes: true }); } catch { return; } for (const entry of entries2) { if (now() > deadline) { exact = false; return; } const name = import_node_path3.default.join(directory, entry.name); if (entry.isSymbolicLink()) continue; if (entry.isDirectory()) { await visit(name); if (!exact) return; } else if (entry.isFile()) { try { bytes += (await io.lstat(name)).size; } catch { } } } }; await visit(root); return { bytes, exact }; } async function writeInstallState(root, { state, chosen }, { io = import_promises2.default, persist = writeSettingsFile, now = Date.now } = {}) { if (!["installing", "complete"].includes(state)) throw new Error(`Invalid install state: ${state}`); const keep = chosen ?? (await readInstallState(root, { io }))?.chosen ?? false; await persist(import_node_path3.default.join(root, INSTALL_STATE_FILE), { format: STATE_FORMAT, version: 1, state, chosen: keep === true, updatedAt: new Date(now()).toISOString() }, { files: io }); } async function markInstallComplete(root, options = {}) { const recorded = await readInstallState(root, options); if (recorded?.state === "complete") return false; await writeInstallState(root, { state: "complete", chosen: recorded?.chosen === true }, options); return true; } async function containsLink(directory, io) { for (const entry of await io.readdir(directory, { withFileTypes: true })) { if (entry.isSymbolicLink()) return true; if (entry.isDirectory() && await containsLink(import_node_path3.default.join(directory, entry.name), io)) return true; } return false; } async function removeAbandonedData(root, { io = import_promises2.default, paths = locationPaths(), keep = [] } = {}) { root = paths.checked(root); if (import_node_path3.default.basename(root).toLowerCase() !== "khaosgame") throw new Error(`Not a game data folder: ${root}`); const guarded = keep.filter((value) => typeof value === "string" && import_node_path3.default.isAbsolute(value)); for (const other of guarded) if (paths.overlap(root, other)) throw new Error(`Game data cleanup refused: ${root} overlaps ${other}`); let stat4; try { stat4 = await io.lstat(root); } catch (error) { if (error?.code === "ENOENT") return { removed: [], kept: [] }; throw error; } if (!stat4.isDirectory() || stat4.isSymbolicLink()) throw new Error(`Game data folder is not a regular folder: ${root}`); const physical = await io.realpath(root); for (const other of guarded) { let real = other; try { real = await io.realpath(other); } catch { } if (paths.overlap(physical, other) || paths.overlap(physical, real)) throw new Error(`Game data cleanup refused: ${physical} overlaps ${other}`); } const removed = [], kept = []; for (const entry of await io.readdir(root, { withFileTypes: true })) { const name = import_node_path3.default.join(root, entry.name), directory = entry.isDirectory(); if (entry.isSymbolicLink() || !(directory || entry.isFile()) || !isKhaosDataEntry(entry.name, directory) || directory && await containsLink(name, io)) { kept.push(entry.name); continue; } await io.rm(name, { recursive: directory, force: true, maxRetries: 3 }); removed.push(entry.name); } if (!kept.length) { try { await io.rmdir(root); } catch { } } return { removed, kept }; } // src/electron/khaos/gameDataLocation.js var cancelled = () => ({ status: "cancelled" }); var parentWindow = (window) => window && !window.isDestroyed() ? window : null; var formatStorageBytes = (bytes) => `${(bytes / 1073741824).toFixed(1).replace(".", ",")} Go`; function locationPaths(paths = import_node_path4.default, platform = process.platform) { const key = (value) => { if (typeof value !== "string" || !paths.isAbsolute(value)) throw new Error("Game data requires an absolute directory"); const resolved = paths.resolve(value); return platform === "win32" ? resolved.toLowerCase() : resolved; }; const within = (base, candidate) => { const distance = paths.relative(key(base), key(candidate)); return distance.length === 0 || !paths.isAbsolute(distance) && distance.split(paths.sep)[0] !== ".."; }; return { same: (left, right) => key(left) === key(right), overlap: (left, right) => within(left, right) || within(right, left), gameDirectory: (selected) => paths.basename(selected).toLowerCase() === "khaosgame" ? selected : paths.join(selected, "KhaosGame"), checked: (value) => { key(value); const resolved = paths.resolve(value); if (resolved === paths.parse(resolved).root) throw new Error("A volume root cannot be used for game data"); return resolved; } }; } async function freeStorageBytes(directory, io = import_promises3.default) { try { const volume = await io.statfs(directory); const bytes = Number(volume.bsize) * Number(volume.bavail); return Number.isSafeInteger(bytes) && bytes >= 0 ? bytes : null; } catch { return null; } } async function directoryState(directory, io) { try { const entry = await io.lstat(directory); if (!entry.isDirectory() || entry.isSymbolicLink()) throw new Error(`Game data directory is not a regular directory: ${directory}`); return true; } catch (error) { if (error?.code === "ENOENT") return false; throw error; } } async function treeEntries(directory, io) { const records = []; async function visit(relative) { for (const entry of await io.readdir(import_node_path4.default.join(directory, relative), { withFileTypes: true })) { const name = import_node_path4.default.join(relative, entry.name); if (entry.isSymbolicLink()) throw new Error(`Game data contains a linked entry: ${name}`); if (entry.isDirectory()) { records.push({ name, directory: true }); await visit(name); } else if (entry.isFile()) records.push({ name, size: (await io.lstat(import_node_path4.default.join(directory, name))).size }); else throw new Error(`Unsupported game data entry: ${name}`); } } await visit(""); return records; } async function fileDigest(filename, io) { const handle = await io.open(filename, "r"); const digest4 = (0, import_node_crypto2.createHash)("sha256"), buffer = Buffer.allocUnsafe(65536); try { for (; ; ) { const { bytesRead } = await handle.read(buffer, 0, buffer.length, null); if (!bytesRead) return digest4.digest("hex"); digest4.update(buffer.subarray(0, bytesRead)); } } finally { await handle.close(); } } async function beginDataRelocation(source, target, { io = import_promises3.default, paths = locationPaths() } = {}) { source = paths.checked(source); target = paths.checked(target); if (paths.overlap(source, target)) throw new Error("Game data directories must be separate"); const present = await directoryState(source, io), destinationPresent = await directoryState(target, io); if (!present) { if (!destinationPresent) throw new Error("Neither game data directory exists"); return { result: "already-moved", finalize: async () => { }, rollback: async () => { } }; } const physicalSource = await io.realpath(source); const physicalTarget = destinationPresent ? await io.realpath(target) : import_node_path4.default.join(await io.realpath(import_node_path4.default.dirname(target)), import_node_path4.default.basename(target)); if (paths.overlap(physicalSource, physicalTarget)) throw new Error("Game data directories overlap through a linked ancestor"); if (destinationPresent && (await io.readdir(target)).length === 0) await io.rmdir(target); if (!await directoryState(target, io)) { try { await io.rename(source, target); return { result: "moved", finalize: async () => { }, rollback: () => io.rename(target, source) }; } catch (error) { if (!["EXDEV", "EPERM", "EACCES"].includes(error?.code)) throw error; } } const inventory = await treeEntries(source, io); await io.mkdir(target, { recursive: true }); for (const entry of inventory) { const original = import_node_path4.default.join(source, entry.name), copied = import_node_path4.default.join(target, entry.name); if (entry.directory) { await directoryState(copied, io); await io.mkdir(copied, { recursive: true }); continue; } try { if (!(await io.lstat(copied)).isFile()) throw new Error(`Destination entry is not a file: ${entry.name}`); } catch (error) { if (error?.code !== "ENOENT") throw error; } await io.copyFile(original, copied); entry.digest = await fileDigest(original, io); if ((await io.lstat(copied)).size !== entry.size || entry.digest !== await fileDigest(copied, io)) { throw new Error(`Game data copy verification failed: ${entry.name}`); } } return { result: "copied", rollback: async () => { }, finalize: async () => { if (!await directoryState(source, io) || await io.realpath(source) !== physicalSource || paths.overlap(source, target)) { throw new Error("Game data source changed before cleanup"); } if (!await directoryState(target, io) || await io.realpath(target) !== physicalTarget) throw new Error("Game data destination changed before cleanup"); const current = await treeEntries(source, io); await treeEntries(target, io); const shape = (list2) => JSON.stringify(list2.map(({ name, directory, size }) => [name, !!directory, size]).sort()); if (shape(current) !== shape(inventory)) throw new Error("Game data inventory changed before cleanup"); for (const entry of inventory.filter((item) => !item.directory)) { if (entry.digest !== await fileDigest(import_node_path4.default.join(source, entry.name), io) || entry.digest !== await fileDigest(import_node_path4.default.join(target, entry.name), io)) throw new Error("Game data changed before cleanup"); } await io.rm(source, { recursive: true, force: false }); } }; } var GameDataLocation = class _GameDataLocation { // `defaultRoot`: where a new install puts its data (installed client: %LOCALAPPDATA%\\KhaosGame, from the // launcher); `setup`: the first-launch step (gameDataSetup.js) that replaces the system message box below. // `programDirectory`: the installed program (never cleaned, never a game data folder). // `downloadBytes`: what a first download fetches (what a partial one still needs is measured against it). constructor({ app, dialog, BrowserWindow, logger = console, io = import_promises3.default, persist = writeSettingsFile, bytes = 12.5 * 1073741824, defaultRoot = null, setup = null, programDirectory = null, downloadBytes = FIRST_DOWNLOAD_BYTES }) { Object.assign(this, { app, dialog, BrowserWindow, logger, io, persist, bytes, setup, programDirectory, downloadBytes }); this.paths = locationPaths(); this.preferredRoot = defaultRoot ? this.validRoot(defaultRoot) : null; this.cleaning = Promise.resolve(); } get rootFile() { return import_node_path4.default.join(this.app.getPath("userData"), "game-data-root.json"); } get planFile() { return import_node_path4.default.join(this.app.getPath("userData"), "game-data-root-relocation.json"); } get cleanupFile() { return import_node_path4.default.join(this.app.getPath("userData"), "game-data-cleanup.json"); } get defaultRoot() { return this.preferredRoot ?? import_node_path4.default.join(this.app.getPath("appData"), "KhaosGame"); } async read(filename) { try { return JSON.parse(await this.io.readFile(filename, "utf8")); } catch (error) { if (error?.code && error.code !== "ENOENT") throw error; return null; } } async message(window, options) { const parent = parentWindow(window); return parent ? this.dialog.showMessageBox(parent, options) : this.dialog.showMessageBox(options); } async pick(window, title) { const parent = parentWindow(window), options = { title, properties: ["openDirectory", "createDirectory", "dontAddToRecent"] }; const answer = await (parent ? this.dialog.showOpenDialog(parent, options) : this.dialog.showOpenDialog(options)); return answer.canceled ? null : answer.filePaths[0] ?? null; } async schedule(current, window) { const selection = await this.pick(window, "Choisir le nouvel emplacement des donn\xE9es de jeu"); if (!selection) return cancelled(); const target = this.paths.gameDirectory(selection); if (this.paths.same(current, target)) return { status: "unchanged", root: current }; if (this.paths.overlap(current, target)) throw new Error("Le nouvel emplacement doit \xEAtre s\xE9par\xE9 du dossier actuel."); if (await directoryState(target, this.io) && (await this.io.readdir(target)).length) throw new Error(`Le dossier n\u2019est pas vide : ${target}`); const probe = import_node_path4.default.join(selection, `.khaos-write-test-${(0, import_node_crypto2.randomUUID)()}`); let handle; try { handle = await this.io.open(probe, "wx"); } finally { if (handle) { await handle.close(); await this.io.unlink(probe); } } const entries2 = await treeEntries(current, this.io), required = entries2.reduce((sum, item) => sum + (item.size ?? 0), 0); const [from, to, free] = await Promise.all([this.io.stat(current), this.io.stat(selection), freeStorageBytes(selection, this.io)]); if (from.dev !== to.dev && free !== null && free < required) throw new Error(`Espace insuffisant : ${formatStorageBytes(required)} requis, ${formatStorageBytes(free)} disponible.`); const detail = [`Dossier actuel : ${current}`, `Destination : ${target}`, `Volume de donn\xE9es : ${formatStorageBytes(required)}`]; if (free !== null) detail.push(`Espace disponible : ${formatStorageBytes(free)}`); detail.push("", "Khaos red\xE9marrera pour d\xE9placer les donn\xE9es avant de lancer le jeu."); const answer = await this.message(window, { type: "question", title: "D\xE9placer les donn\xE9es de jeu", message: "Confirmer le d\xE9placement ?", detail: detail.join("\n"), buttons: ["D\xE9placer et red\xE9marrer", "Annuler"], defaultId: 0, cancelId: 1, noLink: true }); if (answer.response !== 0) return cancelled(); await this.persist(this.planFile, { version: 1, sourceRoot: current, targetRoot: target }, { files: this.io }); return { status: "scheduled", root: target }; } validRoot(value) { try { return this.paths.checked(value); } catch { return null; } } async progress(source, target) { const window = new this.BrowserWindow({ width: 620, height: 300, resizable: false, minimizable: false, maximizable: false, closable: false, show: false, title: "D\xE9placement des donn\xE9es de Khaos", backgroundColor: "#111317", webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } }); const escape = (value) => value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); const html = `

D\xE9placement des donn\xE9es de jeu\u2026

Garde Khaos ouvert pendant le transfert.

${escape(source)}

${escape(target)}

`; try { window.setMenuBarVisibility(false); await window.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`); window.show(); return window; } catch (error) { window.destroy(); throw error; } } async recover(configured) { const value = await this.read(this.planFile); const source = this.validRoot(value?.sourceRoot), target = this.validRoot(value?.targetRoot); if (value?.version !== 1 || !source || !target || this.paths.overlap(source, target)) return configured; const clear = () => this.io.rm(this.planFile, { force: true }); if (configured && this.paths.same(configured, target)) { await clear(); return target; } if (configured && !this.paths.same(configured, source)) { this.logger.error("Ignoring stale game data relocation", { configured, source, target }); await clear(); return configured; } for (; ; ) { let window, transaction; try { window = await this.progress(source, target); transaction = await beginDataRelocation(source, target, { io: this.io, paths: this.paths }); await this.persist(this.rootFile, { root: target }, { files: this.io }); } catch (error) { if (transaction) await transaction.rollback(); window?.destroy(); window = null; this.logger.error("Game data relocation failed", { source, target, message: String(error.message ?? error) }); const answer = await this.message(null, { type: "error", title: "D\xE9placement impossible", message: "Le transfert des donn\xE9es a \xE9chou\xE9.", detail: `${String(error.message ?? error)} Les donn\xE9es originales sont conserv\xE9es. Une copie partielle peut rester dans : ${target}`, buttons: ["R\xE9essayer", "Garder l\u2019ancien emplacement"], defaultId: 0, cancelId: 1, noLink: true }); if (answer.response === 0) continue; if (!await directoryState(source, this.io) && await directoryState(target, this.io)) return target; await clear(); return source; } finally { window?.destroy(); } try { await transaction.finalize(); } catch (error) { this.logger.error("Transferred data retained at original location", { source, message: String(error.message ?? error) }); } await clear(); return target; } } /** * What the folder step needs to know about `root`: { state, chosen, bytes, need, free } (gameDataInstall.js * installStatus; bytes already downloaded, bytes the first download still needs there, free bytes on its drive), * or null when it cannot be read (the start then goes on as before, without the step). */ async inspect(root, { measureComplete = false } = {}) { try { const status = await installStatus(root, { io: this.io }); const measured = status.state === "partial" || measureComplete && status.state === "complete"; const bytes = measured ? (await dataBytes(root, { io: this.io })).bytes : 0; const need = status.state === "complete" ? 0 : Math.max(0, this.downloadBytes - bytes); return { ...status, bytes, need, free: status.state === "absent" ? null : await freeStorageBytes(root, this.io) }; } catch (error) { this.logger.warn("Game data folder check failed", { root, message: String(error?.message ?? error) }); return null; } } /** * Whether the start shows the folder step for a reachable folder (docs/LAUNCH.md section 1): never for a complete * install; for a folder the player confirmed (step, sign-in screen) only when its drive lacks the space still * needed; always for a first download nobody chose (an older client started it in the default folder). */ static needsStep(found) { if (found === null || found.state === "complete") return false; const short = found.free !== null && found.free < found.need; return short || !found.chosen; } /** Records that the player confirmed `root` for an install that is not complete yet. */ async markChosen(root) { try { const status = await installStatus(root, { io: this.io }); if (status.state !== "complete") await writeInstallState(root, { state: "installing", chosen: true }, { io: this.io, persist: this.persist }); } catch (error) { this.logger.warn("Game data install state not written", { root, message: String(error?.message ?? error) }); } } /** Every install stage ended complete in `root` (desktopAssets.js): recorded once. */ async markComplete(root) { try { if (await markInstallComplete(root, { io: this.io, persist: this.persist })) this.logger.info?.("Game data install complete", { root }); } catch (error) { this.logger.warn("Game data install state not written", { root, message: String(error?.message ?? error) }); } } /** Folders a cleanup must never touch: the program, the profile (with the root file) and the Electron app. */ protectedRoots() { const roots = [this.programDirectory, this.app.getPath("userData")]; try { roots.push(this.app.getAppPath?.()); } catch { } return roots.filter((value) => typeof value === "string" && import_node_path4.default.isAbsolute(value)); } /** The abandoned partial download in `root` is removed at the next start (cleanup()), outside the folder in use. */ async scheduleCleanup(root) { const plan = await this.read(this.cleanupFile).catch(() => null); const roots = (Array.isArray(plan?.roots) ? plan.roots : []).filter((entry) => typeof entry?.root === "string" && !this.paths.same(entry.root, root)); roots.push({ root, attempts: 0 }); await this.persist(this.cleanupFile, { version: 1, roots }, { files: this.io }); this.logger.info?.("Abandoned game data scheduled for removal", { root }); } /** * Removes the abandoned partial downloads the player chose to delete (scheduleCleanup), never the folder in use * (`active`) nor one that holds a complete install now; gameDataInstall.js removeAbandonedData only takes the Khaos * asset entries of a KhaosGame folder. A folder that could not be cleaned is tried again at the next starts (3 tries). */ async cleanup(active) { const plan = await this.read(this.cleanupFile).catch(() => null); if (plan === null) return; const left = []; for (const entry of Array.isArray(plan.roots) ? plan.roots : []) { const root = this.validRoot(entry?.root), attempts = Number.isSafeInteger(entry?.attempts) ? entry.attempts : 0; if (!root) continue; try { if (active && this.paths.overlap(root, active)) { this.logger.warn("Abandoned game data kept: it is the folder in use", { root, active }); continue; } if ((await installStatus(root, { io: this.io })).state === "complete") { this.logger.warn("Abandoned game data kept: it holds a complete install", { root }); continue; } const result = await removeAbandonedData(root, { io: this.io, paths: this.paths, keep: [active, ...this.protectedRoots()] }); this.logger.info?.("Abandoned game data removed", { root, ...result }); } catch (error) { this.logger.warn("Abandoned game data cleanup failed", { root, attempts: attempts + 1, message: String(error?.message ?? error) }); if (attempts + 1 < 3) left.push({ root, attempts: attempts + 1 }); } } if (left.length) await this.persist(this.cleanupFile, { version: 1, roots: left }, { files: this.io }); else await this.io.rm(this.cleanupFile, { force: true }); } /** The start goes on with `root`; a pending cleanup runs meanwhile (it never waits for the game). */ started(root) { this.cleaning = this.cleanup(root).catch((error) => this.logger.warn("Abandoned game data cleanup failed", { message: String(error?.message ?? error) })); return root; } /** The step's answer: a folder (older hook) or { root, oldData: "delete" | "move" | null }. */ choice(answer) { if (!answer) return null; const value = typeof answer === "string" ? { root: answer, oldData: null } : answer; return { root: this.paths.checked(value.root), oldData: ["delete", "move"].includes(value.oldData) ? value.oldData : null }; } /** * The sign-in screen's "Change install folder" (and its low-space notice): the folder step on the folder in use. * A complete install moves with the in-game move (relocation plan, restart, recover()); a partial download is * moved the same way or left for cleanup() at the next start, which then uses the new folder. Resolves with * { status: cancelled | unchanged | scheduled (move at restart) | restart (new folder at restart), root }. */ async changeBeforeLogin(current, { window = null, reason = null, neededBytes = null } = {}) { if (!this.setup) return this.schedule(current, window); current = this.paths.checked(current); const found = await this.inspect(current, { measureComplete: true }) ?? { state: "partial", chosen: true, bytes: 0, need: this.bytes, free: null }; const answer = this.choice(await this.setup({ defaultRoot: this.defaultRoot, unavailable: null, bytes: this.bytes, paths: this.paths, mode: "change", reason, parent: window, neededBytes: neededBytes ?? (found.state === "complete" ? null : found.need), current: { root: current, state: found.state, bytes: found.bytes } })); if (!answer) return cancelled(); const target = answer.root; if (this.paths.same(target, current)) { await this.markChosen(current); return { status: "unchanged", root: current }; } if (this.paths.overlap(current, target)) throw new Error("Le nouvel emplacement doit \xEAtre s\xE9par\xE9 du dossier actuel."); if (found.state === "complete" || answer.oldData === "move") { if (found.state !== "complete") await this.markChosen(current); await this.io.mkdir(target, { recursive: true }); await this.persist(this.planFile, { version: 1, sourceRoot: current, targetRoot: target }, { files: this.io }); this.logger.info?.("Game data move scheduled before login", { source: current, target, state: found.state }); return { status: "scheduled", root: target }; } await this.persist(this.rootFile, { root: target }, { files: this.io }); await this.markChosen(target); if (answer.oldData === "delete" || found.state === "empty") await this.scheduleCleanup(current); this.logger.info?.("Game data folder changed before login", { previous: current, root: target, oldData: answer.oldData }); return { status: "restart", root: target }; } // Resolves with the game data folder, or null when the player closed the first-launch step (nothing written then). async initialize({ promptOnFirstRun = false } = {}) { let configured = this.validRoot((await this.read(this.rootFile))?.root); configured = await this.recover(configured); let unavailable = null; if (configured) { try { await this.io.mkdir(configured, { recursive: true }); if (!(promptOnFirstRun && this.setup)) return configured; } catch (error) { this.logger.error("Configured game data is unavailable", { root: configured, message: String(error.message ?? error) }); unavailable = configured; if (promptOnFirstRun && !this.setup) await this.message(null, { type: "warning", title: "Donn\xE9es de jeu inaccessibles", message: "Le dossier configur\xE9 est inaccessible.", detail: `${configured} Choisis un autre dossier pour ret\xE9l\xE9charger les donn\xE9es.`, buttons: ["Continuer"], noLink: true }); } } if (promptOnFirstRun && this.setup) return this.initializeWithStep(configured, unavailable); return this.initializeWithoutStep(configured, promptOnFirstRun); } /** A folder that already holds data and was not saved yet (default folder of an older client): saved, used. */ async adopt(root) { await this.io.mkdir(root, { recursive: true }); await this.persist(this.rootFile, { root }, { files: this.io }); return this.started(root); } /** * The start of an installed client (the launcher's request, launcher/main.cjs): the folder step when no folder holds * a complete install and the player never confirmed one, or when the folder's drive lacks the space the download * still needs (needsStep); an unreachable saved folder gets it too, with its path. Complete installs never see it. * The player's answer for the folder left behind: "delete" (an abandoned partial download, removed by cleanup() * right away, outside the new folder) or "move" (the in-game move's relocation, done here before the game starts). */ async initializeWithStep(configured, unavailable) { let current = unavailable ? null : configured; if (current === null && !unavailable) { if (await directoryState(import_node_path4.default.join(this.app.getPath("userData"), "asset-cache"), this.io)) return this.adopt(this.defaultRoot); current = this.defaultRoot; } const found = current === null ? null : await this.inspect(current); if (current !== null && (found === null || !_GameDataLocation.needsStep(found))) return configured ? this.started(configured) : this.adopt(current); const shown = found !== null && found.state !== "absent" ? { root: current, state: found.state, bytes: found.bytes } : null; const reason = found !== null && found.state !== "absent" && found.free !== null && found.free < found.need ? "space" : found?.state === "partial" ? "partial" : null; this.logger.info?.("Game data folder step", { current, state: found?.state ?? null, chosen: found?.chosen ?? null, bytes: found?.bytes ?? null, free: found?.free ?? null, need: found?.need ?? null, reason, unavailable }); const answer = this.choice(await this.setup({ defaultRoot: this.defaultRoot, unavailable, bytes: this.bytes, paths: this.paths, current: shown, reason, mode: "first", neededBytes: shown ? found.need : null })); if (!answer) return null; const selected = answer.root; const previous = shown && !this.paths.overlap(shown.root, selected) ? shown.root : null; if (previous && answer.oldData === "move" && shown.state === "partial") { await this.io.mkdir(selected, { recursive: true }); await this.persist(this.planFile, { version: 1, sourceRoot: previous, targetRoot: selected }, { files: this.io }); const moved = await this.recover(previous); if (!this.paths.same(moved, selected)) return this.adopt(moved); await this.markChosen(selected); return this.started(selected); } await this.io.mkdir(selected, { recursive: true }); await this.persist(this.rootFile, { root: selected }, { files: this.io }); await this.markChosen(selected); if (previous && (answer.oldData === "delete" || shown.state === "empty")) await this.scheduleCleanup(previous); return this.started(selected); } /** Started without the Khaos step (development runs, older launchers): the default folder or the system box. */ async initializeWithoutStep(configured, promptOnFirstRun) { let selected = this.defaultRoot; const existing = configured === null && (await directoryState(selected, this.io) || await directoryState(import_node_path4.default.join(this.app.getPath("userData"), "asset-cache"), this.io)); if (!existing && promptOnFirstRun) { const free = await freeStorageBytes(this.app.getPath("appData"), this.io); const details = [`Khaos peut t\xE9l\xE9charger ${formatStorageBytes(this.bytes)} de donn\xE9es de jeu.`, "", `Emplacement propos\xE9 : ${selected}`]; if (free !== null) details.push(`Espace libre : ${formatStorageBytes(free)}`); const answer = await this.message(null, { type: "question", title: "Installation de Khaos", message: "Choisir le dossier des donn\xE9es de jeu", detail: details.join("\n"), buttons: ["Emplacement par d\xE9faut", "Choisir un dossier\u2026"], defaultId: 0, cancelId: 0, noLink: true }); if (answer.response === 1) { const picked = await this.pick(null, "Dossier des donn\xE9es de jeu"); if (picked) selected = this.paths.gameDirectory(picked); } } try { await this.io.mkdir(selected, { recursive: true }); } catch (error) { this.logger.error("Selected game data location failed", { root: selected, message: String(error.message ?? error) }); selected = this.defaultRoot; await this.io.mkdir(selected, { recursive: true }); } await this.persist(this.rootFile, { root: selected }, { files: this.io }); return selected; } }; // src/electron/khaos/gameDataSetup.js var import_node_fs = __toESM(require("node:fs"), 1); var import_promises4 = __toESM(require("node:fs/promises"), 1); var import_node_path5 = __toESM(require("node:path"), 1); var import_node_crypto3 = require("node:crypto"); var GiB = 1073741824; var LANGUAGES = [["fr", "Fran\xE7ais"], ["en", "English"], ["es", "Espa\xF1ol"]]; var SETUP_TEXTS = { fr: { unit: "Go", decimal: ",", windowTitle: "Khaos : installation", title: "O\xF9 installer les donn\xE9es du jeu ?", intro: "Au premier lancement, Khaos t\xE9l\xE9charge environ {0} de donn\xE9es de jeu. Rien n\u2019est t\xE9l\xE9charg\xE9 avant votre choix.", need: "Espace n\xE9cessaire : {0}", defaultDrive: "Dossier par d\xE9faut", otherDrive: "Disque {0}", customFolder: "Dossier choisi", free: "{0} libres sur {1}", freeOnly: "{0} libres", freeUnknown: "Espace libre inconnu", notEnough: "Espace insuffisant", choose: "Choisir un autre dossier\u2026", install: "Installer ici", checking: "V\xE9rification\u2026", later: "Vous pourrez d\xE9placer les donn\xE9es plus tard dans les options du jeu.", pickTitle: "Dossier des donn\xE9es de jeu", unavailable: "Le dossier des donn\xE9es de jeu enregistr\xE9 est inaccessible : {0}. Rebranchez ce disque puis relancez Khaos, ou choisissez un autre emplacement.", noSpace: "Il faut au moins {0} libres \xE0 cet endroit ({1} disponibles). Choisissez un autre disque.", notWritable: "Khaos ne peut pas \xE9crire dans ce dossier ({0}). Choisissez-en un autre.", programFolder: "Ce dossier contient le programme Khaos, remplac\xE9 \xE0 chaque mise \xE0 jour. Choisissez-en un autre.", driveRoot: "Choisissez un dossier, pas la racine d\u2019un disque.", failed: "Ce dossier ne peut pas \xEAtre utilis\xE9 : {0}", changeTitle: "Changer le dossier d\u2019installation", changeIntro: "Les donn\xE9es du jeu (environ {0}) peuvent aller sur un autre disque. Khaos red\xE9marre pour utiliser le nouveau dossier.", currentFolder: "Dossier actuel", partialNote: "T\xE9l\xE9chargement inachev\xE9 : {0}", completeNote: "Jeu install\xE9 : {0}", partial: "Le premier t\xE9l\xE9chargement n\u2019est pas termin\xE9 ({0} re\xE7us dans {1}). Vous pouvez le reprendre ici ou choisir un autre dossier.", lowSpace: "Pas assez d\u2019espace sur {0} : il faut encore {1} et seuls {2} sont libres. Choisissez un autre dossier.", spaceFull: "Le disque {0} est plein. Choisissez un autre dossier pour continuer le t\xE9l\xE9chargement.", resume: "Continuer ici", oldTitle: "Et l\u2019ancien t\xE9l\xE9chargement ?", oldPartial: "{0} d\u2019un t\xE9l\xE9chargement inachev\xE9 restent dans {1}. Le supprimer lib\xE8re cette place ; le jeu se t\xE9l\xE9charge dans le nouveau dossier.", deleteOld: "Supprimer et recommencer ici", moveOld: "Le d\xE9placer ici", back: "Retour", moveTitle: "D\xE9placer les donn\xE9es du jeu", moveComplete: "Les donn\xE9es du jeu ({0}) vont \xEAtre d\xE9plac\xE9es de {1} vers {2}. Khaos red\xE9marre pour les d\xE9placer, puis s\u2019ouvre.", moveRestart: "D\xE9placer et red\xE9marrer", notEmpty: "Ce dossier contient d\xE9j\xE0 des fichiers. Choisissez un dossier vide pour y d\xE9placer les donn\xE9es.", overlap: "Choisissez un dossier s\xE9par\xE9 du dossier actuel." }, en: { unit: "GB", decimal: ".", windowTitle: "Khaos: setup", title: "Where should the game files go?", intro: "On its first start, Khaos downloads about {0} of game files. Nothing is downloaded before you choose.", need: "Space needed: {0}", defaultDrive: "Default folder", otherDrive: "Drive {0}", customFolder: "Chosen folder", free: "{0} free of {1}", freeOnly: "{0} free", freeUnknown: "Free space unknown", notEnough: "Not enough space", choose: "Choose another folder\u2026", install: "Install here", checking: "Checking\u2026", later: "You can move the game files later in the game options.", pickTitle: "Game files folder", unavailable: "The saved game files folder cannot be reached: {0}. Plug that drive back in and restart Khaos, or choose another place.", noSpace: "At least {0} must be free here ({1} available). Choose another drive.", notWritable: "Khaos cannot write to this folder ({0}). Choose another one.", programFolder: "This folder holds the Khaos program, which every update replaces. Choose another one.", driveRoot: "Choose a folder, not the root of a drive.", failed: "This folder cannot be used: {0}", changeTitle: "Change install folder", changeIntro: "The game files (about {0}) can go to another drive. Khaos restarts to use the new folder.", currentFolder: "Current folder", partialNote: "Unfinished download: {0}", completeNote: "Installed game: {0}", partial: "The first download did not finish ({0} received in {1}). You can resume it here or choose another folder.", lowSpace: "Not enough space on {0}: {1} more is needed and only {2} is free. Choose another folder.", spaceFull: "Drive {0} is full. Choose another folder to go on with the download.", resume: "Continue here", oldTitle: "What about the old download?", oldPartial: "{0} of an unfinished download are left in {1}. Deleting it frees that space; the game downloads to the new folder.", deleteOld: "Delete it and start here", moveOld: "Move it here", back: "Back", moveTitle: "Move the game files", moveComplete: "The game files ({0}) will be moved from {1} to {2}. Khaos restarts to move them, then opens.", moveRestart: "Move and restart", notEmpty: "This folder already holds files. Choose an empty folder to move the game files to.", overlap: "Choose a folder separate from the current one." }, es: { unit: "GB", decimal: ",", windowTitle: "Khaos: instalaci\xF3n", title: "\xBFD\xF3nde instalar los datos del juego?", intro: "En el primer inicio, Khaos descarga unos {0} de datos del juego. No se descarga nada antes de que elijas.", need: "Espacio necesario: {0}", defaultDrive: "Carpeta predeterminada", otherDrive: "Disco {0}", customFolder: "Carpeta elegida", free: "{0} libres de {1}", freeOnly: "{0} libres", freeUnknown: "Espacio libre desconocido", notEnough: "Espacio insuficiente", choose: "Elegir otra carpeta\u2026", install: "Instalar aqu\xED", checking: "Comprobando\u2026", later: "Podr\xE1s mover los datos m\xE1s tarde en las opciones del juego.", pickTitle: "Carpeta de los datos del juego", unavailable: "No se puede acceder a la carpeta de datos guardada: {0}. Vuelve a conectar ese disco y reinicia Khaos, o elige otro lugar.", noSpace: "Se necesitan al menos {0} libres aqu\xED ({1} disponibles). Elige otro disco.", notWritable: "Khaos no puede escribir en esta carpeta ({0}). Elige otra.", programFolder: "Esta carpeta contiene el programa Khaos, que cada actualizaci\xF3n reemplaza. Elige otra.", driveRoot: "Elige una carpeta, no la ra\xEDz de un disco.", failed: "No se puede usar esta carpeta: {0}", changeTitle: "Cambiar carpeta de instalaci\xF3n", changeIntro: "Los datos del juego (unos {0}) pueden ir a otro disco. Khaos se reinicia para usar la nueva carpeta.", currentFolder: "Carpeta actual", partialNote: "Descarga sin terminar: {0}", completeNote: "Juego instalado: {0}", partial: "La primera descarga no termin\xF3 ({0} recibidos en {1}). Puedes reanudarla aqu\xED o elegir otra carpeta.", lowSpace: "No hay espacio suficiente en {0}: faltan {1} y solo hay {2} libres. Elige otra carpeta.", spaceFull: "El disco {0} est\xE1 lleno. Elige otra carpeta para seguir con la descarga.", resume: "Continuar aqu\xED", oldTitle: "\xBFY la descarga anterior?", oldPartial: "Quedan {0} de una descarga sin terminar en {1}. Borrarla libera ese espacio; el juego se descarga en la nueva carpeta.", deleteOld: "Borrarla y empezar aqu\xED", moveOld: "Moverla aqu\xED", back: "Volver", moveTitle: "Mover los datos del juego", moveComplete: "Los datos del juego ({0}) se mover\xE1n de {1} a {2}. Khaos se reinicia para moverlos y luego se abre.", moveRestart: "Mover y reiniciar", notEmpty: "Esta carpeta ya contiene archivos. Elige una carpeta vac\xEDa para mover los datos.", overlap: "Elige una carpeta separada de la actual." } }; var fill = (template, ...values) => String(template).replace(/\{(\d+)\}/gu, (_, index) => String(values[Number(index)] ?? "")); function setupLanguage(savedSettings, locale) { const saved = savedSettings?.options?.interfaceLanguage ?? savedSettings?.interfaceLanguage; if (typeof saved === "string" && SETUP_TEXTS[saved]) return saved; const system = String(locale ?? "").slice(0, 2).toLowerCase(); return SETUP_TEXTS[system] ? system : "fr"; } function formatSize(bytes, text3, digits = bytes / GiB >= 100 ? 0 : 1) { const value = bytes / GiB; return `${value.toFixed(digits).replace(".", text3.decimal)} ${text3.unit}`; } async function nearestExisting(directory, io) { for (let current = import_node_path5.default.resolve(directory); ; current = import_node_path5.default.dirname(current)) { try { await io.stat(current); return current; } catch (error) { if (current === import_node_path5.default.dirname(current)) throw error; } } } async function measureVolume(directory, { io = import_promises4.default, timeoutMs = 1500 } = {}) { let timer; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve({ present: false }), timeoutMs); }); const probe = (async () => { try { const volume = await io.statfs(await nearestExisting(directory, io)); const block = Number(volume.bsize); const free = block * Number(volume.bavail), total = block * Number(volume.blocks); const known = (value) => Number.isSafeInteger(value) && value >= 0 ? value : null; return { present: true, free: known(free), total: known(total) || null }; } catch { return { present: false }; } })(); try { return await Promise.race([probe, timeout]); } finally { clearTimeout(timer); } } async function storageCandidates({ defaultRoot, platform = process.platform, io = import_promises4.default, folders = null, timeoutMs = 1500 }) { const list2 = [{ id: "default", kind: "default", root: defaultRoot, drive: platform === "win32" ? import_node_path5.default.win32.parse(defaultRoot).root.slice(0, 2).toUpperCase() : "" }]; if (Array.isArray(folders)) { const label = (root) => root.split(/[\\/]+/u).filter((part) => part && !/^khaos(game)?$/iu.test(part)).at(-1) ?? root; folders.forEach((root, index) => list2.push({ id: `folder-${index}`, kind: "drive", root, drive: label(root) })); } else if (platform === "win32") { for (const letter2 of "CDEFGHIJKLMNOPQRSTUVWXYZ") { const drive = `${letter2}:`; if (drive !== list2[0].drive) list2.push({ id: `drive-${letter2}`, kind: "drive", root: `${drive}\\Khaos\\KhaosGame`, drive, probe: `${drive}\\` }); } } const measured = await Promise.all(list2.map(async (candidate) => ({ ...candidate, ...await measureVolume(candidate.probe ?? candidate.root, { io, timeoutMs }) }))); return measured.filter((candidate) => candidate.kind === "default" || candidate.present && candidate.total !== null).map(({ probe, present, ...candidate }) => ({ ...candidate, free: candidate.free ?? null, total: candidate.total ?? null })); } var enoughSpace = (candidate, bytes) => candidate.free === null || candidate.free >= (candidate.need ?? bytes); function preferredCandidate(list2, bytes) { const current = list2.find((candidate) => candidate.current); if (current && enoughSpace(current, bytes)) return current; if (list2[0] && enoughSpace(list2[0], bytes)) return list2[0]; return [...list2].filter((candidate) => enoughSpace(candidate, bytes)).sort((a, b) => (b.free ?? 0) - (a.free ?? 0))[0] ?? list2[0]; } var sizeText = (bytes, text3) => bytes > 0 && bytes < GiB / 10 ? `< ${formatSize(GiB / 10, text3)}` : formatSize(bytes ?? 0, text3); function shortPath(value, max = 62) { if (value.length <= max) return value; const separator = value.includes("\\") ? "\\" : "/", parts = value.split(separator); const head = `${parts.shift()}${separator}\u2026`; let tail = ""; while (parts.length && head.length + separator.length + parts.at(-1).length + tail.length <= max) tail = `${separator}${parts.pop()}${tail}`; return tail ? head + tail : `\u2026${value.slice(-(max - 1))}`; } function setupView({ text: text3, list: list2, selected, bytes, notice = null, error = null, busy = false, current = null, confirm = null }) { const items = list2.map((candidate) => { const enough = enoughSpace(candidate, bytes); const label = candidate.kind === "current" ? text3.currentFolder : candidate.kind === "default" ? text3.defaultDrive : candidate.kind === "custom" ? text3.customFolder : fill(text3.otherDrive, candidate.drive); const note = !candidate.current || !current ? "" : current.state === "partial" ? fill(text3.partialNote, sizeText(current.bytes, text3)) : current.state === "complete" && current.bytes > 0 ? fill(text3.completeNote, sizeText(current.bytes, text3)) : ""; const space = candidate.free === null ? text3.freeUnknown : candidate.total ? fill(text3.free, formatSize(candidate.free, text3), formatSize(candidate.total, text3)) : fill(text3.freeOnly, formatSize(candidate.free, text3)); return { id: candidate.id, badge: candidate.drive || "", label, note, current: candidate.current === true, path: shortPath(candidate.root), fullPath: candidate.root, space, enough, warning: enough ? "" : text3.notEnough, selected: candidate.id === selected, used: candidate.total && candidate.free !== null ? Math.max(0, Math.min(1, 1 - candidate.free / candidate.total)) : null }; }); const chosen = items.find((item) => item.selected); return { items, notice, error, busy, confirm, canInstall: Boolean(chosen?.enough) && !busy, install: busy ? text3.checking : chosen?.current ? text3.resume : text3.install }; } function page(text3, bytes, logo, initial, mode = "first") { const css = ` *{box-sizing:border-box}html,body{margin:0;height:100%} body{font:14px/1.45 "Segoe UI",system-ui,-apple-system,sans-serif;color:#ece7f7;user-select:none;overflow:hidden; background:radial-gradient(120% 60% at 50% -10%,rgba(154,95,224,.30),transparent 60%),radial-gradient(60% 50% at 100% 100%,rgba(102,203,208,.12),transparent 70%),linear-gradient(180deg,#1c1a28 0%,#141820 55%,#10171a 100%)} main{display:flex;flex-direction:column;height:100%;padding:26px 30px 22px} header{display:flex;gap:16px;align-items:center} header img{width:58px;height:58px;filter:drop-shadow(0 0 12px rgba(184,127,224,.55))} h1{margin:0;font-size:21px;font-weight:600;letter-spacing:.2px;color:#f3edff;text-shadow:0 0 18px rgba(184,127,224,.45)} .intro{margin:4px 0 0;color:#ccc4e0} .need{display:inline-block;margin:16px 0 10px;padding:4px 12px;border-radius:999px;border:1px solid rgba(184,150,230,.32);background:rgba(44,38,62,.65);color:#c2aaf0;font-weight:600} .notice{margin:0 0 10px;padding:8px 12px;border-radius:8px;border:1px solid rgba(240,163,92,.45);background:rgba(240,163,92,.10);color:#f3cfa8} ul{list-style:none;margin:0;padding:0 4px 0 0;flex:1;overflow:auto;scrollbar-width:thin;scrollbar-color:rgba(204,196,224,.4) transparent} li{margin:0 0 8px} .drive{display:grid;grid-template-columns:46px 1fr auto;gap:2px 12px;align-items:center;width:100%;padding:10px 14px;border-radius:10px;cursor:pointer;text-align:left;font:inherit;color:inherit; border:1px solid rgba(184,150,230,.24);background:linear-gradient(180deg,rgba(44,38,62,.85),rgba(31,28,42,.85));transition:border-color .12s,box-shadow .12s} .drive:hover{border-color:rgba(128,212,210,.55)} .drive.selected{border-color:#66cbd0;box-shadow:0 0 0 1px #66cbd0 inset,0 0 16px rgba(102,203,208,.25)} .drive.short{opacity:.62} .badge{grid-row:1/3;display:flex;align-items:center;justify-content:center;height:40px;border-radius:8px;background:rgba(15,21,25,.75);border:1px solid rgba(184,150,230,.28);font-weight:700;font-size:15px;color:#c2aaf0;padding:0 3px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis} .label{font-weight:600;color:#f3edff} .space{text-align:right;color:#ccc4e0;white-space:nowrap} .space.short{color:#f08f84;font-weight:600} .note{margin-left:8px;font-size:12px;font-weight:600;color:#80d4d2} .drive.current .badge{border-color:rgba(102,203,208,.55);color:#9fe3df} .path{grid-column:2/4;font-size:12.5px;color:#a9a2bf;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;direction:ltr} .bar{grid-column:2/4;height:4px;margin-top:5px;border-radius:2px;background:rgba(204,196,224,.14);overflow:hidden} .bar>i{display:block;height:100%;background:linear-gradient(90deg,#7b45c4,#b87fe0)} .choose{margin:6px 0 0;align-self:flex-start;padding:8px 16px;border-radius:8px;font:inherit;color:#ece7f7;cursor:pointer;border:1px solid rgba(204,196,224,.45);background:rgba(44,38,62,.9)} .choose:hover{border-color:#80d4d2} .error{min-height:20px;margin:10px 0 0;color:#f08f84} footer{display:flex;align-items:center;gap:16px;margin-top:8px} .langs{display:flex;gap:4px;margin-left:auto;align-self:flex-start;padding:3px;border-radius:999px;border:1px solid rgba(184,150,230,.28);background:rgba(15,21,25,.55)} .langs button{padding:3px 10px;border:0;border-radius:999px;font:inherit;font-size:12px;font-weight:600;color:#ccc4e0;background:transparent;cursor:pointer} .langs button:hover{color:#fff}.langs button.on{color:#fff;background:linear-gradient(180deg,#9a5fe0,#7b45c4)} .later{flex:1;margin:0;font-size:12.5px;color:#a9a2bf} .install{padding:10px 26px;border-radius:9px;font:inherit;font-weight:700;font-size:15px;color:#fff;cursor:pointer;border:1px solid rgba(214,190,245,.6); background:linear-gradient(180deg,#9a5fe0,#7b45c4);box-shadow:0 0 18px rgba(154,95,224,.45)} .install:hover{background:linear-gradient(180deg,#a96ff0,#8a52d6)} .install:disabled{cursor:default;opacity:.45;box-shadow:none} button:focus-visible{outline:2px solid #66cbd0;outline-offset:2px} .confirm{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(10,12,18,.74);backdrop-filter:blur(3px)} .confirm[hidden]{display:none} .confirm>div{max-width:540px;padding:22px 24px 20px;border-radius:12px;border:1px solid rgba(184,150,230,.38);background:linear-gradient(180deg,#24202f,#171a21);box-shadow:0 18px 48px rgba(0,0,0,.55),0 0 22px rgba(154,95,224,.22)} .confirm h2{margin:0 0 8px;font-size:18px;font-weight:600;color:#f3edff} .confirm p{margin:0 0 18px;color:#ccc4e0;word-break:break-word} .actions{display:flex;flex-wrap:wrap;gap:10px;justify-content:flex-end} .actions .choose{margin:0;align-self:auto}`; const script = ` let count = 0; const send = (action, id) => { document.title = "khaos-setup:" + JSON.stringify({ action, id: id ?? null, n: ++count }); }; const $ = (name) => document.querySelector(name); window.khaosSetup = (view) => { const list = $("ul"); list.textContent = ""; for (const item of view.items) { const button = document.createElement("button"); button.className = "drive" + (item.selected ? " selected" : "") + (item.enough ? "" : " short"); button.setAttribute("role", "radio"); button.setAttribute("aria-checked", String(item.selected)); button.dataset.id = item.id; const add = (tag, cls, value) => { const node = document.createElement(tag); node.className = cls; if (value !== undefined) node.textContent = value; button.append(node); return node; }; add("span", "badge", item.badge || "\\u2022"); add("span", "label", item.label).append(Object.assign(document.createElement("span"), { className: "note", textContent: item.note })); if (item.current) button.classList.add("current"); add("span", "space" + (item.enough ? "" : " short"), item.enough ? item.space : item.warning + " \\u00b7 " + item.space); add("span", "path", item.path).title = item.fullPath; if (item.used !== null) add("span", "bar").append(Object.assign(document.createElement("i"), { style: "width:" + Math.round(item.used * 100) + "%" })); button.disabled = view.busy; button.onclick = () => send("select", item.id); button.ondblclick = () => item.enough && send("install"); const row = document.createElement("li"); row.append(button); list.append(row); } const notice = $(".notice"); notice.textContent = view.notice ?? ""; notice.hidden = !view.notice; $(".error").textContent = view.error ?? ""; const install = $(".install"); install.textContent = view.install; install.disabled = !view.canInstall; $(".choose").disabled = view.busy; const confirm = $(".confirm"); confirm.hidden = !view.confirm; if (view.confirm) { confirm.querySelector("h2").textContent = view.confirm.title; confirm.querySelector("p").textContent = view.confirm.text; const actions = confirm.querySelector(".actions"); actions.textContent = ""; for (const action of view.confirm.actions) { const button = document.createElement("button"); button.type = "button"; button.className = action.primary ? "install" : "choose"; button.textContent = action.label; button.dataset.action = action.id; button.disabled = view.busy; button.onclick = () => send("confirm", action.id); actions.append(button); } actions.querySelector(".install")?.focus(); } }; $(".choose").onclick = () => send("pick"); for (const button of document.querySelectorAll(".langs button")) button.onclick = () => send("language", button.dataset.lang); $(".install").onclick = () => send("install"); window.khaosSetup(${JSON.stringify(initial)}); $(".selected")?.focus();`; const escape = (value) => String(value).replace(/[&<>"']/gu, (character) => `&#${character.charCodeAt(0)};`); return `${escape(text3.windowTitle)}
${logo ? `` : ""}

${escape(mode === "change" ? text3.changeTitle : text3.title)}

${escape(fill(mode === "change" ? text3.changeIntro : text3.intro, formatSize(FIRST_DOWNLOAD_BYTES, text3, 0)))}

${escape(fill(text3.need, formatSize(bytes, text3)))}

${escape(text3.later)}

`; } async function checkFolder(root, { text: text3, bytes, io = import_promises4.default, paths = locationPaths(), programDirectory = null, currentRoot = null, requireEmpty = false }) { try { root = paths.checked(root); } catch { return text3.driveRoot; } if (programDirectory && paths.overlap(root, programDirectory)) return text3.programFolder; if (currentRoot && !paths.same(root, currentRoot) && paths.overlap(root, currentRoot)) return text3.overlap; let populated = false; try { populated = (await io.readdir(root)).length > 0; } catch { } if (populated && requireEmpty) return text3.notEmpty; if (!populated) { const volume = await measureVolume(root, { io }); if (volume.present && volume.free !== null && volume.free < bytes) return fill(text3.noSpace, formatSize(bytes, text3), formatSize(volume.free, text3)); } const probe = import_node_path5.default.join(root, `.khaos-write-test-${(0, import_node_crypto3.randomUUID)()}`); try { await io.mkdir(root, { recursive: true }); const handle = await io.open(probe, "wx"); await handle.close(); await io.unlink(probe); return null; } catch (error) { if (error?.code === "ENOSPC") return fill(text3.noSpace, formatSize(bytes, text3), formatSize(0, text3)); if (["EACCES", "EPERM", "EROFS", "EBUSY", "ENOENT", "ENOTDIR", "EEXIST"].includes(error?.code)) return fill(text3.notWritable, error.code); return fill(text3.failed, String(error?.message ?? error)); } } var hasEntries = async (directory, io) => { try { return (await io.readdir(directory)).length > 0; } catch { return false; } }; async function chooseGameDataFolder({ BrowserWindow, dialog, io = import_promises4.default, logger = console, language = "fr", defaultRoot, bytes, unavailable = null, folders = null, platform = process.platform, programDirectory = null, logo = null, paths = locationPaths(), current = null, reason = null, mode = "first", parent = null, neededBytes = null }) { const texts = (code) => ({ ...SETUP_TEXTS[code] ?? SETUP_TEXTS.fr, lang: SETUP_TEXTS[code] ? code : "fr" }); let text3 = texts(language); const driveOf = (root) => platform === "win32" ? import_node_path5.default.win32.parse(root).root.slice(0, 2).toUpperCase() : ""; const list2 = await storageCandidates({ defaultRoot, platform, io, folders }); if (current?.root) { const index = list2.findIndex((candidate) => paths.same(candidate.root, current.root)); if (index >= 0) list2[index].current = true; else { const volume = await measureVolume(current.root, { io }); list2.unshift({ id: "current", kind: "current", root: current.root, drive: driveOf(current.root), current: true, free: volume.free ?? null, total: volume.total ?? null }); } } const moving = current?.state === "complete"; const left = Number.isSafeInteger(neededBytes) && neededBytes >= 0 ? neededBytes : Math.max(0, bytes - (current?.bytes ?? 0)); const needOf = (candidate) => candidate.current ? moving ? 0 : left : Math.max(bytes, moving ? current.bytes ?? 0 : 0); for (const candidate of list2) candidate.need = needOf(candidate); let selected = preferredCandidate(list2, bytes).id, error = null, busy = false, confirm = null; const here = () => list2.find((candidate) => candidate.current) ?? null; const notice = () => { if (unavailable) return fill(text3.unavailable, unavailable); const folder = here(), drive = folder ? folder.drive || shortPath(folder.root, 40) : ""; if (folder && !enoughSpace(folder, bytes)) return fill(text3.lowSpace, drive, formatSize(folder.need, text3), formatSize(folder.free ?? 0, text3)); if (folder && reason === "space") return fill(text3.spaceFull, drive); if (current?.state === "partial" && mode !== "change") return fill(text3.partial, sizeText(current.bytes, text3), shortPath(current.root)); return null; }; const confirmView = () => { if (!confirm) return null; const size = sizeText(current?.bytes ?? 0, text3); if (confirm.kind === "move") { return { title: text3.moveTitle, text: fill(text3.moveComplete, size, shortPath(current.root), shortPath(confirm.root)), actions: [{ id: "move", label: text3.moveRestart, primary: true }, { id: "back", label: text3.back }] }; } return { title: text3.oldTitle, text: fill(text3.oldPartial, size, shortPath(current.root)), actions: [{ id: "delete", label: text3.deleteOld, primary: true }, ...confirm.canMove ? [{ id: "move", label: text3.moveOld }] : [], { id: "back", label: text3.back }] }; }; const view = () => setupView({ text: text3, list: list2, selected, bytes, notice: notice(), error, busy, current, confirm: confirmView() }); const load = () => window.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(page(text3, bytes, logo, view(), mode))}`); logger.info?.("Game data setup shown", { mode, reason, defaultRoot, current: current ? { root: current.root, state: current.state, bytes: current.bytes } : null, candidates: list2.map(({ root, free, need }) => ({ root, free, need })) }); const window = new BrowserWindow({ width: 700, height: 600, minWidth: 560, minHeight: 480, show: false, title: mode === "change" ? text3.changeTitle : text3.windowTitle, backgroundColor: "#141820", autoHideMenuBar: true, ...parent ? { parent, modal: true } : {}, webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true } }); return new Promise((resolve) => { let done = false; const finish = (answer) => { if (done) return; done = true; if (!window.isDestroyed()) window.destroy(); resolve(answer); }; const render = () => { if (!window.isDestroyed()) window.webContents.executeJavaScript(`window.khaosSetup(${JSON.stringify(view())})`).catch(() => { }); }; const act = async ({ action, id }) => { if (busy || done) return; if (action === "language" && SETUP_TEXTS[id] && id !== text3.lang) { text3 = texts(id); error = null; window.setTitle?.(mode === "change" ? text3.changeTitle : text3.windowTitle); load().catch((failure3) => logger.warn?.("Game data setup page reload failed", failure3)); return; } if (confirm) { if (action !== "confirm") return; if (id === "back") { confirm = null; render(); return; } const allowed = confirm.kind === "move" ? id === "move" : id === "delete" || id === "move" && confirm.canMove; if (allowed) { logger.info?.("Game data folder chosen", { root: confirm.root, oldData: id, previous: current.root }); finish({ root: confirm.root, oldData: id }); } return; } if (action === "select" && list2.some((candidate) => candidate.id === id)) { selected = id; error = null; render(); return; } if (action === "pick") { busy = true; render(); try { const chosen = list2.find((candidate) => candidate.id === selected); const answer = await dialog.showOpenDialog(window, { title: text3.pickTitle, defaultPath: chosen ? import_node_path5.default.dirname(chosen.root) : void 0, properties: ["openDirectory", "createDirectory", "dontAddToRecent"] }); const picked = answer.canceled ? null : answer.filePaths?.[0]; if (picked) { const root = paths.gameDirectory(picked), custom = { id: "custom", kind: "custom", root, drive: driveOf(root) }; Object.assign(custom, await measureVolume(root, { io })); delete custom.present; custom.free ??= null; custom.total ??= null; const index = list2.findIndex((candidate) => candidate.id === "custom" || paths.same(candidate.root, root)); if (index >= 0 && list2[index].kind !== "custom") selected = list2[index].id; else { custom.need = needOf(custom); if (index >= 0) list2.splice(index, 1, custom); else list2.push(custom); selected = "custom"; } error = null; } } catch (failure3) { logger.warn?.("Game data folder picker failed", failure3); } busy = false; render(); return; } if (action === "install") { const candidate = list2.find((item) => item.id === selected); if (!candidate) return; busy = true; error = null; render(); const elsewhere = Boolean(current?.root) && !candidate.current; const refusal = await checkFolder(candidate.root, { text: text3, bytes: candidate.need ?? bytes, io, paths, programDirectory, currentRoot: current?.root ?? null, requireEmpty: elsewhere && moving }); if (refusal !== null) { logger.warn?.("Game data folder refused", { root: candidate.root, problem: refusal }); busy = false; error = refusal; render(); return; } const root = paths.checked(candidate.root); if (elsewhere && (current.state === "partial" || moving)) { confirm = { kind: moving ? "move" : "old", root, canMove: !await hasEntries(root, io) }; busy = false; render(); return; } logger.info?.("Game data folder chosen", { root }); finish({ root, oldData: null }); } }; window.on("page-title-updated", (event, title) => { event.preventDefault(); if (!String(title).startsWith("khaos-setup:")) return; let message3; try { message3 = JSON.parse(String(title).slice(10)); } catch { return; } void act(message3 ?? {}); }); window.on("closed", () => finish(null)); window.once("ready-to-show", () => { if (!window.isDestroyed()) { window.show(); window.focus(); } }); window.setMenuBarVisibility?.(false); load().catch((failure3) => { logger.error?.("Game data setup page failed", failure3); finish(mode === "change" ? null : { root: current?.root ?? defaultRoot, oldData: null }); }); }); } function gameDataSetupStep({ electron: electron2, request, coreDirectory, logger = console, readFile: readFile2 = import_node_fs.default.readFileSync }) { if (!request || typeof request.defaultRoot !== "string") return null; return async ({ defaultRoot, unavailable, bytes, paths, current = null, reason = null, mode = "first", parent = null, neededBytes = null }) => { let settings = null, logo = null; try { settings = JSON.parse(readFile2(import_node_path5.default.join(electron2.app.getPath("userData"), "settings.json"), "utf8")); } catch { } try { logo = `data:image/png;base64,${readFile2(import_node_path5.default.join(coreDirectory, "khaos", "brand", "khaos-icon.png")).toString("base64")}`; } catch { } return chooseGameDataFolder({ BrowserWindow: electron2.BrowserWindow, dialog: electron2.dialog, logger, defaultRoot, unavailable, bytes, paths, logo, current, reason, mode, parent, neededBytes, language: setupLanguage(settings, electron2.app.getLocale?.()), folders: Array.isArray(request.folders) ? request.folders : null, programDirectory: import_node_path5.default.dirname(process.execPath) }); }; } // src/electron/khaos/desktopAssets.js var import_node_path13 = __toESM(require("node:path"), 1); // src/electron/khaos/assetCache.js var import_promises7 = __toESM(require("node:fs/promises"), 1); var import_node_path7 = __toESM(require("node:path"), 1); // src/electron/khaos/assetMetadata.js var import_node_crypto5 = require("node:crypto"); var import_promises5 = require("node:fs/promises"); // src/electron/khaos/assetManifest.js var import_node_crypto4 = require("node:crypto"); var manifestProfiles = ["desktop-bc7", "desktop-compatibility"]; var manifestHash = (bytes) => (0, import_node_crypto4.createHash)("sha256").update(bytes).digest("hex"); var digest = (value) => typeof value === "string" && /^[0-9a-f]{64}$/u.test(value); var integer = (value) => Number.isSafeInteger(value) && value >= 0; var text = (value) => typeof value === "string" && Boolean(value.length); var canonicalText = (value) => text(value) && value.trim() === value && !/[\u0000-\u001f\u007f]/u.test(value); var ManifestContractError = class extends Error { constructor(message3) { super(message3); this.name = "ContractError"; } }; var requireContract = (condition, label) => { if (!condition) throw new ManifestContractError(label); }; var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value); function fields(value, names, label) { requireContract(object2(value) && Object.keys(value).length === names.length && names.every((name) => Object.hasOwn(value, name)), `${label}: missing or unexpected fields`); } function logicalAssetPath(value) { requireContract(canonicalText(value) && !/[\\?#]/u.test(value) && value.split("/").every((part) => part && part !== "." && part !== ".."), "Invalid logical asset path"); return value; } function logicalAssetPrefix(value) { requireContract(typeof value === "string" && !value.startsWith("/") && !/[\\\u0000-\u001f\u007f]/u.test(value) && !value.split("/").includes(".."), "Invalid logical asset prefix"); return value; } function strictVersion(value) { requireContract(text(value) && value.split(".").length === 3 && value.split(".").every((part) => /^(0|[1-9][0-9]*)$/u.test(part) && Number.isSafeInteger(Number(part))), "Invalid minimum client version"); return value; } function artifactReference(value, expectedPath) { fields(value, ["path", "hash", "size", "itemCount"], "Artifact reference"); requireContract(digest(value.hash) && integer(value.size) && integer(value.itemCount), "Invalid artifact digest or counts"); logicalAssetPath(value.path); requireContract(value.path === expectedPath(value.hash), "Noncanonical immutable artifact path"); return { path: value.path, hash: value.hash, size: value.size, itemCount: value.itemCount }; } function parseManifest(bytes) { let value; try { value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch (cause) { throw new ManifestContractError(`Manifest is not UTF-8 JSON: ${cause.message}`); } fields(value, ["schemaVersion", "format", "version", "coverage", "generatedAt", "shardPrefixLength", "packFormat", "individualFallback", "minimumClients", "packCatalog", "installPlans", "shards"], "Manifest"); const fixed = { schemaVersion: 3, format: "path-sha256-carriers-sharded", coverage: "complete", packFormat: "raw-concat-v1", individualFallback: "ca" }; requireContract(Object.entries(fixed).every(([key, expected]) => value[key] === expected), "Manifest does not use the v3 carrier contract"); requireContract(canonicalText(value.version), "Noncanonical manifest version"); requireContract(integer(value.shardPrefixLength) && value.shardPrefixLength > 0 && value.shardPrefixLength <= 64, "Invalid shard prefix length"); const generated = new Date(value.generatedAt); requireContract(text(value.generatedAt) && Number.isFinite(generated.getTime()) && generated.toISOString() === value.generatedAt, "Invalid manifest timestamp"); fields(value.minimumClients, ["game", "editor", "studio", "webCacheVersion"], "Minimum clients"); const minimumClients = Object.fromEntries(["game", "editor", "studio"].map((variant) => [variant, strictVersion(value.minimumClients[variant])])); requireContract(typeof value.minimumClients.webCacheVersion === "string" && /^[0-9]{14}$/u.test(value.minimumClients.webCacheVersion), "Invalid web cache version"); minimumClients.webCacheVersion = value.minimumClients.webCacheVersion; fields(value.installPlans, manifestProfiles, "Install plans"); const packCatalog = artifactReference(value.packCatalog, (hash) => `asset-pack-catalog/${hash}.json`); const installPlans = Object.fromEntries(manifestProfiles.map((profile) => [profile, artifactReference(value.installPlans[profile], (hash) => `asset-install-plans/${profile}/${hash}.json`)])); requireContract(object2(value.shards) && Object.keys(value.shards).length > 0, "Manifest needs at least one shard"); const shards = /* @__PURE__ */ Object.create(null); for (const [id, reference] of Object.entries(value.shards)) { requireContract(id.length === value.shardPrefixLength && /^[0-9a-f]+$/u.test(id), "Invalid shard id"); shards[id] = artifactReference(reference, (hash) => `asset-manifest-shards/${id}-${hash}.json`); } const artifactBytes = [packCatalog, ...Object.values(installPlans), ...Object.values(shards)].reduce((total, reference) => total + reference.size, 0); requireContract(integer(artifactBytes) && artifactBytes <= 320 * 1024 * 1024, "Manifest immutable metadata exceeds 320 MiB"); const manifest = { ...fixed, version: value.version, generatedAt: value.generatedAt, shardPrefixLength: value.shardPrefixLength, minimumClients, packCatalog, installPlans, shards }; return { manifest, revision: manifestHash(bytes), sourceBytes: bytes }; } function assetReference(asset2) { logicalAssetPath(asset2.path); requireContract(digest(asset2.hash) && integer(asset2.size), "Invalid logical asset digest or size"); return asset2; } var packPath = (hash) => { requireContract(digest(hash), "Invalid pack digest"); return `packs/sha256/${hash.substring(0, 2)}/${hash}.pack`; }; function validateCarrier(asset2, catalog) { if (asset2.carrier.kind === "loose") return; const pack2 = catalog.packs[asset2.carrier.packHash]; requireContract(Boolean(pack2), `Missing pack for ${asset2.path}`); const end = asset2.carrier.offset + asset2.carrier.length; requireContract(integer(asset2.carrier.offset) && integer(end) && asset2.carrier.length === asset2.size && end <= pack2.size, `Asset range exceeds pack: ${asset2.path}`); } function cooperativeWork({ budgetMs = 4, checkInterval = 256, now = () => performance.now(), yieldControl = () => new Promise((resolve) => setImmediate(resolve)) } = {}) { requireContract(Number.isFinite(budgetMs) && budgetMs >= 0 && Number.isSafeInteger(checkInterval) && checkInterval > 0, "Invalid cooperative work budget"); let next = checkInterval, started = now(); const yieldNow = async () => { await yieldControl(); next = checkInterval; started = now(); }; return { yieldNow, checkpoint() { if (--next > 0) return null; next = checkInterval; return now() - started >= budgetMs ? yieldNow() : null; } }; } function uniqueHashSizes(assets) { const hashes = /* @__PURE__ */ new Map(); for (const asset2 of assets) { if (hashes.has(asset2.hash)) requireContract(hashes.get(asset2.hash) === asset2.size, `Inconsistent size for ${asset2.hash}`); hashes.set(asset2.hash, asset2.size); } return Array.from(hashes, ([hash, size]) => ({ hash, size })); } function requiredCompletionDescriptor(sourceKey2, snapshot2) { const plan = snapshot2.plan; const assets = plan.requiredCategories.flatMap((id) => { requireContract(Boolean(plan.categories[id]), "Required category is absent"); return plan.categories[id].assets; }); const unique = uniqueHashSizes(assets); const uniqueLogicalBytes = unique.reduce((sum, asset2) => sum + asset2.size, 0); requireContract(integer(uniqueLogicalBytes), "Required inventory exceeds safe byte count"); return { sourceKey: sourceKey2, profile: plan.profile, planHash: snapshot2.hash, categories: plan.requiredCategories.map((id) => ({ id, label: plan.categories[id].label, assetCount: plan.categories[id].assetCount, logicalBytes: plan.categories[id].logicalBytes })), uniqueAssetCount: unique.length, uniqueLogicalBytes }; } async function validateInstallPlan(plan, catalog, work = cooperativeWork()) { for (const [id, category2] of Object.entries(plan.categories)) { const carriers = /* @__PURE__ */ new Map(); for (const asset2 of category2.assets) { validateCarrier(asset2, catalog); const key = asset2.carrier.kind === "pack" ? `pack:${asset2.carrier.packHash}` : `asset:${asset2.hash}`; const size = asset2.carrier.kind === "pack" ? catalog.packs[asset2.carrier.packHash].size : asset2.size; requireContract(!carriers.has(key) || carriers.get(key) === size, `Inconsistent transfer size in ${id}`); carriers.set(key, size); const pause3 = work.checkpoint(); if (pause3) await pause3; } const expectedPacks = new Set(Array.from(carriers.keys()).filter((key) => key.startsWith("pack:")).map((key) => key.substring(5))); requireContract(category2.packs.length === expectedPacks.size && new Set(category2.packs).size === expectedPacks.size && category2.packs.every((hash) => expectedPacks.has(hash)), `Category pack set differs: ${id}`); requireContract(Array.from(carriers.values()).reduce((sum, size) => sum + size, 0) === category2.transferBytes, `Category transfer bytes differ: ${id}`); } } function equivalent(left, right) { const scalar = ["hash", "size", "contentType"].every((key) => left[key] === right[key]); return scalar && ["kind", "packHash", "offset", "length"].every((key) => left.carrier[key] === right.carrier[key]); } function corpusValidation(catalog) { const packMembers = /* @__PURE__ */ new Map(); return { asset(asset2) { validateCarrier(asset2, catalog); if (asset2.carrier.kind !== "pack") return; const carrier2 = asset2.carrier; const members = packMembers.get(carrier2.packHash) ?? /* @__PURE__ */ new Map(); const previous = members.get(asset2.hash); requireContract(!previous || previous.offset === carrier2.offset && previous.length === carrier2.length, `Conflicting packed hash range: ${asset2.hash}`); members.set(asset2.hash, carrier2); packMembers.set(carrier2.packHash, members); }, async packs(work = cooperativeWork()) { for (const [hash, pack2] of Object.entries(catalog.packs)) { const ranges = Array.from(packMembers.get(hash)?.values() ?? []).sort((left, right) => left.offset - right.offset); let end = 0, liveBytes = 0; for (const range of ranges) { requireContract(range.offset >= end, `Overlapping members in pack ${hash}`); end = range.offset + range.length; liveBytes += range.length; const pause3 = work.checkpoint(); if (pause3) await pause3; } requireContract(ranges.length > 0 && ranges.length <= pack2.memberCount && liveBytes === pack2.liveBytes && pack2.path === packPath(hash), `Pack corpus coverage differs: ${hash}`); } }, async plan(plan, itemCount, find, work = cooperativeWork()) { const selected = /* @__PURE__ */ new Map(); for (const category2 of Object.values(plan.categories)) { for (const asset2 of category2.assets) { requireContract(!selected.has(asset2.path) || equivalent(selected.get(asset2.path), asset2), `Conflicting plan path: ${asset2.path}`); const known = find(asset2.path); requireContract(Boolean(known) && equivalent(known, asset2), `Plan asset differs from shard: ${asset2.path}`); selected.set(asset2.path, asset2); const pause3 = work.checkpoint(); if (pause3) await pause3; } } requireContract(selected.size === itemCount, "Plan item count differs from root"); } }; } async function validateCorpus(root, shards, catalog, plans, work = cooperativeWork()) { const paths = /* @__PURE__ */ new Map(), checks = corpusValidation(catalog); for (const shard of shards) { for (const [path22, record7] of Object.entries(shard.value.assets)) { requireContract(!paths.has(path22), `Duplicate manifest path: ${path22}`); const asset2 = { path: path22, ...record7 }; checks.asset(asset2); paths.set(path22, asset2); const pause3 = work.checkpoint(); if (pause3) await pause3; } } await checks.packs(work); for (const plan of plans) await checks.plan(plan, root.manifest.installPlans[plan.profile].itemCount, (path22) => paths.get(path22), work); return Array.from(paths.values()); } // src/electron/khaos/assetIndex.js var KEY_BYTES = 32; var HASH_AT = KEY_BYTES; var SIZE_AT = HASH_AT + 32; var TYPE_AT = SIZE_AT + 8; var PACK_AT = TYPE_AT + 2; var OFFSET_AT = PACK_AT + 4; var RECORD_BYTES = OFFSET_AT + 8; var LOOSE = 4294967295; var MAX_TYPES2 = 65536; var natural = (value) => Number.isSafeInteger(value) && value >= 0; var storeDigest = (buffer, text3, at) => typeof text3 === "string" && text3.length === 64 && buffer.write(text3, at, 32, "hex") === 32 && buffer.toString("hex", at, at + 32) === text3; function refuse(reason) { const error = new Error(`Asset record cannot be indexed: ${reason}`); error.name = "AssetIndexError"; throw error; } var AssetIndex = class { #shards = /* @__PURE__ */ new Map(); #types = []; #typeIds = /* @__PURE__ */ new Map(); #packs = []; #packIds = /* @__PURE__ */ new Map(); #assets = 0; #bytes = 0; /** `{ packs: { [hash]: { size } } }` of the verified pack catalog (what a packed read's range check needs), or null. */ catalog = null; constructor(revision) { this.revision = revision; } get shardCount() { return this.#shards.size; } get assetCount() { return this.#assets; } get byteLength() { return this.#bytes; } hasShard(id) { return this.#shards.has(id); } #intern(value, list2, ids, limit) { let id = ids.get(value); if (id === void 0) { if (list2.length >= limit) refuse("too many distinct values"); id = list2.length; list2.push(value); ids.set(value, id); } return id; } /** * Adds one verified shard. `rows` are `[digest, asset]`: the lowercase hex SHA-256 of the logical path and the * shard's record for it (`{ hash, size, contentType, carrier }`). All of it or nothing: one refused record and the * shard is not added. */ addShard(id, rows) { if (this.#shards.has(id)) return; const sorted = [...rows].sort((left, right) => left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0); const buffer = Buffer.allocUnsafeSlow(sorted.length * RECORD_BYTES); let previous = null; for (let row = 0, at = 0; row < sorted.length; row++, at += RECORD_BYTES) { const [digest4, asset2] = sorted[row], carrier2 = asset2?.carrier; if (!storeDigest(buffer, digest4, at) || !digest4.startsWith(id)) refuse("path digest outside the shard"); if (digest4 === previous) refuse("two records for one path digest"); previous = digest4; if (!storeDigest(buffer, asset2?.hash, at + HASH_AT) || !natural(asset2.size)) refuse("digest or size"); if (typeof asset2.contentType !== "string" || !asset2.contentType) refuse("content type"); let pack2 = LOOSE, offset = 0, fields3 = 1; if (carrier2?.kind === "pack") { if (typeof carrier2.packHash !== "string" || !carrier2.packHash || !natural(carrier2.offset) || carrier2.length !== asset2.size) refuse("pack carrier"); pack2 = this.#intern(carrier2.packHash, this.#packs, this.#packIds, LOOSE); offset = carrier2.offset; fields3 = 4; } else if (carrier2?.kind !== "loose") refuse("carrier kind"); if (Object.keys(asset2).length !== 4 || Object.keys(carrier2).length !== fields3) refuse("unknown field"); buffer.writeDoubleLE(asset2.size, at + SIZE_AT); buffer.writeUInt16LE(this.#intern(asset2.contentType, this.#types, this.#typeIds, MAX_TYPES2), at + TYPE_AT); buffer.writeUInt32LE(pack2, at + PACK_AT); buffer.writeDoubleLE(offset, at + OFFSET_AT); } this.#shards.set(id, buffer); this.#assets += sorted.length; this.#bytes += buffer.length; } /** * The record of the asset whose path has this digest, as the shard gave it: `{ hash, size, contentType, carrier }`. * null = the shard has no such path; undefined = the shard is not in the index (the caller loads and adds it). */ find(id, digest4) { const buffer = this.#shards.get(id); if (buffer === void 0) return void 0; const key = Buffer.from(digest4, "hex"); if (key.length !== KEY_BYTES) return null; for (let low = 0, high = buffer.length / RECORD_BYTES - 1; low <= high; ) { const middle = low + high >>> 1, at = middle * RECORD_BYTES; const order = buffer.compare(key, 0, KEY_BYTES, at, at + KEY_BYTES); if (order === 0) { const size = buffer.readDoubleLE(at + SIZE_AT), pack2 = buffer.readUInt32LE(at + PACK_AT); return { hash: buffer.toString("hex", at + HASH_AT, at + HASH_AT + 32), size, contentType: this.#types[buffer.readUInt16LE(at + TYPE_AT)], carrier: pack2 === LOOSE ? { kind: "loose" } : { kind: "pack", packHash: this.#packs[pack2], offset: buffer.readDoubleLE(at + OFFSET_AT), length: size } }; } if (order > 0) high = middle - 1; else low = middle + 1; } return null; } /** Keeps the sizes of the verified catalog's packs (`validateCarrier` and a pack read need nothing else of it). */ setCatalog(catalog) { const packs = /* @__PURE__ */ Object.create(null); for (const [hash, pack2] of Object.entries(catalog.packs)) { if (!natural(pack2?.size)) refuse("pack size"); packs[hash] = { size: pack2.size }; } this.catalog = { packs }; } }; // src/electron/khaos/pruneSummary.js var DIGEST = 32; var SIZED = DIGEST + 8; var RECORDS = { blobs: SIZED, packs: SIZED, protectedBlobs: DIGEST, protectedPacks: DIGEST }; var NAMES = Object.keys(RECORDS); var DISAGREE = "Source snapshots disagree about a content size"; var bytesOf = (table2) => Buffer.from(table2.buffer, table2.byteOffset, table2.byteLength); var bothProfiles = (profiles2) => profiles2.length === 2 && new Set(profiles2).size === 2 && manifestProfiles.every((profile) => profiles2.includes(profile)); function pruneSets(catalog) { const blobs = /* @__PURE__ */ new Map(), packs = /* @__PURE__ */ new Map(), protectedBlobs = /* @__PURE__ */ new Set(), protectedPacks = /* @__PURE__ */ new Set(), profiles2 = []; const note = (sizes, hash, size) => { if (sizes.has(hash) && sizes.get(hash) !== size) throw new Error(DISAGREE); sizes.set(hash, size); }; return { asset(asset2) { assetReference(asset2); validateCarrier(asset2, catalog); note(blobs, asset2.hash, asset2.size); }, packs() { for (const [hash, pack2] of Object.entries(catalog.packs)) { if (!/^[0-9a-f]{64}$/u.test(hash) || !Number.isSafeInteger(pack2.size) || pack2.size <= 0) throw new Error("Invalid snapshot pack"); note(packs, hash, pack2.size); } }, async plan(plan, find, work = cooperativeWork()) { profiles2.push(plan.profile); const required = new Set(plan.requiredCategories); if ([...required].some((key) => !plan.backgroundCategories.includes(key))) throw new Error("Required category missing from background"); for (const key of plan.backgroundCategories) { const category2 = plan.categories[key]; if (!category2) throw new Error("Snapshot category missing"); for (const asset2 of category2.assets) { const expected = find(asset2.path); if (!expected || expected.hash !== asset2.hash || expected.size !== asset2.size) throw new Error("Category does not match its logical corpus"); if (asset2.carrier.kind === "loose" || required.has(key)) protectedBlobs.add(asset2.hash); if (asset2.carrier.kind === "pack") { if (!packs.has(asset2.carrier.packHash) || !category2.packs.includes(asset2.carrier.packHash)) throw new Error("Category does not name its carrier pack"); protectedPacks.add(asset2.carrier.packHash); } const pause3 = work.checkpoint(); if (pause3) await pause3; } for (const hash of category2.packs) { if (!packs.has(hash)) throw new Error("Protected pack is unknown"); protectedPacks.add(hash); } } }, result() { if (!bothProfiles(profiles2)) throw new Error("Prune snapshot needs both desktop profiles"); return { blobs, packs, protectedBlobs, protectedPacks }; } }; } function table(hashes, sizes = null) { const record7 = sizes ? SIZED : DIGEST, sorted = Array.from(hashes).sort(), result = new Uint8Array(sorted.length * record7), bytes = bytesOf(result); let at = 0; for (const hash of sorted) { if (typeof hash !== "string" || hash.length !== 64 || bytes.write(hash, at, DIGEST, "hex") !== DIGEST || bytes.toString("hex", at, at + DIGEST) !== hash) throw new Error("Prune summary cannot hold this digest"); if (sizes) { const size = sizes.get(hash); if (!Number.isSafeInteger(size) || size < 0) throw new Error("Prune summary cannot hold this size"); bytes.writeDoubleLE(size, at + DIGEST); } at += record7; } return result; } function encodePruneSummary({ blobs, packs, protectedBlobs, protectedPacks }) { return { blobs: table(blobs.keys(), blobs), packs: table(packs.keys(), packs), protectedBlobs: table(protectedBlobs), protectedPacks: table(protectedPacks) }; } function isPruneSummary(value) { return value !== null && typeof value === "object" && Object.keys(value).length === NAMES.length && NAMES.every((name) => value[name] instanceof Uint8Array && value[name].byteLength % RECORDS[name] === 0); } function union(left, right, record7) { if (!left.byteLength) return right; if (!right.byteLength) return left; const a = bytesOf(left), b = bytesOf(right), merged = Buffer.from(new ArrayBuffer(a.length + b.length)); let i = 0, j = 0, at = 0; while (i < a.length && j < b.length) { const order = a.compare(b, j, j + DIGEST, i, i + DIGEST); if (order === 0 && record7 === SIZED && a.readDoubleLE(i + DIGEST) !== b.readDoubleLE(j + DIGEST)) throw new Error(DISAGREE); if (order <= 0) { a.copy(merged, at, i, i + record7); i += record7; if (order === 0) j += record7; } else { b.copy(merged, at, j, j + record7); j += record7; } at += record7; } if (i < a.length) at += a.copy(merged, at, i); if (j < b.length) at += b.copy(merged, at, j); return new Uint8Array(merged.buffer.slice(0, at)); } function mergePruneSummaries(left, right) { if (left === null) return right; return Object.fromEntries(NAMES.map((name) => [name, union(left[name], right[name], RECORDS[name])])); } var DigestTable = class { #bytes; #record; // where the digests that begin with each two bytes start: a lookup then searches half a dozen records, not 400 000 #starts = new Uint32Array(65537); constructor(bytes, record7) { this.#bytes = bytesOf(bytes); this.#record = record7; const count2 = this.size; for (let row = 0, bucket = 0; bucket <= 65536; bucket++) { while (row < count2 && this.#bytes.readUInt16BE(row * record7) < bucket) row++; this.#starts[bucket] = row; } } get size() { return this.#bytes.length / this.#record; } #find(hash) { if (typeof hash !== "string" || hash.length !== 64) return -1; const key = Buffer.from(hash, "hex"); if (key.length !== DIGEST) return -1; const bucket = key.readUInt16BE(0); for (let low = this.#starts[bucket], high = this.#starts[bucket + 1] - 1; low <= high; ) { const middle = low + high >>> 1, at = middle * this.#record, order = this.#bytes.compare(key, 0, DIGEST, at, at + DIGEST); if (order === 0) return at; if (order > 0) high = middle - 1; else low = middle + 1; } return -1; } has(hash) { return this.#find(hash) >= 0; } get(hash) { const at = this.#find(hash); return at < 0 || this.#record !== SIZED ? void 0 : this.#bytes.readDoubleLE(at + DIGEST); } /** Every digest in order, as text (tests and diagnostics: this allocates what the table avoids). */ *hashes() { for (let at = 0; at < this.#bytes.length; at += this.#record) yield this.#bytes.toString("hex", at, at + DIGEST); } }; function pruneLookups(summary) { const of = (name) => new DigestTable(summary?.[name] ?? new Uint8Array(0), RECORDS[name]); return { blob: { retained: of("blobs"), protected: of("protectedBlobs") }, pack: { retained: of("packs"), protected: of("protectedPacks") } }; } // src/electron/khaos/assetMetadata.js var MAX_METADATA_BYTES = 320 * 1024 * 1024; var MAX_PACK_BYTES = 8 * 1024 * 1024; var PROFILES = ["desktop-bc7", "desktop-compatibility"]; var MetadataIntegrityError = class extends Error { constructor(message3) { super(message3); this.name = "AssetMetadataIntegrityError"; } }; function invalid(context, requirement) { const error = new Error(`${context}: ${requirement}`); error.name = "ContractError"; throw error; } var expect = (condition, context, requirement) => { if (!condition) invalid(context, requirement); }; var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var text2 = (value, context) => { expect(typeof value === "string" && value.length > 0, context, "expected a nonempty string"); return value; }; var canonicalText2 = (value, context) => { text2(value, context); expect(value.trim() === value && !/[\u0000-\u001f\u007f]/u.test(value), context, "noncanonical text"); return value; }; var integer2 = (minimum = 0, maximum = Number.MAX_SAFE_INTEGER) => (value, context) => { expect(Number.isSafeInteger(value) && value >= minimum && value <= maximum, context, `expected integer in ${minimum}..${maximum}`); return value; }; var digest2 = (value, context) => { expect(typeof value === "string" && /^[0-9a-f]{64}$/.test(value), context, "expected lowercase SHA-256"); return value; }; var choice = (...values) => (value, context) => { expect(values.includes(value), context, `expected ${values.join(" or ")}`); return value; }; var assetPath = (value, context) => { canonicalText2(value, context); expect(!/[\\?#]/u.test(value) && value.split("/").every((segment) => segment && segment !== "." && segment !== ".."), context, "expected relative POSIX path"); return value; }; var contentType = (value, context) => { text2(value, context); expect(/^[^\s/;]+\/[^\s;]+(?:\s*;\s*[^\s=;]+=[^;]+)*$/.test(value), context, "invalid content type"); return value; }; function record4(value, fields3, context) { expect(isRecord(value), context, "expected object"); const names = Object.keys(fields3); expect(Object.keys(value).length === names.length && names.every((key) => Object.hasOwn(value, key)), context, "unexpected or missing fields"); return Object.fromEntries(names.map((key) => [key, fields3[key](value[key], `${context}.${key}`)])); } var dictionary = (keyRule, valueRule) => (value, context) => { expect(isRecord(value), context, "expected dictionary"); const result = /* @__PURE__ */ Object.create(null); for (const [key, entry] of Object.entries(value)) result[keyRule(key, context)] = valueRule(entry, `${context}[${key}]`); return result; }; var list = (itemRule, uniqueKey) => (value, context) => { expect(Array.isArray(value), context, "expected array"); const items = value.map((entry, index) => itemRule(entry, `${context}[${index}]`)); if (uniqueKey) expect(new Set(items.map(uniqueKey)).size === items.length, context, "duplicate entries"); return items; }; var uniqueStrings = list(canonicalText2, (item) => item); var hashList = list(digest2, (item) => item); var carrier = (value, context) => { if (value?.kind === "loose") return record4(value, { kind: choice("loose") }, context); const result = record4(value, { kind: choice("pack"), packHash: digest2, offset: integer2(), length: integer2(1) }, context); expect(Number.isSafeInteger(result.offset + result.length), context, "pack range overflows"); return result; }; var assetFields = { hash: digest2, size: integer2(), contentType, carrier }; function checkAsset(entry, context, withPath = false) { const result = record4(entry, withPath ? { path: assetPath, ...assetFields } : assetFields, context); expect(result.carrier.kind !== "pack" || result.carrier.length === result.size, context, "packed length must equal logical size"); return result; } var asset = (entry, context) => checkAsset(entry, context); var listedAsset = (entry, context) => checkAsset(entry, context, true); var pack = (entry, context) => { const result = record4(entry, { path: assetPath, size: integer2(1, MAX_PACK_BYTES), memberCount: integer2(1), group: canonicalText2, tier: choice("base", "delta"), generation: canonicalText2, liveBytes: integer2(1) }, context); expect(result.liveBytes <= result.size, context, "live bytes exceed pack size"); return result; }; var category = (entry, context) => { const result = record4(entry, { label: canonicalText2, assetCount: integer2(), logicalBytes: integer2(), transferBytes: integer2(), packs: hashList, assets: list(listedAsset, (item) => item.path) }, context); expect(result.assetCount === result.assets.length, context, "asset count mismatch"); const logicalBytes = result.assets.reduce((sum, item) => sum + item.size, 0); expect(Number.isSafeInteger(logicalBytes) && logicalBytes === result.logicalBytes, context, "logical byte count mismatch"); const usedPacks = new Set(result.assets.filter((item) => item.carrier.kind === "pack").map((item) => item.carrier.packHash)); expect(result.packs.length === usedPacks.size && result.packs.every((hash) => usedPacks.has(hash)), context, "pack list mismatch"); return result; }; function decodeShard(value, shardId) { return record4(value, { schemaVersion: choice(3), shard: choice(shardId), assets: dictionary(assetPath, asset) }, "shard"); } function decodeCatalog(value) { const result = record4(value, { schemaVersion: choice(1), format: choice("raw-concat-catalog"), packs: dictionary(digest2, pack) }, "catalog"); for (const [hash, entry] of Object.entries(result.packs)) { expect(entry.path === `packs/sha256/${hash.slice(0, 2)}/${hash}.pack`, `catalog[${hash}]`, "pack path is not content-addressed"); } return result; } function sameAsset(left, right) { const a = left.carrier; const b = right.carrier; return left.hash === right.hash && left.size === right.size && left.contentType === right.contentType && a.kind === b.kind && (a.kind === "loose" || a.packHash === b.packHash && a.offset === b.offset && a.length === b.length); } function decodePlan(value, profile) { const result = record4(value, { schemaVersion: choice(1), format: choice("desktop-install-plan"), profile: choice(...PROFILES), requiredCategories: uniqueStrings, backgroundCategories: uniqueStrings, optionalCategories: uniqueStrings, categories: dictionary(canonicalText2, category) }, "install plan"); expect(result.profile === profile, "install plan", "profile mismatch"); const background = new Set(result.backgroundCategories); expect(result.requiredCategories.every((name) => background.has(name)), "install plan", "required category missing from background"); expect(result.optionalCategories.every((name) => !background.has(name)), "install plan", "optional category overlaps background"); const assigned = /* @__PURE__ */ new Set([...result.backgroundCategories, ...result.optionalCategories]); const names = Object.keys(result.categories); expect(names.length === assigned.size && names.every((name) => assigned.has(name)), "install plan", "unassigned or absent category"); const seen = /* @__PURE__ */ new Map(); for (const entry of Object.values(result.categories)) { for (const item of entry.assets) { if (seen.has(item.path)) expect(sameAsset(seen.get(item.path), item), item.path, "conflicting category entries"); else seen.set(item.path, item); } } return { value: result, itemCount: seen.size }; } function decodeMetadata(bytes, request, label = "asset metadata") { let parsed; try { parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch (cause) { throw new Error(`${label}: invalid UTF-8 JSON`, { cause }); } if (request.kind === "shard") { const value = decodeShard(parsed, request.shardId); return { kind: "shard", value, itemCount: Object.keys(value.assets).length }; } if (request.kind === "catalog") { const value = decodeCatalog(parsed); return { kind: "catalog", value, itemCount: Object.keys(value.packs).length }; } return { kind: "install-plan", ...decodePlan(parsed, request.profile) }; } async function verifyMetadataFile(filePath, integrity, label) { let file2; try { file2 = await (0, import_promises5.open)(filePath, "r"); } catch (error) { if (error.code === "ENOENT") throw new MetadataIntegrityError(`${label}: metadata file is missing`); throw error; } try { const stat4 = await file2.stat(); if (!stat4.isFile() || stat4.size !== integrity.size) throw new MetadataIntegrityError(`${label}: metadata size mismatch`); const hash = (0, import_node_crypto5.createHash)("sha256"); const chunks = []; let count2 = 0; for await (const chunk of file2.createReadStream({ start: 0, end: integrity.size, autoClose: false })) { count2 += chunk.length; hash.update(chunk); chunks.push(chunk); } if (count2 !== integrity.size || hash.digest("hex") !== integrity.hash) { throw new MetadataIntegrityError(`${label}: metadata differs from its immutable root reference`); } return Buffer.concat(chunks, count2); } finally { await file2.close(); } } var pruneArtifact = { filePath: text2, hash: digest2, size: integer2(0, MAX_METADATA_BYTES), itemCount: integer2() }; var pruneRequest = { kind: choice("prune-summary"), shardPrefixLength: integer2(1, 64), catalog: (value, context) => record4(value, pruneArtifact, context), shards: list((value, context) => record4(value, { id: text2, ...pruneArtifact }, context), (item) => item.id), plans: list((value, context) => record4(value, { profile: choice(...PROFILES), ...pruneArtifact }, context), (item) => item.profile), previous: (value, context) => { expect(value === null || isPruneSummary(value), context, "expected a prune summary"); return value; } }; async function summarizePruneSource(input, work = { checkpoint: () => null }) { const request = record4(input, pruneRequest, "prune request"), prefix = request.shardPrefixLength; const load = async (kind, id, reference, decoding) => { const label = `Asset metadata ${kind} ${id ?? ""}`; let bytes; try { bytes = await verifyMetadataFile(reference.filePath, reference, label); } catch (error) { if (error?.name === "AssetMetadataIntegrityError") error.artifact = { kind, id }; throw error; } const result = decodeMetadata(bytes, decoding, label); if (result.itemCount !== reference.itemCount) throw new Error("Immutable metadata item count differs from root"); return result.value; }; const catalog = await load("catalog", null, request.catalog, { kind: "catalog" }); const corpus = corpusValidation(catalog), sets = pruneSets(catalog), index = new AssetIndex("prune"); let assets = 0; for (const reference of request.shards) { const value = await load("shard", reference.id, reference, { kind: "shard", shardId: reference.id }), rows = []; for (const [logicalPath, entry] of Object.entries(value.assets)) { const pathDigest = manifestHash(logicalPath); if (pathDigest.substring(0, prefix) !== reference.id) throw new Error("Asset appears in incorrect manifest shard"); const asset2 = { path: logicalPath, ...entry }; assetReference(asset2); corpus.asset(asset2); sets.asset(asset2); rows.push([pathDigest, entry]); const pause3 = work.checkpoint(); if (pause3) await pause3; } index.addShard(reference.id, rows); assets += rows.length; } await corpus.packs(work); sets.packs(); const find = (logicalPath) => { const pathDigest = manifestHash(logicalPath), entry = index.find(pathDigest.substring(0, prefix), pathDigest); return entry ? { path: logicalPath, ...entry } : void 0; }; for (const reference of request.plans) { const plan = await load("plan", reference.profile, reference, { kind: "install-plan", profile: reference.profile }); await validateInstallPlan(plan, catalog, work); await corpus.plan(plan, reference.itemCount, find, work); await sets.plan(plan, find, work); } return { kind: "prune-summary", itemCount: assets, value: mergePruneSummaries(request.previous, encodePruneSummary(sets.result())) }; } // src/electron/khaos/assetTransfer.js var import_promises6 = __toESM(require("node:fs/promises"), 1); var import_node_path6 = __toESM(require("node:path"), 1); var import_node_crypto6 = require("node:crypto"); var AssetError = class extends Error { constructor(name, message3, details = {}) { super(message3); this.name = name; Object.assign(this, details); } }; var StaleManifestError = class extends AssetError { constructor(message3) { super("StaleManifestError", message3); } }; var causeText = (cause) => { const text3 = cause === void 0 || cause === null ? "" : String(cause?.message ?? cause).replace(/\s+/gu, " ").slice(0, 200); return text3 ? ` (${text3})` : ""; }; var AssetNetworkError = class extends AssetError { constructor(url, networkCause) { super("AssetNetworkError", `Asset network request failed: ${url}${causeText(networkCause)}`, { url, networkCause }); } }; var AssetStallError = class extends AssetError { constructor(url, phase, idleMs) { super("AssetStallError", `Asset transfer stalled: no ${phase === "headers" ? "response" : "data"} for ${Math.round(idleMs / 1e3)} s`, { url, phase, idleMs }); } }; var AssetHttpError = class extends AssetError { constructor(message3, status, url, retryAfterMs, classification) { super("AssetHttpError", message3, { status, url, retryAfterMs, classification }); } }; var AssetInMemoryLimitError = class extends AssetError { constructor(assetPath2, size, maximumBytes) { super("AssetInMemoryLimitError", `Asset ${assetPath2} exceeds the in-memory limit of ${maximumBytes} bytes`, { assetPath: assetPath2, size, maximumBytes }); } }; var AssetPackRangeUnsupportedError = class extends AssetError { constructor(message3) { super("AssetPackRangeUnsupportedError", message3); } }; var AssetMetadataLimitError = class extends AssetError { constructor(message3) { super("AssetMetadataStoredFileTooLargeError", message3); } }; function checkSignal(signal) { if (signal?.aborted) throw signal.reason ?? new DOMException("Asset operation stopped", "AbortError"); } function classifyAssetError(error) { const network = error?.name === "AssetNetworkError"; const http = ["AssetHttpError", "AssetPackHttpError"].includes(error?.name); const congestion = network || http && ([408, 425, 429].includes(error.status) || error.status >= 500); return { retry: congestion, congestion, retryAfterMs: error?.name === "AssetHttpError" ? error.retryAfterMs : null }; } function retryDelay(value) { if (value === null) return null; if (/^[0-9]+$/u.test(value)) { const milliseconds = Number(value) * 1e3; return Number.isSafeInteger(milliseconds) ? milliseconds : null; } const date = Date.parse(value); return Number.isFinite(date) ? Math.max(0, date - Date.now()) : null; } var transientStatus = (status) => [408, 425, 429].includes(status) || status >= 500; var LAUNCHER_ERROR_HEADER = "x-khaos-asset-error"; function httpError(response, url, label) { const status = response.status, detail = response.headers.get(LAUNCHER_ERROR_HEADER); return new AssetHttpError(`${label}: ${status} ${url}${detail ? ` (${detail.slice(0, 300)})` : ""}`, status, url, retryDelay(response.headers.get("retry-after")), transientStatus(status) ? "congestion" : "terminal"); } async function discardResponse(response) { try { await response.body?.cancel(); } catch { } } function responseLength(response) { const value = response.headers.get("content-length"); if (value === null) return null; if (!/^(0|[1-9][0-9]*)$/u.test(value) || !Number.isSafeInteger(Number(value))) throw new StaleManifestError("Invalid asset Content-Length"); return Number(value); } async function consumeBody(body, signal, consume) { const reader = body.getReader(); const cancel = () => { void reader.cancel(signal.reason).catch(() => { }); }; signal?.addEventListener("abort", cancel, { once: true }); let finished = false; try { checkSignal(signal); for (; ; ) { const chunk = await reader.read(); checkSignal(signal); if (chunk.done) { finished = true; break; } await consume(chunk.value); } } finally { signal?.removeEventListener("abort", cancel); if (!finished) await reader.cancel().catch(() => { }); reader.releaseLock(); } } async function responseBytes(response, url, maximum, signal, onChunk = null) { let length; try { length = responseLength(response); if (length !== null && length > maximum) throw new AssetMetadataLimitError(`Asset response exceeds ${maximum} bytes`); } catch (error) { await discardResponse(response); throw error; } let count2 = 0; const chunks = []; if (response.body) { try { await consumeBody(response.body, signal, (chunk) => { count2 += chunk.byteLength; if (count2 > maximum) throw new AssetMetadataLimitError(`Asset response exceeds ${maximum} bytes`); chunks.push(chunk); if (onChunk) onChunk(chunk.byteLength); }); } catch (error) { checkSignal(signal); if (error instanceof AssetMetadataLimitError || error?.name === "AssetNetworkError") throw error; throw new AssetNetworkError(url, error); } } if (length !== null && count2 !== length) throw new StaleManifestError("Asset Content-Length differs from its body"); return Buffer.concat(chunks, count2); } function assetDirectory(root, logicalPath) { logicalAssetPath(logicalPath); const target = import_node_path6.default.resolve(root, ...logicalPath.split("/")); const relative = import_node_path6.default.relative(import_node_path6.default.resolve(root), target); if (import_node_path6.default.isAbsolute(relative) || relative.split(import_node_path6.default.sep)[0] === "..") throw new Error("Asset path escapes its storage root"); return target; } async function safeDirectory(root, directory) { const relative = import_node_path6.default.relative(root, directory); if (import_node_path6.default.isAbsolute(relative) || relative.split(import_node_path6.default.sep)[0] === "..") throw new Error("Metadata directory escapes its root"); const chain = [root]; for (const component of relative.split(import_node_path6.default.sep).filter(Boolean)) chain.push(import_node_path6.default.join(chain.at(-1), component)); for (const entry of chain) { try { const stat4 = await import_promises6.default.lstat(entry); if (!stat4.isDirectory() || stat4.isSymbolicLink()) throw new Error("Metadata directory is not a regular directory"); } catch (error) { if (error?.code !== "ENOENT") throw error; try { await import_promises6.default.mkdir(entry, { recursive: entry === root }); } catch (race) { if (race?.code !== "EEXIST") throw race; const appeared = await import_promises6.default.lstat(entry); if (!appeared.isDirectory() || appeared.isSymbolicLink()) throw new Error("Metadata directory changed during creation"); } } } } async function persistBytes(root, target, bytes) { await safeDirectory(import_node_path6.default.resolve(root), import_node_path6.default.dirname(target)); const temporary = import_node_path6.default.join(import_node_path6.default.dirname(target), `.${(0, import_node_crypto6.randomUUID)()}.tmp`); let handle; try { handle = await import_promises6.default.open(temporary, "wx", 384); await handle.writeFile(bytes); await handle.sync(); await handle.close(); handle = null; for (let retry = 0; ; retry += 1) { try { await import_promises6.default.rename(temporary, target); return; } catch (error) { if (retry === 19 || !["EBUSY", "EPERM"].includes(error?.code)) throw error; await new Promise((resolve) => setTimeout(resolve, 50)); } } } finally { await handle?.close().catch(() => { }); await import_promises6.default.rm(temporary, { force: true }).catch(() => { }); } } async function storedBytes(target, maximum) { try { const entry = await import_promises6.default.lstat(target); if (!entry.isFile() || entry.isSymbolicLink() || entry.size > maximum || !Number.isSafeInteger(entry.size)) throw new AssetMetadataLimitError("Stored metadata is not a bounded regular file"); } catch (error) { if (error?.code === "ENOENT") return null; throw error; } const handle = await import_promises6.default.open(target, "r"); try { const chunks = []; let size = 0; for await (const chunk of handle.createReadStream({ autoClose: false, start: 0, end: maximum })) { size += chunk.length; if (size > maximum) throw new AssetMetadataLimitError("Stored metadata grew beyond its bound"); chunks.push(chunk); } return Buffer.concat(chunks, size); } finally { await handle.close(); } } var verifiedBytes = (bytes, reference) => bytes !== null && bytes.byteLength === reference.size && manifestHash(bytes) === reference.hash; function meteredResponse(response, context) { if (!response.body) return response; const body = response.body.pipeThrough(new TransformStream({ transform(chunk, destination) { checkSignal(context.signal); context.reportNetworkBytes(chunk.byteLength); destination.enqueue(chunk); } })); return new Response(body, { headers: response.headers, status: response.status, statusText: response.statusText }); } var STALL_HEADER = "x-khaos-stall-ms"; var realTimers = { timeout: (operation, ms) => setTimeout(operation, ms), clear: (timer) => clearTimeout(timer) }; function unlessAborted(promise, signal) { if (signal.aborted) { promise.catch(() => { }); return Promise.reject(signal.reason); } return new Promise((resolve, reject) => { const stop = () => reject(signal.reason); signal.addEventListener("abort", stop, { once: true }); promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop)).catch(() => { }); }); } async function watchedFetch(fetcher, url, request, idleMs, { timers = realTimers, onStall = null } = {}) { if (!Number.isFinite(idleMs) || idleMs <= 0) return fetcher(url, request); const watchdog = new AbortController(), outer = request.signal; let timer = null; const disarm = () => { if (timer !== null) { timers.clear(timer); timer = null; } }; const arm = (phase) => { disarm(); timer = timers.timeout(() => { timer = null; const stall = new AssetStallError(url, phase, idleMs); watchdog.abort(stall); try { onStall?.(stall); } catch { } }, idleMs); timer?.unref?.(); }; const signal = outer ? AbortSignal.any([outer, watchdog.signal]) : watchdog.signal; arm("headers"); const pending = Promise.resolve().then(() => fetcher(url, { ...request, headers: { ...request.headers, [STALL_HEADER]: String(idleMs) }, signal })); let response; try { response = await unlessAborted(pending, signal); } catch (error) { if (signal.aborted) void pending.then((late) => late?.body?.cancel().catch(() => { }), () => { }); if (outer?.aborted) throw outer.reason ?? error; throw watchdog.signal.aborted ? watchdog.signal.reason : error; } finally { disarm(); } if (!response?.body) return response; const reader = response.body.getReader(); const failure3 = (error) => { if (outer?.aborted) return outer.reason ?? error; const cause = watchdog.signal.aborted ? watchdog.signal.reason : error; return cause?.name === "AssetNetworkError" ? cause : new AssetNetworkError(url, cause); }; const body = new ReadableStream({ async pull(destination) { arm("body"); let part; try { part = await unlessAborted(reader.read(), signal); } catch (error) { disarm(); const reason = failure3(error); watchdog.abort(reason); void reader.cancel(reason).catch(() => { }); destination.error(reason); return; } disarm(); if (part.done) destination.close(); else destination.enqueue(part.value); }, cancel(reason) { disarm(); watchdog.abort(reason); return reader.cancel(reason).catch(() => { }); } }, { highWaterMark: 0 }); return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers }); } // src/electron/khaos-delta.mjs var import_zlib = __toESM(require("zlib"), 1); var MAGIC = [87, 88, 68, 49]; var WXD_DEFAULT_MAX = 512 * 1024 * 1024; function applyKhaosDelta(oldBuf, delta, maxSize = WXD_DEFAULT_MAX) { const cap = Math.min(maxSize, WXD_DEFAULT_MAX); const d = import_zlib.default.gunzipSync(delta, { maxOutputLength: cap + Math.ceil(cap / 16) + 65536 }); for (let i = 0; i < 4; i++) if (d[i] !== MAGIC[i]) throw new Error("not a WXD1 delta"); const size = d[4] + d[5] * 256 + d[6] * 65536 + d[7] * 16777216; if (size > cap) throw new Error(`WXD1 declares ${size} bytes, more than the ${cap} allowed`); const out = Buffer.allocUnsafe(size); let p = 8; let w = 0; const read = () => { let n = 0; let mul = 1; for (; ; ) { if (p >= d.length) throw new Error("truncated WXD1 delta"); const b = d[p++]; n += (b & 127) * mul; if (b < 128) return n; mul *= 128; } }; for (; ; ) { if (p >= d.length) throw new Error("truncated WXD1 delta"); const op = d[p++]; if (op === 0) break; if (op === 1) { const off = read(); const len = read(); if (off + len > oldBuf.length || w + len > size) throw new Error("WXD1 copy out of range"); Buffer.from(oldBuf.buffer, oldBuf.byteOffset, oldBuf.byteLength).copy(out, w, off, off + len); w += len; } else if (op === 2) { const len = read(); if (p + len > d.length || w + len > size) throw new Error("WXD1 insert out of range"); d.copy(out, w, p, p + len); p += len; w += len; } else throw new Error(`WXD1 unknown op ${op}`); } if (w !== size) throw new Error("WXD1 size mismatch"); return out; } function artifactSlot(path22) { return String(path22).replace(/[0-9a-f]{64}/, "#"); } function rootArtifacts(manifest) { return [...Object.values(manifest.shards ?? {}), manifest.packCatalog, ...Object.values(manifest.installPlans ?? {})].filter(Boolean); } function khaosDeltaPath(newHash, oldHash) { return `asset-deltas/${newHash}.${oldHash}.wxd`; } // src/electron/khaos/assetCache.js var ROOT_FILE = "asset-manifest.json"; var LIMITS = { root: 4 << 20, shard: 32 << 20, catalog: 16 << 20, plan: 96 << 20, live: 64 << 20 }; var AVAILABLE = () => ({ status: "available", completion: null }); var packRecord = (hash, record7) => ({ hash, size: record7.size }); var memberRecord = (asset2) => ({ hash: asset2.hash, offset: asset2.carrier.offset, length: asset2.size }); var ordered = (record7) => Object.entries(record7).sort(([a], [b]) => a.localeCompare(b, "en")); var errorNamed = (error, names) => names.includes(error?.name); var SHA = /^[0-9a-f]{64}$/u; var VERIFY_ERRORS = ["AssetBlobHashMismatchError", "AssetBlobSizeMismatchError", "AssetHashMismatchError", "AssetSizeMismatchError"]; var LOCKED_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES"]); var RESUMABLE_LOOSE_BYTES = 8 << 20; var RANGE_RETRY_DELAYS_MS = [1e3, 3e3, 9e3]; var LOOSE_RETRY_DELAYS_MS = [500, 2e3]; var STALL_MS = Object.freeze({ live: 1e4, required: 2e4, background: 3e4 }); var RECORDED_STALLS = 10; function looseFailureKind(error) { if (error?.code === "ENOSPC" || error?.code === "EDQUOT") return "disk-full"; if (error?.name === "AssetNetworkError") return "network"; if (LOCKED_CODES.has(error?.code) || error?.name === "AssetPackLockOpenPermissionError") return "blocked"; if (errorNamed(error, VERIFY_ERRORS)) return error.blobMissing ? "vanished" : "mismatch"; if (error?.name === "StaleManifestError" && error.lengthMismatch) return "mismatch"; return null; } function failureDetails(error) { const details = { error: error?.name ?? typeof error, code: error?.code ?? null, message: String(error?.message ?? error).slice(0, 300) }; for (const key of ["expectedSize", "actualSize", "expectedHash", "actualHash", "blobMissing"]) if (error?.[key] !== void 0) details[key] = error[key]; const cause = error?.networkCause; if (cause !== void 0 && cause !== null) { details.cause = { error: cause?.name ?? typeof cause, code: cause?.code ?? null, message: String(cause?.message ?? cause).slice(0, 300) }; if (cause?.phase) details.cause.phase = cause.phase; } return details; } function responseDetails(response, now = Date.now()) { const header = (name) => response.headers?.get?.(name) ?? null; const date = header("date"), served = date === null ? NaN : Date.parse(date); return { status: response.status, contentLength: header("content-length"), contentEncoding: header("content-encoding"), etag: header("etag"), date, dateAgeS: Number.isFinite(served) ? Math.round((now - served) / 1e3) : null, lastModified: header("last-modified"), cfRay: header("cf-ray"), cfCacheStatus: header("cf-cache-status"), age: header("age") }; } var RECORDED_TRIES = 20; function pause(milliseconds, signal) { return new Promise((resolve, reject) => { const stop = () => { clearTimeout(timer); reject(signal.reason ?? new DOMException("Asset operation stopped", "AbortError")); }; const timer = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(); }, milliseconds); if (signal?.aborted) stop(); else signal?.addEventListener("abort", stop, { once: true }); }); } function normalizedUrl(value, base = false) { if (typeof value !== "string" || !value.trim()) throw new Error("Asset URL must be nonempty"); const trimmed = base ? value.trim().replace(/\/+$/u, "") : value.trim(); const parsed = new URL(trimmed); if (!["http:", "https:"].includes(parsed.protocol)) throw new Error("Asset transport requires HTTP or HTTPS"); return trimmed; } function requestedPath(value) { const url = new URL(value); if (url.protocol !== "dofus-assets:" || url.hostname !== "game") throw new Error("Unsupported asset protocol URL"); const segments = url.pathname.split("/").filter(Boolean); if (segments.length < 2) throw new Error("Asset URL needs a source and a path"); return logicalAssetPath(segments.slice(1).map(decodeURIComponent).join("/")); } function settledMemo(map, key, factory) { if (!map.has(key)) { const promise = Promise.resolve().then(factory); map.set(key, promise); void promise.catch(() => { if (map.get(key) === promise) map.delete(key); }); } return map.get(key); } async function storedWithSize(file2, size) { try { const stat4 = await import_promises7.default.stat(file2); return stat4.isFile() && stat4.size === size; } catch (error) { if (error.code === "ENOENT") return false; throw error; } } async function parallelMap(items, width, consume) { const results = []; for (let offset = 0; offset < items.length; offset += width) { results.push(...await Promise.all(items.slice(offset, offset + width).map(consume))); } return results; } var AssetCache = class { #options; #memo = /* @__PURE__ */ new Map(); // Khaos (asset-index 2026-11-09): what asset lookups read, kept when #memo is released (assetIndex.js). One per root // revision, normally one; a second only while operations of a replaced root are still running. #indexes = /* @__PURE__ */ new Map(); #completion = /* @__PURE__ */ new WeakMap(); #root = null; #refresh = null; // Index downloads in flight (install plans, catalog, shards: the loading screen's 5 % before the file check, owner // 2026-11-04): bytes received / expected, reset when a new batch starts after the last one ended. #metadata = { active: 0, bytesDone: 0, bytesTotal: 0 }; #metadataListeners = /* @__PURE__ */ new Set(); #generation = 0; #releaseTimer; #recordedTries = 0; #stalls = 0; #recordedStalls = 0; constructor(options) { const retained = options.retainedManifestCount ?? 2; if (typeof options.sourceKey !== "string" || !options.sourceKey.trim()) throw new Error("Asset cache source key is required"); if (!Number.isSafeInteger(retained) || retained < 1) throw new Error("Retained manifests must be a positive integer"); const remote = normalizedUrl(options.remoteBaseUrl, true); this.#options = { ...options, retainedManifestCount: retained, remoteBaseUrl: remote, manifestUrl: normalizedUrl(options.manifestUrl ?? `${remote}/${ROOT_FILE}`), manifestRoot: import_node_path7.default.resolve(options.manifestRoot), fetcher: options.fetcher ?? ((url, request) => fetch(url, { signal: request.signal, headers: request.headers })), validateRoot: options.validateRoot ?? (() => { }), createCooperativeWork: options.createCooperativeWork ?? cooperativeWork, heavyCacheReleaseMs: options.heavyCacheReleaseMs ?? 6e4, looseRetryDelaysMs: options.looseRetryDelaysMs ?? LOOSE_RETRY_DELAYS_MS, resumableLooseBytes: options.resumableLooseBytes ?? RESUMABLE_LOOSE_BYTES, rangeRetryDelaysMs: options.rangeRetryDelaysMs ?? RANGE_RETRY_DELAYS_MS, record: typeof options.record === "function" ? options.record : null, // null: no stall watchdog (only the fetcher's own timeout) stallMs: options.stallMs === null ? null : { ...STALL_MS, ...options.stallMs } }; } get sourceKey() { return this.#options.sourceKey; } get remoteBaseUrl() { return this.#options.remoteBaseUrl; } get liveInflightCount() { return this.#options.blobStore.liveInflightCount; } /** Transfers this cache stopped because nothing came for too long (diagnostics, F11 reports). */ get stallCount() { return this.#stalls; } getTransportMode() { return this.#options.downloadCoordinator.getTransportMode(this.sourceKey); } setDownloadSpeedProfile(profile) { this.#options.downloadCoordinator.setSpeedProfile(profile); } async get(url, signal) { return this.#serve(requestedPath(url), signal, false); } async open(url, signal) { return this.#serve(requestedPath(url), signal, true); } async getManifestAsset(logicalPath, signal) { return this.#serve(logicalAssetPath(logicalPath), signal, false); } async #serve(logicalPath, signal, asFile) { return this.#options.blobStore.runLive(async () => { checkSignal(signal); if (logicalPath === ROOT_FILE) { const root = await this.#loadRoot(); return { bytes: root.sourceBytes, contentType: "application/json; charset=utf-8", source: "manifest", hash: root.revision, version: root.manifest.version }; } return this.#useRoot(async (root) => { const asset2 = await this.#resolve(root, logicalPath); if (asFile && asset2.carrier.kind === "loose") { let file2 = await this.#options.blobStore.openVerifiedFile(asset2.hash, asset2.size); const source = file2 === null ? "remote" : "local"; if (file2 === null) { await this.#downloadLoose(asset2, { priority: "live", signal }); file2 = await this.#options.blobStore.openVerifiedFile(asset2.hash, asset2.size); } if (file2 === null) throw new Error(`Verified asset file unavailable after transfer: ${logicalPath}`); return this.#representation(root, asset2, source, { file: file2 }); } if (asset2.size > LIMITS.live) throw new AssetInMemoryLimitError(logicalPath, asset2.size, LIMITS.live); const packed = await this.#readPack(root, asset2, signal); if (packed !== null) return this.#representation(root, asset2, "local-pack", { bytes: packed }); const resident = await this.#options.blobStore.readVerified(asset2.hash, asset2.size); if (resident !== null) return this.#representation(root, asset2, "local", { bytes: resident }); await this.#downloadAsset(root, asset2, { priority: "live", signal }); const bytes = await this.#readPack(root, asset2, signal) ?? await this.#options.blobStore.readVerified(asset2.hash, asset2.size); if (bytes === null) throw new Error(`Verified asset unavailable after transfer: ${logicalPath}`); return this.#representation(root, asset2, "remote", { bytes }); }); }); } #representation(root, asset2, source, body) { return Object.assign(body, { contentType: asset2.contentType, source, hash: asset2.hash, version: root.manifest.version }); } async openLocalManifestAssetFile(logicalPath) { return this.#assetFile(logicalAssetPath(logicalPath), false); } async ensureManifestAssetFile(logicalPath, signal) { return this.#assetFile(logicalAssetPath(logicalPath), true, signal); } #assetFile(logicalPath, ensure, signal) { return this.#useRoot(async (root) => { checkSignal(signal); const asset2 = await this.#resolve(root, logicalPath); let file2 = await this.#options.blobStore.openVerifiedFile(asset2.hash, asset2.size); if (ensure && file2 === null) { let bytes = await this.#readPack(root, asset2, signal); if (bytes === null) { await this.#downloadAsset(root, asset2, { priority: "live", signal }); bytes = await this.#readPack(root, asset2, signal); } if (bytes !== null) await this.#options.blobStore.ensure(asset2.hash, async () => bytes); file2 = await this.#options.blobStore.openVerifiedFile(asset2.hash, asset2.size); } if (ensure && file2 === null) throw new Error(`Asset file transfer produced no verified file: ${logicalPath}`); return file2 === null ? null : Object.assign({ file: file2, filePath: file2.filePath }, { hash: asset2.hash, size: asset2.size, contentType: asset2.contentType, version: root.manifest.version }); }); } async #readPack(root, asset2, signal) { if (asset2.carrier.kind !== "pack") return null; const catalog = await this.#packSizes(root); validateCarrier(asset2, catalog); const pack2 = packRecord(asset2.carrier.packHash, catalog.packs[asset2.carrier.packHash]); try { return await this.#options.packStore.readInstalledMember(pack2, memberRecord(asset2), signal); } catch (error) { checkSignal(signal); if (errorNamed(error, ["AssetPackLocalCorruptionError"])) await this.#options.packStore.discardCorruptPack(pack2); else if (!errorNamed(error, ["AssetPackLockOpenPermissionError"])) throw error; return null; } } async listAssets(prefixes) { prefixes.forEach(logicalAssetPrefix); return this.#useRoot(async (root) => ({ version: root.manifest.version, revision: root.revision, coverage: "complete", assets: (await this.#corpus(root)).assets.filter((asset2) => prefixes.some((prefix) => asset2.path.startsWith(prefix))) })); } async loadInstallPlan(profile) { return this.#useRoot(async (root) => { const artifact = await this.#artifact(root, "plan", profile); const snapshot2 = Object.freeze({ plan: artifact.value, hash: artifact.ref.hash }); this.#completion.set(snapshot2, requiredCompletionDescriptor(this.sourceKey, snapshot2)); return snapshot2; }); } #descriptor(snapshot2) { const descriptor = this.#completion.get(snapshot2); if (!descriptor) throw new Error("Required completion requires a snapshot from this asset cache"); return descriptor; } async checkRequiredInstallCompletion(snapshot2, signal) { return this.#options.completionStore.checkRequiredCompletion(this.#descriptor(snapshot2), signal); } async recordRequiredInstallCompletion(snapshot2, completion, signal) { return completion === null ? Promise.resolve(false) : this.#options.completionStore.recordRequiredCompletion(this.#descriptor(snapshot2), completion, signal); } async probePackTransport(options) { return this.#useRoot((root) => this.#probe(root, options)); } /** * The hashes of `assets` already on disk. `onProgress(count)` reports assets as they are checked (a pack's members * at once, then every loose file): the install scan's counter, which once sat silent for minutes. */ async findAvailableAssetHashes(assets, signal, onProgress = null) { checkSignal(signal); const report = typeof onProgress === "function" ? onProgress : () => { }; return this.#useRoot(async (root) => { const catalog = (await this.#artifact(root, "catalog")).value; const grouped = /* @__PURE__ */ new Map(); for (const asset2 of assets) { assetReference(asset2); validateCarrier(asset2, catalog); if (asset2.carrier.kind === "pack") { const hash = asset2.carrier.packHash; if (!grouped.has(hash)) grouped.set(hash, []); grouped.get(hash).push(asset2.hash); } } const available = /* @__PURE__ */ new Set(); await parallelMap([...grouped], 8, async ([hash, members]) => { checkSignal(signal); if (await this.#options.packStore.hasPack(packRecord(hash, catalog.packs[hash]), signal)) { members.forEach((member) => available.add(member)); report(members.length); } checkSignal(signal); }); const loose = uniqueHashSizes(assets).filter((asset2) => !available.has(asset2.hash)); if (loose.length) for (const hash of await this.#options.blobStore.findReceiptVerifiedHashes(loose, signal, () => report(1))) available.add(hash); return available; }); } async ensureInstallPack(hash, options) { return this.#useRoot(async (root) => { const entry = (await this.#artifact(root, "catalog")).value.packs[hash]; if (!entry) throw new Error(`Pack is absent from corpus: ${hash}`); return this.#downloadPack(hash, entry, options); }); } async ensureInstallAsset(asset2, options) { assetReference(asset2); return this.#useRoot(async (root) => { checkSignal(options.signal); if (await this.#options.blobStore.hasVerifiedBlob(asset2.hash, asset2.size, options.signal)) return AVAILABLE(); const catalog = (await this.#artifact(root, "catalog")).value; validateCarrier(asset2, catalog); if (asset2.carrier.kind === "pack") { const hash = asset2.carrier.packHash, record7 = catalog.packs[hash]; if (await this.#options.packStore.hasPack(packRecord(hash, record7), options.signal)) return AVAILABLE(); return this.#downloadPack(hash, record7, options); } return this.#ensureLoose(asset2, options); }); } async hasBlob(hash) { return this.#options.blobStore.hasBlob(hash); } async findExistingBlobHashes(hashes) { return this.#options.blobStore.findExistingHashes(hashes); } async ensureBlob(asset2, _legacyUnused, options = { priority: "required" }) { assetReference(asset2); await this.#ensureLoose(asset2, options); } async ensureContentAddressedAsset(asset2, options) { assetReference(asset2); return this.#ensureLoose({ ...asset2, carrier: { kind: "loose" } }, options); } async collectManifestHashes() { return this.#useRoot(async (root) => { const hashes = /* @__PURE__ */ new Set(), work = this.#options.createCooperativeWork(); for (const asset2 of (await this.#corpus(root)).assets) { hashes.add(asset2.hash); const pause3 = work.checkpoint(); if (pause3) await pause3; } return hashes; }); } // Khaos (prune-pass 2026-11-09): what the storage pruner needs to know of this source, added to the summary of the // sources before it (pruneSummary.js). The whole corpus is read and checked for it by the metadata worker given as // `pruneSummarizer`, off this thread (without one: here, by the same code). This thread only sees to it that the // files are stored. Before, it loaded every one of them parsed and kept them a minute (loadPruneSnapshot): 5 to 7 s // of stalls a source (docs/client/load-latency.md section 9). async loadPruneSummary(previous = null) { return this.#useRoot(async (root) => { const started = performance.now(), artifacts = this.#corpusArtifacts(root); const describe = ({ ref, filePath }) => ({ filePath, hash: ref.hash, size: ref.size, itemCount: ref.itemCount }); const request = { kind: "prune-summary", shardPrefixLength: root.manifest.shardPrefixLength, catalog: describe(artifacts[0]), shards: artifacts.filter((artifact) => artifact.kind === "shard").map((artifact) => ({ id: artifact.id, ...describe(artifact) })), plans: artifacts.filter((artifact) => artifact.kind === "plan").map((artifact) => ({ profile: artifact.id, ...describe(artifact) })), previous }; const summarize = () => this.#options.pruneSummarizer ? this.#options.pruneSummarizer.summarizePrune(request) : summarizePruneSource(request, this.#options.createCooperativeWork()); let fetched = 0; await parallelMap(artifacts, 8, async (artifact) => { if (!await storedWithSize(artifact.filePath, artifact.ref.size)) { await this.#fetchArtifact(root, artifact.ref, artifact.filePath); fetched++; } }); let result; try { result = await summarize(); } catch (error) { const broken = error?.name === "AssetMetadataIntegrityError" && error.artifact ? artifacts.find((artifact) => artifact.kind === error.artifact.kind && artifact.id === error.artifact.id) : null; if (!broken) throw error; if (!verifiedBytes(await this.#readCandidate(broken.filePath, broken.ref.size), broken.ref)) { await this.#fetchArtifact(root, broken.ref, broken.filePath); fetched++; } result = await summarize(); } this.#options.trace?.({ k: "prune-source", source: this.sourceKey, ms: Math.round(performance.now() - started), assets: result.itemCount, fetched }); return result.value; }); } /** Every immutable file of a root's corpus (the catalog first, then the shards and both install plans) and where it is stored. */ #corpusArtifacts(root) { const item = (kind, id, ref, maximum) => { if (!ref || ref.size > maximum) throw new Error("Invalid or oversized immutable metadata reference"); return { kind, id, ref, filePath: this.#artifactFile(root, ref.hash) }; }; return [item("catalog", null, root.manifest.packCatalog, LIMITS.catalog), ...ordered(root.manifest.shards).map(([id, ref]) => item("shard", id, ref, LIMITS.shard)), ...manifestProfiles.map((profile) => item("plan", profile, root.manifest.installPlans[profile], LIMITS.plan))]; } async materializeManifestMetadata(options) { return this.#useRoot(async (root) => { const destination = import_node_path7.default.resolve(options.destinationRoot), corpus = await this.#corpus(root); const rootFilePath = assetDirectory(destination, ROOT_FILE); checkSignal(options.signal); await persistBytes(destination, rootFilePath, root.sourceBytes); const copied = /* @__PURE__ */ new Map(); for (const artifact of [...corpus.shards, corpus.catalog, ...Object.values(corpus.plans)]) { checkSignal(options.signal); const bytes = await storedBytes(artifact.filePath, artifact.ref.size); if (!verifiedBytes(bytes, artifact.ref)) throw new StaleManifestError("Metadata changed before materialization"); const filePath = assetDirectory(destination, artifact.ref.path); await persistBytes(destination, filePath, bytes); copied.set(artifact.ref.hash, { ...artifact, bytes, filePath }); } return { root, rootFilePath, shards: corpus.shards.map((artifact) => copied.get(artifact.ref.hash)), packCatalog: copied.get(corpus.catalog.ref.hash), installPlans: Object.fromEntries(manifestProfiles.map((profile) => [profile, copied.get(corpus.plans[profile].ref.hash)])), packs: ordered(corpus.catalog.value.packs).map(([hash, pack2]) => ({ hash, size: pack2.size, path: pack2.path })) }; }); } async seedManifestArtifacts(options) { const root = await this.#loadRoot(); const refs = [...ordered(root.manifest.shards).map(([, ref]) => ref), root.manifest.packCatalog, ...manifestProfiles.map((profile) => root.manifest.installPlans[profile])]; const result = { revision: root.revision, artifactCount: refs.length, artifactBytes: 0, storedCount: 0, storedBytes: 0, seededCount: 0, seededBytes: 0 }; for (const ref of refs) { checkSignal(options.signal); result.artifactBytes += ref.size; const target = this.#artifactFile(root, ref.hash); if (verifiedBytes(await this.#readCandidate(target, ref.size), ref)) { result.storedCount++; result.storedBytes += ref.size; continue; } const candidate = await this.#readCandidate(assetDirectory(import_node_path7.default.resolve(options.sourceRoot), ref.path), ref.size); if (verifiedBytes(candidate, ref)) { await persistBytes(this.#options.manifestRoot, target, candidate); result.seededCount++; result.seededBytes += ref.size; } } return result; } async refreshManifestIndex() { return (await this.#freshRoot()).revision; } /** * `listener({ bytesDone, bytesTotal })` is told about the index files (install plans, catalog, shards) this cache * downloads, as they arrive. Returns the function that stops it. */ onMetadataProgress(listener) { if (typeof listener !== "function") throw new TypeError("Metadata progress listener must be a function"); this.#metadataListeners.add(listener); return () => this.#metadataListeners.delete(listener); } #metadataChanged() { const snapshot2 = { bytesDone: this.#metadata.bytesDone, bytesTotal: this.#metadata.bytesTotal }; for (const listener of this.#metadataListeners) { try { listener(snapshot2); } catch { } } } async #metadataBytes(url, ref) { const metadata = this.#metadata; if (metadata.active === 0) { metadata.bytesDone = 0; metadata.bytesTotal = 0; } metadata.active += 1; metadata.bytesTotal += ref.size; let received = 0; this.#metadataChanged(); try { const response = await this.#request(url, { expectedBytes: ref.size }); if (response.status !== 200) { const error = response.status === 404 ? new StaleManifestError("Immutable metadata referenced by this root is unavailable") : httpError(response, url, "Asset metadata"); await discardResponse(response); throw error; } return await responseBytes(response, url, ref.size, void 0, (count2) => { received += count2; metadata.bytesDone += count2; this.#metadataChanged(); }); } catch (error) { metadata.bytesDone -= received; metadata.bytesTotal -= ref.size; this.#metadataChanged(); throw error; } finally { metadata.active -= 1; } } async manifestIdentity() { const root = await this.#loadRoot(); return { version: root.manifest.version, revision: root.revision }; } async clearManifests() { this.invalidateManifest(); await import_promises7.default.rm(this.#options.manifestRoot, { recursive: true, force: true }); } invalidateManifest() { this.#generation++; this.#root = null; this.#refresh = null; this.#memo.clear(); this.#indexes.clear(); clearTimeout(this.#releaseTimer); this.#releaseTimer = void 0; } /** * The lookup index of this root revision (assetIndex.js). It holds the shards that lookups asked for, each added * once it passed every check of #artifact, and it outlives #memo: the parsed shards go a minute after their last * load, the index stays until the root changes (#freshRoot, invalidateManifest). The same revision names the same * shard digests, so a manifest refresh that finds the same root keeps it. */ #index(root) { let index = this.#indexes.get(root.revision); if (index === void 0) { if (this.#indexes.size >= 2) this.#indexes.delete(this.#indexes.keys().next().value); index = new AssetIndex(root.revision); this.#indexes.set(root.revision, index); } return index; } /** Pack sizes of the verified catalog, kept with the index: a packed read needs nothing else of the catalog. */ async #packSizes(root) { let index = this.#index(root); if (index.catalog === null) { const catalog = (await this.#artifact(root, "catalog")).value; index = this.#index(root); if (index.catalog === null) index.setCatalog(catalog); } return index.catalog; } #remember(root, kind, factory) { clearTimeout(this.#releaseTimer); this.#releaseTimer = setTimeout(() => { const kept = [...this.#indexes.values()]; this.#options.trace?.({ k: "index-release", source: this.sourceKey, entries: this.#memo.size, keptShards: kept.reduce((sum, index) => sum + index.shardCount, 0), keptAssets: kept.reduce((sum, index) => sum + index.assetCount, 0), keptBytes: kept.reduce((sum, index) => sum + index.byteLength, 0) }); this.#memo.clear(); try { this.#options.releaseMemory?.(); } catch { } }, this.#options.heavyCacheReleaseMs); this.#releaseTimer.unref?.(); return settledMemo(this.#memo, `${root.revision}/${kind}`, factory); } #loadRoot() { if (this.#root === null) { const generation = this.#generation; const load = (async () => { for (const directory of await this.#directories()) { const bytes = await this.#readCandidate(import_node_path7.default.join(directory.path, ROOT_FILE), LIMITS.root); if (bytes === null) continue; let root; try { root = parseManifest(bytes); } catch { continue; } if (directory.name !== import_node_path7.default.basename(this.#rootDirectory(root))) continue; this.#options.validateRoot(root.manifest); return root; } return this.#fetchRoot(); })(); this.#root = load; void load.catch(() => { if (this.#generation === generation && this.#root === load) this.#root = null; }); } return this.#root; } #freshRoot() { if (this.#refresh === null) { const generation = this.#generation; const fetch2 = this.#fetchRoot().then((root) => { if (this.#generation === generation) { this.#memo.clear(); this.#root = Promise.resolve(root); for (const revision of [...this.#indexes.keys()]) if (revision !== root.revision) this.#indexes.delete(revision); } return root; }); this.#refresh = fetch2; void fetch2.finally(() => { if (this.#refresh === fetch2) this.#refresh = null; }).catch(() => { }); } return this.#refresh; } async #useRoot(operation) { const root = await this.#loadRoot(); try { return await operation(root); } catch (error) { if (error?.name !== "StaleManifestError") throw error; const fresh = await this.#freshRoot(); if (fresh.revision === root.revision) throw error; return operation(fresh); } } async #fetchRoot() { const url = new URL(this.#options.manifestUrl); url.searchParams.set("t", String(Date.now())); const response = await this.#request(url.toString(), {}); if (response.status !== 200) { const error = httpError(response, url.toString(), "Manifest request"); await discardResponse(response); throw error; } const root = parseManifest(await responseBytes(response, url.toString(), LIMITS.root)); this.#options.validateRoot(root.manifest); await persistBytes(this.#options.manifestRoot, import_node_path7.default.join(this.#rootDirectory(root), ROOT_FILE), root.sourceBytes); const directories = await this.#directories(); const keep = /* @__PURE__ */ new Set([this.#rootDirectory(root), ...directories.map((entry) => entry.path).filter((entry) => entry !== this.#rootDirectory(root)).slice(0, this.#options.retainedManifestCount - 1)]); for (const directory of directories) if (!keep.has(directory.path)) await import_promises7.default.rm(directory.path, { recursive: true, force: true }); return root; } async #resolve(root, logicalPath) { const digest4 = manifestHash(logicalPath), id = digest4.substring(0, root.manifest.shardPrefixLength); const ref = root.manifest.shards[id]; const missing = () => new AssetHttpError(`Asset absent from complete corpus: ${logicalPath}`, 404, `${this.remoteBaseUrl}/${logicalPath}`, null, "terminal"); if (!ref) throw missing(); let record7 = this.#index(root).find(id, digest4); if (record7 === void 0) { const shard = await this.#artifact(root, "shard", id, true); const index = this.#index(root); if (!index.hasShard(id)) index.addShard(id, Object.entries(shard.value.assets).map(([name, asset2]) => [manifestHash(name), asset2])); record7 = index.find(id, digest4); } if (!record7) throw missing(); return { path: logicalPath, ...record7 }; } /** `forLookup`: the shard is loaded to answer a lookup and goes into the lookup index once it is checked. */ #artifact(root, kind, id, forLookup = false) { return this.#remember(root, `${kind}/${id ?? ""}`, async () => { const descriptor = kind === "shard" ? { ref: root.manifest.shards[id], maximum: LIMITS.shard } : kind === "catalog" ? { ref: root.manifest.packCatalog, maximum: LIMITS.catalog } : { ref: root.manifest.installPlans[id], maximum: LIMITS.plan }; if (!descriptor.ref || descriptor.ref.size > descriptor.maximum) throw new Error("Invalid or oversized immutable metadata reference"); const { ref } = descriptor, target = this.#artifactFile(root, ref.hash), label = `Asset metadata ${kind} ${id ?? ""}`; const trace = this.#options.trace, t0 = trace ? performance.now() : 0; let bytes = await this.#readCandidate(target, ref.size); const t1 = trace ? performance.now() : 0; const stored = verifiedBytes(bytes, ref); const t2 = trace ? performance.now() : 0; if (!stored) await this.#fetchArtifact(root, ref, target); bytes = null; const request = kind === "shard" ? { kind, shardId: id } : kind === "catalog" ? { kind } : { kind: "install-plan", profile: id }; let parsed; try { if (!this.#options.metadataParser) parsed = decodeMetadata(await verifyMetadataFile(target, ref, label), request, label); else { const parser = this.#options.metadataParser; if (kind === "shard") parsed = await parser.parseShard(target, label, id, ref); if (kind === "catalog") parsed = await parser.parseCatalog(target, label, ref); if (kind === "plan") parsed = await parser.parseInstallPlan(target, label, id, ref); } } catch (error) { if (error?.name === "AssetMetadataIntegrityError") throw new StaleManifestError("Persisted metadata changed during validation"); throw error; } const t3 = trace ? performance.now() : 0; if (parsed.itemCount !== ref.itemCount) throw new Error("Immutable metadata item count differs from root"); if (kind === "shard") { const work = this.#options.createCooperativeWork(); const rows = forLookup && !this.#index(root).hasShard(id) ? [] : null; for (const [logicalPath, asset2] of Object.entries(parsed.value.assets)) { const digest4 = manifestHash(logicalPath); if (digest4.substring(0, root.manifest.shardPrefixLength) !== id) throw new Error("Asset appears in incorrect manifest shard"); assetReference({ path: logicalPath, ...asset2 }); rows?.push([digest4, asset2]); const pause3 = work.checkpoint(); if (pause3) await pause3; } if (rows) this.#index(root).addShard(id, rows); } if (kind === "plan") await validateInstallPlan(parsed.value, (await this.#artifact(root, "catalog")).value, this.#options.createCooperativeWork()); trace?.({ k: "index", source: this.sourceKey, kind, id: id ?? null, bytes: ref.size, items: ref.itemCount, stored, ms: Math.round(performance.now() - t0), read: +(t1 - t0).toFixed(1), hash: +(t2 - t1).toFixed(1), parse: +(t3 - t2).toFixed(1), check: +(performance.now() - t3).toFixed(1) }); return { ref, filePath: target, value: parsed.value }; }); } /** Stores an immutable metadata file that is not on disk as its root names it: from an older root, a delta, or the server. */ async #fetchArtifact(root, ref, target) { let bytes = await this.#restore(root, ref); if (bytes === null) { const url = new URL(ref.path, this.#options.manifestUrl); url.searchParams.set("v", ref.hash); bytes = await this.#metadataBytes(url.toString(), ref); if (!verifiedBytes(bytes, ref)) throw new StaleManifestError("Metadata digest differs from root reference"); } await persistBytes(this.#options.manifestRoot, target, bytes); } #corpus(root) { return this.#remember(root, "corpus", async () => { const shards = await parallelMap(ordered(root.manifest.shards), 8, ([id]) => this.#artifact(root, "shard", id)); const catalog = await this.#artifact(root, "catalog"); const plans = Object.fromEntries(await Promise.all(manifestProfiles.map(async (profile) => [profile, await this.#artifact(root, "plan", profile)]))); const assets = await validateCorpus(root, shards, catalog.value, Object.values(plans).map((plan) => plan.value), this.#options.createCooperativeWork()); return { root, shards, catalog, plans, assets }; }); } async #restore(root, ref) { const previous = (await this.#directories()).filter((directory) => directory.path !== this.#rootDirectory(root)); for (const directory of previous) { const bytes = await this.#readCandidate(import_node_path7.default.join(directory.path, "objects", `${ref.hash}.json`), ref.size); if (verifiedBytes(bytes, ref)) return bytes; } for (const directory of previous) { try { const bytes = await this.#readCandidate(import_node_path7.default.join(directory.path, ROOT_FILE), LIMITS.root); if (!bytes) continue; const older = parseManifest(bytes).manifest; const base = rootArtifacts(older).find((artifact) => artifactSlot(artifact.path) === artifactSlot(ref.path)); if (!base || base.hash === ref.hash) continue; const original = await this.#readCandidate(import_node_path7.default.join(directory.path, "objects", `${base.hash}.json`), base.size); if (!verifiedBytes(original, base)) continue; const url = new URL(khaosDeltaPath(ref.hash, base.hash), this.#options.manifestUrl).toString(); const response = await this.#request(url, { expectedBytes: ref.size }); if (response.status !== 200) { await discardResponse(response); continue; } const rebuilt = applyKhaosDelta(original, await responseBytes(response, url, ref.size), ref.size); if (verifiedBytes(rebuilt, ref)) return rebuilt; } catch { } } return null; } #rootDirectory(root) { return import_node_path7.default.join(this.#options.manifestRoot, `${root.manifest.version.replace(/[^A-Za-z0-9._-]/gu, "_")}-${root.revision}`); } #artifactFile(root, hash) { if (!SHA.test(hash)) throw new Error("Invalid immutable metadata digest"); return import_node_path7.default.join(this.#rootDirectory(root), "objects", `${hash}.json`); } async #readCandidate(target, maximum) { try { return await storedBytes(target, maximum); } catch (error) { if (error instanceof AssetMetadataLimitError) return null; throw error; } } async #directories() { let entries2; try { entries2 = await import_promises7.default.readdir(this.#options.manifestRoot, { withFileTypes: true }); } catch (error) { if (error.code === "ENOENT") return []; throw error; } const result = []; for (const entry of entries2) { if (!entry.isDirectory() || entry.isSymbolicLink() || !/^[A-Za-z0-9._-]+-[0-9a-f]{64}$/u.test(entry.name)) continue; const directory = import_node_path7.default.join(this.#options.manifestRoot, entry.name); try { result.push({ name: entry.name, path: directory, time: (await import_promises7.default.lstat(directory)).mtimeMs }); } catch (error) { if (error.code !== "ENOENT") throw error; } } return result.sort((a, b) => b.time - a.time); } /** Every HTTP request of this cache. `options.priority`: the coordinator lane, for the stall limit (STALL_MS). */ async #request(url, options) { checkSignal(options.signal); const limits = this.#options.stallMs, idleMs = limits === null ? 0 : limits[options.priority] ?? limits.required; try { return await watchedFetch(this.#options.fetcher, url, options, idleMs, { onStall: (stall) => this.#stalled(stall, options.priority) }); } catch (error) { checkSignal(options.signal); if (error?.name === "AssetNetworkError") throw error; throw new AssetNetworkError(url, error); } } /** One line in the main log per stall (an F11 report carries its tail), the first ones in the stability log too. */ #stalled(stall, priority) { this.#stalls += 1; const details = { url: String(stall.url).replace(/\?.*$/u, ""), phase: stall.phase, idleMs: stall.idleMs, priority: priority ?? "required", stalls: this.#stalls }; this.#options.logger?.warn?.("Asset transfer stalled; it is tried again", details); if (!this.#options.record || this.#recordedStalls >= RECORDED_STALLS) return; this.#recordedStalls += 1; try { this.#options.record(`ASSET STALL ${JSON.stringify(details).slice(0, 600)}`); } catch { } } #individual(asset2) { return { carrierHash: asset2.hash, byteLength: asset2.size, execute: (context) => this.#storeLoose(asset2, context) }; } #queue(carrier2, options, transport) { return this.#options.downloadCoordinator.enqueue(Object.assign({}, carrier2, { sourceKey: this.sourceKey, priority: options.priority, signal: options.signal, maxAttempts: options.maxAttempts, classifyError: classifyAssetError, transport })); } #downloadLoose(asset2, options) { return this.#queue(this.#individual(asset2), options, { kind: "individual" }); } async #ensureLoose(asset2, options) { checkSignal(options.signal); return await this.#options.blobStore.hasVerifiedBlob(asset2.hash, asset2.size, options.signal) ? AVAILABLE() : { status: "downloaded", completion: await this.#downloadLoose(asset2, options) }; } /** * One loose file from `ca/`, stored once its bytes match the manifest. * Khaos (asset-verify 2026-10-15): a beta tester's loading screen stopped at 100 % on "Asset verification failed: * data/items.bin" while the production file was good, because nothing downloaded it again for the same manifest * revision. Now a try that fails its check (wrong bytes or length, or a blob that is locked or gone right after it * was written) is downloaded again: three tries in all, and the last one skips the CDN cache. Every failed try is * logged with what the client saw. The final error carries `failureKind` for the player's message. Network errors * are left to the coordinator's own retries, and a full disk is reported at once. */ async #storeLoose(asset2, context) { const tries = this.#options.looseRetryDelaysMs.length + 1; const begin = this.#onceStarted(context); for (let attempt = 1; ; attempt += 1) { const evidence = { path: asset2.path, hash: asset2.hash, size: asset2.size, attempt, tries, url: `${this.remoteBaseUrl}/ca/${asset2.hash}` }; if (attempt > 1 && attempt === tries) evidence.url += `?khaos-retry=${Date.now()}`; try { await this.#storeLooseOnce(asset2, context, evidence, begin); if (attempt > 1) this.#options.logger?.info?.("Asset transfer verified on a later try", { path: asset2.path, attempt }); context.reportVerifiedBytes(asset2.size); return; } catch (error) { checkSignal(context.signal); const kind = looseFailureKind(error); if (kind === null) { if (error?.name === "AssetHttpError" && error.classification === "congestion") { Object.assign(evidence, failureDetails(error), { kind: "server" }); this.#options.logger?.warn?.("Asset transfer failed", evidence); this.#recordTry(evidence); } throw error; } Object.assign(evidence, failureDetails(error), { kind }); this.#options.logger?.warn?.("Asset transfer failed", evidence); this.#recordTry(evidence); if (kind === "disk-full" || kind === "network" || attempt >= tries) throw this.#looseFailure(asset2, kind, error, evidence); if (await this.#verifiedNow(asset2, context.signal)) { context.reportVerifiedBytes(asset2.size); return; } await pause(this.#options.looseRetryDelaysMs[attempt - 1], context.signal); } } } /** * One stability-log line per failed try, at most RECORDED_TRIES per session. The main log is kept in memory only * (an F11 report carries its tail; the logs folder players zip has none of it), and the stability log is a file. */ #recordTry(evidence) { if (!this.#options.record || this.#recordedTries > RECORDED_TRIES) return; this.#recordedTries += 1; const line = this.#recordedTries > RECORDED_TRIES ? "ASSET TRY FAILED: more failed tries this session are not recorded" : `ASSET TRY FAILED ${JSON.stringify(evidence).slice(0, 1500)}`; try { this.#options.record(line); } catch { } } async #verifiedNow(asset2, signal) { try { return await this.#options.blobStore.hasVerifiedBlob(asset2.hash, asset2.size, signal); } catch (error) { checkSignal(signal); if (looseFailureKind(error) === null) throw error; return false; } } #looseFailure(asset2, kind, error, evidence) { const failure3 = kind === "mismatch" || kind === "vanished" ? new StaleManifestError(`Asset verification failed: ${asset2.path}`) : error; return Object.assign(failure3, { failureKind: kind, evidence: { ...evidence } }); } async #storeLooseOnce(asset2, context, evidence, begin) { if (asset2.size > this.#options.resumableLooseBytes && typeof this.#options.blobStore.ensureStoredResumable === "function") return this.#storeLooseResumable(asset2, context, evidence, begin); const url = evidence.url; await this.#options.blobStore.ensureStored(asset2.hash, asset2.size, async (write, signal) => { const response = await this.#request(url, { expectedBytes: asset2.size, signal, priority: context.priority }); begin(); Object.assign(evidence, responseDetails(response), { receivedBytes: 0 }); if (response.status !== 200) { const error = response.status === 404 ? new StaleManifestError("Content-addressed asset is unavailable") : httpError(response, url, "Asset transfer"); await discardResponse(response); throw error; } let writeError = null; try { const length = responseLength(response); if (length !== null && length !== asset2.size) throw Object.assign(new StaleManifestError("Asset response length differs from manifest"), { lengthMismatch: true }); if (!response.body) throw new AssetNetworkError(url, new Error("Asset response has no body")); await consumeBody(response.body, signal, async (chunk) => { evidence.receivedBytes += chunk.byteLength; context.reportNetworkBytes(chunk.byteLength); const started = performance.now(); try { await write(chunk); } catch (error) { writeError = error; throw error; } context.recordWriteDuration(performance.now() - started); }); } catch (error) { await discardResponse(response); checkSignal(signal); if (error !== writeError && error?.name !== "StaleManifestError" && error?.name !== "AssetNetworkError") throw new AssetNetworkError(url, error); throw error; } }, context.signal); } /** * A loose file larger than a pack (the 692 MB FMOD music bank) resumes where a cut transfer stopped (owner * 2026-11-04): BlobStore.ensureStoredResumable keeps the bytes in `.part`, and this asks for the rest with * `Range: bytes=-`. A 206 must describe exactly that range; a 200 (a server or proxy that ignores Range) starts * the file over. A cut connection is still a network failure for the coordinator's retries, which now carry on from * the part instead of from zero, as does the next start of the client. */ async #storeLooseResumable(asset2, context, evidence, begin) { const url = evidence.url; const stored = await this.#options.blobStore.ensureStoredResumable(asset2.hash, asset2.size, async (write, signal, { offset, restart }) => { const headers = offset > 0 ? { Range: `bytes=${offset}-` } : void 0; let response; for (let retry = 0; ; retry += 1) { response = await this.#request(url, { expectedBytes: asset2.size - offset, signal, headers, priority: context.priority }); if (!(offset > 0 && response.status === 200) || retry >= this.#options.rangeRetryDelaysMs.length) break; await discardResponse(response); evidence.rangeIgnored = retry + 1; this.#options.logger?.warn?.("Asset resume answered without its range; asking again", { path: asset2.path, offset, retry: retry + 1 }); await pause(this.#options.rangeRetryDelaysMs[retry], signal); } begin(); Object.assign(evidence, responseDetails(response), { receivedBytes: 0, offset }); const partial = offset > 0 && response.status === 206; if (response.status !== 200 && !partial) { const error = response.status === 404 ? new StaleManifestError("Content-addressed asset is unavailable") : httpError(response, url, "Asset transfer"); await discardResponse(response); throw error; } let writeError = null; try { const length = responseLength(response), expected = partial ? asset2.size - offset : asset2.size; if (partial && response.headers.get("content-range") !== `bytes ${offset}-${asset2.size - 1}/${asset2.size}`) throw Object.assign(new StaleManifestError("Asset Content-Range differs from the requested bytes"), { lengthMismatch: true }); if (length !== null && length !== expected) throw Object.assign(new StaleManifestError("Asset response length differs from manifest"), { lengthMismatch: true }); if (!response.body) throw new AssetNetworkError(url, new Error("Asset response has no body")); if (offset > 0 && !partial) { evidence.restarted = true; await restart(); } await consumeBody(response.body, signal, async (chunk) => { evidence.receivedBytes += chunk.byteLength; context.reportNetworkBytes(chunk.byteLength); const started = performance.now(); try { await write(chunk); } catch (error) { writeError = error; throw error; } context.recordWriteDuration(performance.now() - started); }); } catch (error) { await discardResponse(response); checkSignal(signal); if (error !== writeError && error?.name !== "StaleManifestError" && error?.name !== "AssetNetworkError") throw new AssetNetworkError(url, error); throw error; } }, context.signal); if (stored.resumedBytes > 0) { context.reportResumedBytes(stored.resumedBytes); this.#options.logger?.info?.("Asset transfer resumed", { path: asset2.path, resumedBytes: stored.resumedBytes, size: asset2.size }); } } async #downloadAsset(root, asset2, options) { if (asset2.carrier.kind !== "pack") return this.#downloadLoose(asset2, options); const catalog = (await this.#artifact(root, "catalog")).value; validateCarrier(asset2, catalog); const record7 = catalog.packs[asset2.carrier.packHash]; const carrierHash = manifestHash(`pack-member:${asset2.carrier.packHash}:${asset2.carrier.offset}:${asset2.size}:${asset2.hash}`); return this.#queue({ carrierHash, byteLength: asset2.size, execute: async (context) => { const begin = this.#onceStarted(context); try { const bytes = await this.#options.packStore.fetchMember(packRecord(asset2.carrier.packHash, record7), memberRecord(asset2), (request) => this.#packResponse(record7.path, request, context, begin), { signal: context.signal }); await this.#options.blobStore.ensure(asset2.hash, async () => bytes); context.reportVerifiedBytes(asset2.size); } catch (error) { if (errorNamed(error, ["AssetPackResponseContractError", "AssetPackMemberHashMismatchError", "AssetPackSizeMismatchError"])) throw new AssetPackRangeUnsupportedError(`Invalid packed asset transfer: ${asset2.path}`); throw error; } } }, options, { kind: "pack-member", individual: this.#wholePack(asset2.carrier.packHash, record7) }); } #onceStarted(context) { let started = false; return () => { if (!started) { started = true; context.markResponseStarted(); } }; } async #packResponse(logicalPath, request, context, begin) { const url = new URL(logicalPath, `${this.remoteBaseUrl}/`).toString(); const range = request.rangeHeader; const expectedBytes = range === null ? request.pack.size : request.rangeEnd - request.rangeStart + 1; const response = await this.#request(url, { expectedBytes, signal: request.signal, headers: range === null ? {} : { Range: range }, priority: context.priority }); begin(); if (response.status === 404) { await discardResponse(response); throw new StaleManifestError("Content-addressed pack is unavailable"); } if (![200, 206, 416].includes(response.status) && !response.ok) { const error = httpError(response, url, "Pack transfer"); await discardResponse(response); throw error; } return meteredResponse(response, context); } async #downloadPack(hash, record7, options) { checkSignal(options.signal); const pack2 = packRecord(hash, record7); if (await this.#options.packStore.hasPack(pack2, options.signal)) return AVAILABLE(); const completion = await this.#queue(this.#wholePack(hash, record7), options, { kind: "individual" }); return { status: "downloaded", completion }; } /** * The carrier of a whole pack: one GET without a byte range, stored in the pack store; installs and, when byte ranges * do not work (the "individual" transport mode), live reads of a packed file (its member is then read from the * pack). Khaos (F11 #121, 2026-11-17): that mode fetched packed files as loose `ca/` copies, which the CDN does * not keep, and a whole pack was refused outside the "pack" mode, so the mode lost most of the corpus. Outside the * "pack" mode a cut transfer starts over (the part is dropped); a resume answered without its range (the CDN does that * now and then) drops the part and asks for the pack whole at once, the mode unchanged. */ #wholePack(hash, record7) { const pack2 = packRecord(hash, record7); return { carrierHash: hash, byteLength: record7.size, execute: async (context) => { const begin = this.#onceStarted(context); const fetchPack = (request) => this.#packResponse(record7.path, request, context, begin); const store2 = (resume) => this.#options.packStore.ensurePack(pack2, fetchPack, { signal: context.signal, resume }); let result; try { const resume = this.getTransportMode() === "pack"; try { result = await store2(resume); } catch (error) { if (error?.name !== "AssetPackRangeUnsupportedError" || !resume) throw error; result = await store2(false); } } catch (error) { if (errorNamed(error, ["AssetPackHashMismatchError", "AssetPackSizeMismatchError"])) throw new StaleManifestError("Downloaded pack differs from corpus"); throw error; } context.reportResumedBytes(result.resumedBytes); context.reportVerifiedBytes(record7.size); } }; } async #probe(root, options) { if (this.getTransportMode() !== "unknown") return this.getTransportMode(); const first = ordered((await this.#artifact(root, "catalog")).value.packs)[0]; if (!first) { this.#options.downloadCoordinator.setTransportMode(this.sourceKey, "individual"); return "individual"; } const [hash, record7] = first, size = Math.min(record7.size, 2); try { await this.#queue({ carrierHash: manifestHash(`pack-probe:${this.sourceKey}:${hash}`), byteLength: size, execute: async (context) => { const url = new URL(record7.path, `${this.remoteBaseUrl}/`).toString(); const response = await this.#request(url, { expectedBytes: size, signal: context.signal, headers: { Range: `bytes=0-${size - 1}` }, priority: context.priority }); context.markResponseStarted(); if (response.status === 404) { await discardResponse(response); throw new StaleManifestError("Pack probe target is unavailable"); } if (transientStatus(response.status)) { const error = httpError(response, url, "Pack probe"); await discardResponse(response); throw error; } if (response.status !== 206 || response.headers.get("content-range") !== `bytes 0-${size - 1}/${record7.size}`) { await discardResponse(response); throw new AssetPackRangeUnsupportedError("Pack host does not satisfy a byte range"); } try { const bytes = await responseBytes(response, url, size, context.signal); if (bytes.byteLength !== size) throw new AssetPackRangeUnsupportedError("Pack probe body has wrong size"); context.reportNetworkBytes(size); context.reportVerifiedBytes(size); } catch (error) { if (errorNamed(error, ["StaleManifestError", "AssetMetadataStoredFileTooLargeError"])) throw new AssetPackRangeUnsupportedError("Pack probe body is invalid"); throw error; } } }, options); this.#options.downloadCoordinator.setTransportMode(this.sourceKey, "pack"); } catch (error) { if (error?.name !== "AssetPackRangeUnsupportedError") throw error; this.#options.downloadCoordinator.setTransportMode(this.sourceKey, "individual"); } return this.getTransportMode(); } }; // src/electron/khaos/blobStore.js var fs4 = __toESM(require("node:fs/promises"), 1); var import_node_path9 = __toESM(require("node:path"), 1); var import_node_crypto8 = require("node:crypto"); // src/electron/khaos/contentStorePrimitives.js var fs3 = __toESM(require("node:fs/promises"), 1); var import_node_path8 = __toESM(require("node:path"), 1); var import_node_crypto7 = require("node:crypto"); var digest3 = (bytes) => (0, import_node_crypto7.createHash)("sha256").update(bytes).digest("hex"); var allocatedBytes = (bytes) => 4096 * Math.ceil(bytes / 4096); function sha256(value) { if (typeof value !== "string" || value.length !== 64 || /[^a-f\d]/i.test(value)) throw new TypeError("A SHA-256 content address is required"); return value.toLowerCase(); } function assertContained(root, file2) { const relative = import_node_path8.default.relative(import_node_path8.default.resolve(root), import_node_path8.default.resolve(file2)); if (import_node_path8.default.isAbsolute(relative) || relative.split(import_node_path8.default.sep)[0] === "..") throw new Error("Content path leaves its configured cache"); } function assertSafeRoot(root) { const absolute = import_node_path8.default.resolve(root); if (absolute === import_node_path8.default.parse(absolute).root || absolute.split(import_node_path8.default.sep).filter(Boolean).length < 3) throw new Error("Content cache root is unsafe to clear"); } function abortCheck(signal) { if (signal?.aborted) throw signal.reason ?? new DOMException("Content operation cancelled", "AbortError"); } function raceAbort(operation, signal) { if (!signal) return Promise.resolve(operation); try { abortCheck(signal); } catch (error) { Promise.resolve(operation).catch(() => { }); return Promise.reject(error); } return new Promise((resolve, reject) => { const fail = () => reject(signal.reason ?? new DOMException("Content operation cancelled", "AbortError")); signal.addEventListener("abort", fail, { once: true }); Promise.resolve(operation).then(resolve, reject).finally(() => signal.removeEventListener("abort", fail)).catch(() => { }); }); } async function delay(ms, signal) { let timer; try { await raceAbort(new Promise((resolve) => { timer = setTimeout(resolve, ms); }), signal); } finally { clearTimeout(timer); } } async function retryFile(action) { const transient = /* @__PURE__ */ new Set(["EBUSY", "EACCES", "EPERM"]); for (let attempt = 0; ; attempt += 1) { try { return await action(); } catch (error) { if (!transient.has(error.code) || attempt === 4) throw error; await delay(20 * 2 ** attempt); } } } var removeFile = (file2) => retryFile(() => fs3.rm(file2, { force: true })); async function maybeStat(file2) { try { return await fs3.stat(file2, { bigint: true }); } catch (error) { if (error.code === "ENOENT") return null; throw error; } } function fingerprint(stat4) { return ["size", "mtimeNs", "ctimeNs", "birthtimeNs", "dev", "ino"].map((field) => String(stat4[field])); } var sameFingerprint = (left, right) => Array.isArray(left) && Array.isArray(right) && left.length === 6 && JSON.stringify(left) === JSON.stringify(right); async function readJson(file2, limit = 65536, signal) { abortCheck(signal); let handle; try { handle = await fs3.open(file2, "r"); } catch (error) { if (error.code === "ENOENT") return null; throw error; } try { const before = await handle.stat({ bigint: true }); if (!before.isFile() || before.size > BigInt(limit)) return null; let data; try { data = await readRange(handle, 0, Number(before.size), signal); } catch (error) { if (error.message === "Content file ended before the requested range") return null; throw error; } const tail = await handle.read(Buffer.alloc(1), 0, 1, Number(before.size)); if (tail.bytesRead) return null; const after = await handle.stat({ bigint: true }); const current = await maybeStat(file2); if (data.length > limit || data.length !== Number(before.size) || !current || !sameFingerprint(fingerprint(before), fingerprint(after)) || !sameFingerprint(fingerprint(current), fingerprint(after))) return null; try { return JSON.parse(data.toString("utf8")); } catch (error) { if (error instanceof SyntaxError) return null; throw error; } } finally { await handle.close(); } } async function atomicWrite(file2, data, root) { assertContained(root, file2); await fs3.mkdir(import_node_path8.default.dirname(file2), { recursive: true }); const temporary = `${file2}.khaos-${(0, import_node_crypto7.randomUUID)()}.tmp`; let handle; try { handle = await fs3.open(temporary, "wx"); await handle.writeFile(data); await handle.sync(); await handle.close(); handle = null; await retryFile(() => fs3.rename(temporary, file2)); } finally { await handle?.close().catch(() => { }); await removeFile(temporary); } } async function writeAll(handle, bytes, position) { let written = 0; while (written !== bytes.byteLength) { const next = await handle.write(bytes, written, bytes.byteLength - written, position + written); if (next.bytesWritten === 0) throw new Error("Content write made no progress"); written += next.bytesWritten; } } async function readRange(handle, offset, length, signal) { abortCheck(signal); const result = Buffer.allocUnsafe(length); let cursor = offset; const end = offset + length; while (cursor < end) { abortCheck(signal); const read = await handle.read(result, cursor - offset, end - cursor, cursor); if (!read.bytesRead) throw new Error("Content file ended before the requested range"); cursor += read.bytesRead; } return result; } async function hashRange(handle, offset, length, signal) { const hasher = (0, import_node_crypto7.createHash)("sha256"); for (let position = 0; position < length; position += 131072) { hasher.update(await readRange(handle, offset + position, Math.min(131072, length - position), signal)); } abortCheck(signal); return hasher.digest("hex"); } function checkRange(size, offset, length) { if (![size, offset, length].every(Number.isSafeInteger) || offset < 0 || length < 0 || offset > size - length) throw new RangeError("Content read range is outside the verified file"); } var ContentReader = class { constructor(handle, release, offset, size, details = {}) { Object.assign(this, details); this.handle = handle; this.release = release; this.offset = offset; this.rangeSize = size; this.operations = /* @__PURE__ */ new Set(); this.closePromise = null; } async read(offset, length, signal) { if (this.closePromise) return Promise.reject(new Error("Content reader is closed")); checkRange(this.rangeSize, offset, length); const operation = readRange(this.handle, this.offset + offset, length, signal); this.operations.add(operation); operation.finally(() => this.operations.delete(operation)).catch(() => { }); return operation; } close() { this.closePromise ??= (async () => { await Promise.allSettled([...this.operations]); try { await this.handle.close(); } finally { await this.release(); } })(); return this.closePromise; } }; function namedError(name, message3, properties = {}, cause) { const result = new Error(message3, cause ? { cause } : void 0); Object.assign(result, properties, { name }); return result; } function joinTask(task, signal) { task.waiters += 1; return raceAbort(task.promise, signal).finally(() => { task.waiters -= 1; if (!task.done && !task.waiters) task.controller.abort(new DOMException("No content consumers remain", "AbortError")); }); } function startTask(tasks, key, operation) { const task = { controller: new AbortController(), waiters: 0, done: false, promise: null }; tasks.set(key, task); task.promise = Promise.resolve().then(() => operation(task.controller.signal)); const finish = () => { task.done = true; if (tasks.get(key) === task) tasks.delete(key); }; task.promise.then(finish, finish); return task; } async function parallelMap2(values, limit, operation) { const entries2 = [...values]; const iterator = entries2.values(); const slots = Array.from({ length: Math.min(limit, entries2.length) }, async () => { for (const entry of iterator) await operation(entry); }); await Promise.all(slots); } function processAlive(pid) { if (!Number.isSafeInteger(pid) || pid < 1) return false; try { process.kill(pid, 0); return true; } catch (error) { return error.code !== "ESRCH"; } } var DiskLock = class { // `onLongWait({ lockPath, waitedMs, owner, ownerAlive, ageMs })` runs once per acquire that has waited longWaitMs: // a read waiting on a lock shows in the main log (an F11 report carries it) instead of hanging silently. constructor({ pollMs = 100, staleMs = 3e5, heartbeatMs = 1e4, longWaitMs = 1e4, onLongWait = null } = {}) { for (const value of [pollMs, staleMs, heartbeatMs, longWaitMs]) if (!Number.isSafeInteger(value) || value < 1) throw new TypeError("Lock timing must be a positive integer"); Object.assign(this, { pollMs, staleMs, heartbeatMs, longWaitMs, onLongWait }); } async tryAcquire(file2) { await fs3.mkdir(import_node_path8.default.dirname(file2), { recursive: true }); const token2 = (0, import_node_crypto7.randomUUID)(); let handle; try { handle = await fs3.open(file2, "wx"); } catch (error) { if (error.code === "EEXIST") return null; if (error.code === "EPERM") throw namedError("AssetPackLockOpenPermissionError", "Content lock cannot be opened", { lockPath: file2, permissionCause: error }, error); throw error; } try { await handle.writeFile(JSON.stringify({ token: token2, pid: process.pid, createdAt: Date.now() })); } catch (error) { await handle.close(); handle = null; await removeFile(file2); throw error; } finally { await handle?.close(); } const lock = { file: file2, token: token2, heartbeatError: null, touching: null }; lock.timer = setInterval(() => { if (lock.touching) return; lock.touching = this.touch(lock).catch((error) => { lock.heartbeatError = error; }).finally(() => { lock.touching = null; }); }, this.heartbeatMs); lock.timer.unref(); return lock; } async touch(lock) { if ((await readJson(lock.file, 4096))?.token !== lock.token) throw new Error("Content lock ownership changed"); const now = /* @__PURE__ */ new Date(); await fs3.utimes(lock.file, now, now); } async stale(file2) { const stat4 = await maybeStat(file2); if (!stat4) return true; const age = Date.now() - Number(stat4.mtimeMs); if (age < Math.min(this.staleMs, 2 * this.heartbeatMs)) return false; const owner = await readJson(file2, 4096).catch(() => null); const ownerGone = owner === null || Number.isSafeInteger(owner?.pid) && owner.pid !== process.pid && !processAlive(owner.pid); if (!ownerGone && age < this.staleMs) return false; if (owner?.pid === process.pid) return false; const again = await maybeStat(file2); if (again && sameFingerprint(fingerprint(stat4), fingerprint(again))) await removeFile(file2); return true; } async acquire(file2, signal) { const startedAt = Date.now(); let reported = false; for (; ; ) { abortCheck(signal); const lock = await this.tryAcquire(file2); if (lock) return lock; if (await this.stale(file2)) continue; if (!reported && this.onLongWait && Date.now() - startedAt >= this.longWaitMs) { reported = true; await this.reportLongWait(file2, Date.now() - startedAt); } await delay(this.pollMs, signal); } } async reportLongWait(file2, waitedMs) { try { const stat4 = await maybeStat(file2); const owner = await readJson(file2, 4096).catch(() => null); this.onLongWait({ lockPath: file2, waitedMs, owner, ownerAlive: processAlive(owner?.pid), ageMs: stat4 ? Date.now() - Number(stat4.mtimeMs) : null }); } catch { } } async release(lock) { clearInterval(lock.timer); await lock.touching; await retryFile(async () => { if ((await readJson(lock.file, 4096))?.token === lock.token) await removeFile(lock.file); }); } }; var LEASE_NAME = /\.lease\.(\d+)\.[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i; var ContentDisk = class { constructor(root, suffix, options = {}) { if (typeof root !== "string" || !root.trim()) throw new TypeError("A content cache root is required"); this.root = import_node_path8.default.resolve(root); this.suffix = suffix; this.locks = new DiskLock(options); this.readers = /* @__PURE__ */ new Map(); this.verified = /* @__PURE__ */ new Map(); this.access = /* @__PURE__ */ new Map(); this.validations = /* @__PURE__ */ new Map(); this.clearBarrier = `${this.root}.clear.lock`; } file(hash) { hash = sha256(hash); return import_node_path8.default.join(this.root, hash.substring(0, 2), hash + this.suffix); } receipt(hash) { return `${this.file(hash)}.verified.json`; } async waitBarrier(signal) { while (await maybeStat(this.clearBarrier)) { abortCheck(signal); if (!await this.locks.stale(this.clearBarrier)) await delay(this.locks.pollMs, signal); } } async lock(hash, signal, immediate = false, clearing = false) { for (; ; ) { if (!clearing) await this.waitBarrier(signal); const file2 = `${this.file(hash)}.lock`; const lock = immediate ? await this.locks.tryAcquire(file2) : await this.locks.acquire(file2, signal); if (!lock) return null; if (clearing || !await maybeStat(this.clearBarrier)) return lock; await this.locks.release(lock); if (immediate) return null; } } async lease(hash, signal) { let shared = this.readers.get(hash); if (!shared) { shared = { refs: 0, promise: null, path: null, controller: new AbortController(), ready: false }; this.readers.set(hash, shared); shared.promise = (async () => { const lock = await this.lock(hash, shared.controller.signal); try { shared.path = `${this.file(hash)}.lease.${process.pid}.${(0, import_node_crypto7.randomUUID)()}`; await fs3.writeFile(shared.path, JSON.stringify({ pid: process.pid, createdAt: Date.now() }), { flag: "wx" }); } finally { await this.locks.release(lock); } shared.ready = true; })(); const setup = shared; shared.promise.finally(async () => { if (!setup.refs) { if (this.readers.get(hash) === setup) this.readers.delete(hash); if (setup.path) await removeFile(setup.path); } }).catch(() => { }); } shared.refs += 1; try { await raceAbort(shared.promise, signal); } catch (error) { shared.refs -= 1; if (!shared.refs) { shared.controller.abort(error); if (this.readers.get(hash) === shared) this.readers.delete(hash); if (shared.ready && shared.path) await removeFile(shared.path); } throw error; } let closed = false; return async () => { if (closed) return; closed = true; shared.refs -= 1; if (!shared.refs) { if (this.readers.get(hash) === shared) this.readers.delete(hash); await removeFile(shared.path); } }; } async hasLease(hash) { const prefix = import_node_path8.default.basename(this.file(hash)) + ".lease."; const directory = import_node_path8.default.dirname(this.file(hash)); let names; try { names = await fs3.readdir(directory); } catch (error) { if (error.code === "ENOENT") return false; throw error; } for (const name of names.filter((entry) => entry.startsWith(prefix))) { const leasePath = import_node_path8.default.join(directory, name); const record7 = await readJson(leasePath, 4096); if (processAlive(record7?.pid)) return true; const stat4 = await maybeStat(leasePath); if (stat4 && Date.now() - Number(stat4.mtimeMs) < this.locks.staleMs) return true; await removeFile(leasePath); } return false; } async remember(hash, stat4) { const identity = fingerprint(stat4); const body = { format: "khaos-content-verification", version: 2, hash, identity }; await atomicWrite(this.receipt(hash), JSON.stringify({ ...body, signature: digest3(JSON.stringify(body)) }), this.root); this.verified.set(hash, identity); return identity; } async receiptMatches(hash, stat4, signal) { const receipt = await readJson(this.receipt(hash), 4096, signal); if (this.suffix === "" && receipt?.format === "khaos-asset-blob-verification" && receipt.schemaVersion === 1 && receipt.blobHash === hash) { const fields3 = ["format", "schemaVersion", "blobHash", "size", "mtimeNs", "ctimeNs", "birthtimeNs", "device", "inode"]; const body2 = Object.fromEntries(fields3.map((field) => [field, receipt[field]])); const oldIdentity = fields3.slice(3).map((field) => receipt[field]); return digest3(JSON.stringify(body2)) === receipt.signature && sameFingerprint(oldIdentity, fingerprint(stat4)); } if (receipt?.format !== "khaos-content-verification" || receipt.version !== 2 || receipt.hash !== hash) return false; const body = { format: receipt.format, version: receipt.version, hash: receipt.hash, identity: receipt.identity }; return digest3(JSON.stringify(body)) === receipt.signature && sameFingerprint(receipt.identity, fingerprint(stat4)); } async verify(handle, hash, size, signal, onHash) { const before = await handle.stat({ bigint: true }); if (!before.isFile() || size !== void 0 && before.size !== BigInt(size) || before.size > BigInt(Number.MAX_SAFE_INTEGER)) return false; const identity = fingerprint(before); if (!sameFingerprint(this.verified.get(hash), identity) && !await this.receiptMatches(hash, before, signal)) { const key = `${hash}:${identity.join(":")}`; const task = this.validations.get(key) ?? startTask(this.validations, key, async (validationSignal) => { let verifier; try { verifier = await fs3.open(this.file(hash), "r"); } catch (error) { if (error.code === "ENOENT") return false; throw error; } try { if (!sameFingerprint(identity, fingerprint(await verifier.stat({ bigint: true })))) return false; onHash?.(hash); if (await hashRange(verifier, 0, Number(before.size), validationSignal) !== hash) return false; const after = await verifier.stat({ bigint: true }); const current = await maybeStat(this.file(hash)); if (!current || !sameFingerprint(identity, fingerprint(after)) || !sameFingerprint(identity, fingerprint(current))) return false; await this.remember(hash, after); return true; } finally { await verifier.close(); } }); if (!await joinTask(task, signal)) return false; } abortCheck(signal); const final = await handle.stat({ bigint: true }); if (!sameFingerprint(identity, fingerprint(final))) return false; this.verified.set(hash, identity); this.access.set(hash, Date.now()); return true; } // `leases`, when given, receives the path of every lease file met on the way. async inventory(leases = null) { let folders; try { folders = await fs3.readdir(this.root, { withFileTypes: true }); } catch (error) { if (error.code === "ENOENT") return []; throw error; } const result = []; for (const folder of folders.filter((entry) => entry.isDirectory() && /^[a-f\d]{2}$/i.test(entry.name))) { const directory = import_node_path8.default.join(this.root, folder.name); let names; try { names = await fs3.readdir(directory); } catch (error) { if (error.code === "ENOENT") continue; throw error; } for (const name of names) { if (leases && LEASE_NAME.test(name)) { leases.push(import_node_path8.default.join(directory, name)); continue; } const hash = name.slice(0, 64).toLowerCase(); if (name !== hash + this.suffix || !/^[a-f\d]{64}$/.test(hash) || hash.substring(0, 2) !== folder.name.toLowerCase()) continue; const file2 = import_node_path8.default.join(directory, name); const stat4 = await maybeStat(file2); if (stat4?.isFile()) result.push({ hash, file: file2, size: Number(stat4.size), age: this.access.get(hash) ?? Number(stat4.mtimeMs) }); } } return result; } async removeIdle(entry) { if (this.readers.has(entry.hash)) return false; const lock = await this.lock(entry.hash, void 0, true); if (!lock) return false; try { if (this.readers.has(entry.hash) || await this.hasLease(entry.hash)) return false; const current = await maybeStat(entry.file); if (!current) return false; if (entry.identity && !sameFingerprint(entry.identity, fingerprint(current))) return false; await removeFile(entry.file); await removeFile(this.receipt(entry.hash)); this.verified.delete(entry.hash); this.access.delete(entry.hash); return true; } finally { await this.locks.release(lock); } } // Khaos (asset-fast-path 2026-11-09): a client that is killed leaves the leases of the packs it kept open (PackStore // pools them) and of its open files. Nothing looked at those of content that is kept, so they piled up; the pruner // now removes every lease whose process is gone, by the rule hasLease applies (the pid is in the name). async dropDeadLeases(files6) { for (const file2 of files6) { const pid = Number(LEASE_NAME.exec(file2)[1]); if (pid === process.pid || processAlive(pid)) continue; const stat4 = await maybeStat(file2); if (stat4 && Date.now() - Number(stat4.mtimeMs) >= this.locks.staleMs) await removeFile(file2).catch(() => { }); } } async prune(retained, options, pending, kind) { const { maxBytes, minAgeMs = 0, protectedHashes = /* @__PURE__ */ new Set() } = options; if (!(maxBytes >= 0) || !Number.isFinite(maxBytes) && maxBytes !== Infinity || !Number.isSafeInteger(minAgeMs) || minAgeMs < 0) throw new TypeError("Invalid content budget or minimum age"); const lookup = (hashes) => { if (typeof hashes?.[Symbol.iterator] === "function") return new Set([...hashes].map(sha256)); if (typeof hashes?.has !== "function") throw new TypeError("A set of content addresses is required"); return hashes; }; retained = lookup(retained); const protectedSet = lookup(protectedHashes); const leases = []; const entries2 = (await this.inventory(leases)).sort((left, right) => left.age - right.age); await this.dropDeadLeases(leases); const bytesBefore = entries2.reduce((total, item) => total + allocatedBytes(item.size), 0); let bytesAfter = bytesBefore; let count2 = 0; const cutoff = Date.now() - minAgeMs; let protectedBytes = 0; let turn = performance.now(); for (let index = 0; index < entries2.length; index++) { if ((index & 255) === 255 && performance.now() - turn >= 4) { await new Promise((resolve) => setImmediate(resolve)); turn = performance.now(); } const entry = entries2[index]; const guarded = protectedSet.has(entry.hash); if (guarded) protectedBytes += allocatedBytes(entry.size); if (pending.has(entry.hash) || entry.age > cutoff || retained.has(entry.hash) && (guarded || bytesAfter <= maxBytes)) continue; if (await this.removeIdle(entry)) { bytesAfter -= allocatedBytes(entry.size); count2 += 1; } } return { bytesBefore, bytesAfter, removedBytes: bytesBefore - bytesAfter, [kind]: count2, overBudgetBytes: Math.max(0, bytesAfter - maxBytes), protectedBytes }; } async clear() { assertSafeRoot(this.root); const barrier = await this.locks.acquire(this.clearBarrier); const locks = []; try { if (this.readers.size) throw new Error("Cannot clear content with open readers"); const hashes = new Set((await this.inventory()).map((entry) => entry.hash)); let folders = []; try { folders = await fs3.readdir(this.root, { withFileTypes: true }); } catch (error) { if (error.code !== "ENOENT") throw error; } for (const folder of folders.filter((entry) => entry.isDirectory() && /^[a-f\d]{2}$/i.test(entry.name))) { for (const name of await fs3.readdir(import_node_path8.default.join(this.root, folder.name))) { const address = name.slice(0, 64); if (/^[a-f\d]{64}$/i.test(address)) hashes.add(address.toLowerCase()); } } for (const hash of hashes) locks.push(await this.lock(hash, void 0, false, true)); for (const hash of hashes) if (await this.hasLease(hash)) throw new Error("Cannot clear content with a reader in another process"); await fs3.rm(this.root, { recursive: true, force: true }); this.verified.clear(); this.access.clear(); } finally { for (const lock of locks.reverse()) await this.locks.release(lock); await this.locks.release(barrier); } } }; // src/electron/khaos/blobStore.js var hashMismatch = (expectedHash, actualHash) => namedError("AssetBlobHashMismatchError", "Downloaded blob did not match its content address", { expectedHash, actualHash }); var sizeMismatch = (expectedSize, actualSize) => namedError("AssetBlobSizeMismatchError", "Downloaded blob length is incorrect", { expectedSize, actualSize }); function expectedLength(value) { if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) throw new TypeError("Expected blob size must be a nonnegative integer"); } var BlobStore = class { constructor(root, { onBlobHashRead, onLockWait } = {}) { this.disk = new ContentDisk(root, "", { onLongWait: onLockWait }); this.onHash = onBlobHashRead; this.pending = /* @__PURE__ */ new Map(); this.validations = /* @__PURE__ */ new Set(); this.live = 0; this.clearing = false; } get liveInflightCount() { return this.live; } async runLive(operation) { this.live += 1; try { return await operation(); } finally { this.live -= 1; } } blobPath(hash) { return this.disk.file(hash); } async hasBlob(hash) { return (await maybeStat(this.blobPath(hash)))?.isFile() ?? false; } async hasVerifiedBlob(hash, size, signal) { const reader = await this.openVerifiedFile(hash, size, signal); if (!reader) return false; await reader.close(); return true; } async openVerifiedFile(hash, size, signal) { hash = sha256(hash); expectedLength(size); abortCheck(signal); if (this.clearing) throw new Error("Blob store is being cleared"); const task = this.pending.get(hash); if (task) await joinTask(task, signal); const release = await this.disk.lease(hash, signal); let handle; let transferred = false; const validation = {}; this.validations.add(validation); try { try { handle = await fs4.open(this.blobPath(hash), "r"); } catch (error) { if (error.code === "ENOENT") return null; throw error; } if (!await this.disk.verify(handle, hash, size, signal, this.onHash)) { const identity = fingerprint(await handle.stat({ bigint: true })); await handle.close(); handle = null; await release(); const current = await maybeStat(this.blobPath(hash)); if (current && sameFingerprint(identity, fingerprint(current))) await this.disk.removeIdle({ hash, file: this.blobPath(hash), identity }); return null; } const length = Number((await handle.stat({ bigint: true })).size); const retained = handle; handle = null; transferred = true; return new ContentReader(retained, release, 0, length, { hash, filePath: this.blobPath(hash), fd: retained.fd, size: length }); } finally { this.validations.delete(validation); if (handle) await handle.close().catch(() => { }); if (!transferred) await release(); } } async readVerified(hash, size) { const file2 = await this.openVerifiedFile(hash, size); if (!file2) return null; try { return await file2.read(0, file2.size); } finally { await file2.close(); } } async findExistingHashes(hashes, signal) { const requested = new Set([...hashes].map(sha256)); const found = /* @__PURE__ */ new Set(); await parallelMap2(requested, 64, async (hash) => { abortCheck(signal); if (await this.hasVerifiedBlob(hash, void 0, signal)) found.add(hash); }); return found; } // `onChecked()` runs once per blob looked at, found or not (the loading screen's scan counter). async findReceiptVerifiedHashes(records, signal, onChecked = null) { const sizes = /* @__PURE__ */ new Map(); const found = /* @__PURE__ */ new Set(); for (const record7 of records) { const hash = sha256(record7.hash); expectedLength(record7.size); if (record7.size === void 0) throw new TypeError("Receipt lookup requires a blob size"); if (sizes.has(hash) && sizes.get(hash) !== record7.size) throw new Error("Conflicting blob receipt sizes"); sizes.set(hash, record7.size); } await parallelMap2(sizes, 64, async ([hash, size]) => { abortCheck(signal); const stat4 = await maybeStat(this.blobPath(hash)); if (stat4?.isFile() && stat4.size === BigInt(size) && await this.disk.receiptMatches(hash, stat4, signal)) { const current = await maybeStat(this.blobPath(hash)); if (current && sameFingerprint(fingerprint(stat4), fingerprint(current))) found.add(hash); } onChecked?.(); }); return found; } async ensure(hash, supplier) { hash = sha256(hash); const task = this.download(hash, void 0, async (write) => { const bytes2 = await supplier(); await write(bytes2); return bytes2; }, "bytes"); const result = await joinTask(task); const bytes = result ?? await this.readVerified(hash); if (bytes === null) throw new Error("The completed blob disappeared before it could be read"); return bytes; } async ensureStored(hash, size, supplier, signal) { expectedLength(size); hash = sha256(hash); abortCheck(signal); const task = this.download(hash, size, supplier, "stored"); await joinTask(task, signal); if (size !== void 0) { const stat4 = await maybeStat(this.blobPath(hash)); if (!stat4 || stat4.size !== BigInt(size)) throw Object.assign(sizeMismatch(size, Number(stat4?.size ?? 0n)), { blobMissing: !stat4, afterWrite: true }); } } /** * Like ensureStored, for a large blob whose transfer can resume (owner 2026-11-04, ticket "Latence pendant le DL": * the 692 MB FMOD music bank restarted from zero after every cut connection or relaunch, so a shaky line never * finished it). The bytes go to `.part`, kept when the transfer stops; the next try hashes what is there and * calls `supplier(write, signal, { offset, restart })` for the rest: the supplier asks for bytes from `offset`, and * awaits `restart()` before writing when the server sent the whole file instead. A part that overflows the size or * ends with the wrong digest is deleted. Resolves with the bytes taken from the part. */ async ensureStoredResumable(hash, size, supplier, signal) { if (!Number.isSafeInteger(size) || size < 1) throw new TypeError("A resumable blob needs its size"); hash = sha256(hash); abortCheck(signal); const task = this.download(hash, size, supplier, "stored", true); const result = await joinTask(task, signal); const stat4 = await maybeStat(this.blobPath(hash)); if (!stat4 || stat4.size !== BigInt(size)) throw Object.assign(sizeMismatch(size, Number(stat4?.size ?? 0n)), { blobMissing: !stat4, afterWrite: true }); return { resumedBytes: result?.resumedBytes ?? 0 }; } async #storeResumable(hash, size, supplier, signal, lock, file2) { const partial = `${file2}.part`; await fs4.mkdir(import_node_path9.default.dirname(file2), { recursive: true }); const stat4 = await maybeStat(partial); if (stat4 && !stat4.isFile()) throw new Error("Blob partial download path is not a file"); let count2 = Number(stat4?.size ?? 0n); if (count2 > size) { await removeFile(partial); count2 = 0; } const resumedBytes = count2; const writer = await fs4.open(partial, count2 ? "r+" : "w+"); let closed = false; let discard = false; try { let hasher = (0, import_node_crypto8.createHash)("sha256"); for (let position = 0; position < count2; position += 131072) hasher.update(await readRange(writer, position, Math.min(131072, count2 - position), signal)); let writes = Promise.resolve(); const write = (chunk) => { const bytes = Buffer.from(chunk); writes = writes.then(async () => { abortCheck(signal); const next = count2 + bytes.length; if (next > size) { discard = true; throw sizeMismatch(size, next); } await writeAll(writer, bytes, count2); hasher.update(bytes); count2 = next; if (lock.heartbeatError) throw lock.heartbeatError; }); writes.catch(() => { }); return writes; }; const restart = async () => { await writes; await writer.truncate(0); count2 = 0; hasher = (0, import_node_crypto8.createHash)("sha256"); }; if (count2 < size) { try { await supplier(write, signal, { offset: resumedBytes, restart }); } finally { await writes.catch(() => { }); } await writes; } abortCheck(signal); if (count2 !== size) throw sizeMismatch(size, count2); const actual = hasher.digest("hex"); if (actual !== hash) { discard = true; throw hashMismatch(hash, actual); } if (lock.heartbeatError) throw lock.heartbeatError; await writer.sync(); await writer.close(); closed = true; await retryFile(() => fs4.rename(partial, file2)); let written; try { written = await fs4.stat(file2, { bigint: true }); } catch (error) { if (error.code === "ENOENT") throw Object.assign(sizeMismatch(count2, 0), { blobMissing: true, afterWrite: true }); throw error; } await this.disk.remember(hash, written); return { resumedBytes }; } finally { if (!closed) await writer.close().catch(() => { }); if (discard) await removeFile(partial); } } download(hash, size, supplier, mode, resumable = false) { if (this.clearing) throw new Error("Blob store is being cleared"); const active = this.pending.get(hash); if (active && !active.controller.signal.aborted) { if (active.mode === "stored" && active.size !== size && mode === "stored") throw namedError("AssetBlobInflightSizeConflictError", "Concurrent blob downloads disagree on size", { hash, activeExpectedSize: active.size, requestedExpectedSize: size }); return active; } const task = startTask(this.pending, hash, async (signal) => { const lock = await this.disk.lock(hash, signal); const file2 = this.blobPath(hash); let temporary; let writer; try { let existing; try { existing = await fs4.open(file2, "r"); } catch (error) { if (error.code !== "ENOENT") throw error; } if (existing) { try { if (await this.disk.verify(existing, hash, size, signal, this.onHash)) return mode === "bytes" ? await existing.readFile() : void 0; } finally { await existing.close(); } } if (resumable) return await this.#storeResumable(hash, size, supplier, signal, lock, file2); temporary = `${file2}.khaos-${(0, import_node_crypto8.randomUUID)()}.tmp`; await fs4.mkdir(import_node_path9.default.dirname(file2), { recursive: true }); writer = await fs4.open(temporary, "wx"); const hasher = (0, import_node_crypto8.createHash)("sha256"); let count2 = 0; let writes = Promise.resolve(); const write = (chunk) => { const bytes = Buffer.from(chunk); writes = writes.then(async () => { abortCheck(signal); const next = count2 + bytes.length; if (size !== void 0 && next > size) throw sizeMismatch(size, next); await writeAll(writer, bytes, count2); hasher.update(bytes); count2 = next; abortCheck(signal); }); writes.catch(() => { }); return writes; }; let supplied; try { supplied = await supplier(write, signal); } finally { await writes; } abortCheck(signal); if (size !== void 0 && count2 !== size) throw sizeMismatch(size, count2); const actual = hasher.digest("hex"); if (actual !== hash) throw hashMismatch(hash, actual); if (lock.heartbeatError) throw lock.heartbeatError; await writer.sync(); await writer.close(); writer = null; await retryFile(() => fs4.rename(temporary, file2)); temporary = null; let written; try { written = await fs4.stat(file2, { bigint: true }); } catch (error) { if (error.code === "ENOENT") throw Object.assign(sizeMismatch(count2, 0), { blobMissing: true, afterWrite: true }); throw error; } await this.disk.remember(hash, written); return mode === "bytes" ? supplied : void 0; } finally { await writer?.close().catch(() => { }); if (temporary) await removeFile(temporary); await this.disk.locks.release(lock); } }); Object.assign(task, { size, mode }); return task; } async pruneStale(retained, options = {}) { await this.pruneToBudget(retained, { ...options, maxBytes: Infinity, protectedHashes: /* @__PURE__ */ new Set() }); } async pruneToBudget(retained, options) { return this.disk.prune(retained, options, this.pending, "removedBlobs"); } async clear() { if (this.pending.size || this.validations.size || this.disk.validations.size || this.disk.readers.size) throw new Error("Cannot clear blobs with active transfers, validations or readers"); this.clearing = true; try { await this.disk.clear(); } finally { this.clearing = false; } } }; // src/electron/khaos/packStore.js var fs5 = __toESM(require("node:fs/promises"), 1); var import_node_crypto9 = require("node:crypto"); var failure = (kind, message3, details, cause) => namedError(`AssetPack${kind}Error`, message3, details, cause); var sizeFailure = (expectedSize, actualSize) => failure("SizeMismatch", "Pack length did not match its manifest", { expectedSize, actualSize }); var hashFailure = (kind, expectedHash, actualHash) => failure(kind, "Pack content did not match its SHA-256 address", { expectedHash, actualHash }); function packDescriptor(pack2) { const size = pack2?.size; if (!Number.isSafeInteger(size) || size < 1 || size > 8388608) throw new TypeError("Pack size must be between one byte and 8 MiB"); return { hash: sha256(pack2.hash), size }; } function memberDescriptor(pack2, member) { const { offset, length } = member ?? {}; checkRange(pack2.size, offset, length); if (length === 0) throw new RangeError("Pack members must contain bytes"); return { hash: sha256(member.hash), offset, length }; } function inspectResponse(response, pack2, start, length, partial) { const expected = partial ? 206 : 200; if (response.status !== expected) { const unsuccessful = response.status >= 400 && response.status !== 416; throw failure(unsuccessful ? "Http" : "RangeUnsupported", `Pack request expected HTTP ${expected}; received ${response.status}`, { status: response.status }); } const range = response.headers.get("content-range"); if (partial) { const expectedRange = ["bytes ", start, "-", start + length - 1, "/", pack2.size].join(""); if (range !== expectedRange) throw failure("RangeUnsupported", "Pack Content-Range did not describe the requested bytes"); } else if (range !== null) throw failure("ResponseContract", "A whole pack response included an unexpected range"); const declared = response.headers.get("content-length"); if (declared !== null && (!/^(0|[1-9]\d*)$/.test(declared) || Number(declared) !== length)) throw failure("ResponseContract", "Pack Content-Length disagrees with the request"); if (!response.body) throw failure("ResponseContract", "Pack response did not include a body"); } async function consumeBody2(body, signal, consume) { const reader = body.getReader(); let completed = false; try { for (; ; ) { const part = await raceAbort(reader.read(), signal); if (part.done) { completed = true; break; } await consume(part.value); } } finally { if (!completed) await reader.cancel().catch(() => { }); reader.releaseLock(); } } async function memberDigest(bytes, signal) { if (bytes.length <= 1048576) return digest3(bytes); const hasher = (0, import_node_crypto9.createHash)("sha256"); for (let position = 0; position < bytes.length; position += 1048576) { hasher.update(bytes.subarray(position, position + 1048576)); await new Promise((resolve) => setImmediate(resolve)); abortCheck(signal); } return hasher.digest("hex"); } var PackStore = class { // Khaos (asset-fast-path 2026-11-09): `maxOpenPacks` packs stay open for readInstalledMember (0 = none, every read // opens its pack); one that served nothing for `idlePackMs` is closed. // Measured on the 3.7 corpus (1957 packs): the assets of one map are spread over many packs. Login reads 264 packs, // the first map 250 more, twelve maps 715; with 64 open packs one map change kept closing and opening them. 1024 is // above all of that and well under the open-file limit of the main process (8192: the Windows C runtime, and what // Chromium raises it to on macOS and Linux). Opening a pack costs about ten file operations, so a pack stays open // through a fight (five minutes) rather than being opened again for the next map. constructor({ root, lockPollMs, staleLockMs, lockHeartbeatMs, onPackHashRead, onLockWait, onPackOpen, maxOpenPacks = 1024, idlePackMs = 3e5 }) { if (!Number.isSafeInteger(maxOpenPacks) || maxOpenPacks < 0) throw new TypeError("The open pack limit must be a non-negative integer"); if (!Number.isSafeInteger(idlePackMs) || idlePackMs < 1) throw new TypeError("The idle pack time must be a positive integer"); this.disk = new ContentDisk(root, ".pack", { pollMs: lockPollMs, staleMs: staleLockMs, heartbeatMs: lockHeartbeatMs, onLongWait: onLockWait }); this.onHash = onPackHashRead; this.pending = /* @__PURE__ */ new Map(); this.validation = /* @__PURE__ */ new Map(); this.clearing = null; this.maxOpenPacks = maxOpenPacks; this.idlePackMs = idlePackMs; this.onPackOpen = onPackOpen; this.pool = /* @__PURE__ */ new Map(); this.opening = /* @__PURE__ */ new Map(); this.closing = /* @__PURE__ */ new Set(); this.poolTimer = null; this.poolClosed = false; } get inflightCount() { return this.pending.size + this.validation.size + this.opening.size; } get openPackCount() { return this.pool.size; } get openHandleCount() { return [...this.disk.readers.values()].reduce((total, lease) => total + lease.refs, 0); } packPath(hash) { return this.disk.file(hash); } assertAvailable() { if (this.clearing) throw new Error("Pack store is being cleared"); } async hasPack(descriptor, signal) { this.assertAvailable(); const pack2 = packDescriptor(descriptor); abortCheck(signal); const key = `${pack2.hash}:${pack2.size}`; const task = this.validation.get(key) ?? startTask(this.validation, key, async (signal2) => { const release = await this.disk.lease(pack2.hash, signal2); try { return await this.verifyPath(pack2, signal2); } finally { await release(); } }); return joinTask(task, signal); } async verifyPath(pack2, signal) { let handle; try { handle = await fs5.open(this.packPath(pack2.hash), "r"); } catch (error) { if (error.code === "ENOENT") return false; throw error; } try { return await this.disk.verify(handle, pack2.hash, pack2.size, signal, this.onHash); } finally { await handle.close(); } } // `resume: false` (a host that serves no byte range, F11 #121 2026-11-17): a part left by a cut transfer is dropped and // the pack is asked for whole, instead of a resume the host would answer wrongly. ensurePack(descriptor, fetcher, { signal, resume = true } = {}) { this.assertAvailable(); const pack2 = packDescriptor(descriptor); abortCheck(signal); let task = this.pending.get(pack2.hash); if (task && task.size !== pack2.size) throw new Error("Concurrent pack requests disagree on pack size"); if (!task) { task = startTask(this.pending, pack2.hash, async (signal2) => { if (await this.hasPack(pack2, signal2)) return { filePath: this.packPath(pack2.hash), source: "local", resumedBytes: 0, downloadedBytes: 0 }; const lock = await this.disk.lock(pack2.hash, signal2); try { if (await this.verifyPath(pack2, signal2)) return { filePath: this.packPath(pack2.hash), source: "local", resumedBytes: 0, downloadedBytes: 0 }; await this.invalidate(pack2.hash); await this.closePooled(pack2.hash); await removeFile(this.packPath(pack2.hash)); try { return await this.download(pack2, fetcher, lock, signal2, resume); } catch (error) { if (error.name === "AssetPackRangeUnsupportedError") await removeFile(`${this.packPath(pack2.hash)}.part`); throw error; } } finally { await this.disk.locks.release(lock); } }); task.size = pack2.size; } return joinTask(task, signal); } async download(pack2, fetcher, lock, signal, resume = true) { const file2 = this.packPath(pack2.hash); const partial = `${file2}.part`; const stat4 = await maybeStat(partial); if (stat4 && !stat4.isFile()) throw new Error("Pack partial download path is not a file"); let resumedBytes = Number(stat4?.size ?? 0n); if (resumedBytes > pack2.size || !resume && resumedBytes > 0 && resumedBytes < pack2.size) { await removeFile(partial); resumedBytes = 0; } const writer = await fs5.open(partial, resumedBytes ? "r+" : "w+"); let closed = false; try { if (resumedBytes === pack2.size) { const actual = await hashRange(writer, 0, pack2.size, signal); if (actual !== pack2.hash) { await writer.close(); closed = true; await removeFile(partial); throw hashFailure("HashMismatch", pack2.hash, actual); } } else { const hasher = (0, import_node_crypto9.createHash)("sha256"); for (let position = 0; position < resumedBytes; position += 131072) hasher.update(await readRange(writer, position, Math.min(131072, resumedBytes - position), signal)); const request = { pack: pack2, rangeStart: resumedBytes, rangeEnd: pack2.size - 1, rangeHeader: resumedBytes ? `bytes=${resumedBytes}-` : null, signal }; const response = await raceAbort(fetcher(request), signal); try { inspectResponse(response, pack2, resumedBytes, pack2.size - resumedBytes, resumedBytes > 0); } catch (error) { await response.body?.cancel().catch(() => { }); throw error; } let count2 = resumedBytes; await consumeBody2(response.body, signal, async (chunk) => { abortCheck(signal); if (count2 + chunk.length > pack2.size) { await writer.truncate(resumedBytes); throw sizeFailure(pack2.size, count2 + chunk.length); } await writeAll(writer, chunk, count2); hasher.update(chunk); count2 += chunk.length; if (lock.heartbeatError) throw lock.heartbeatError; }); if (count2 !== pack2.size) throw sizeFailure(pack2.size, count2); const actual = hasher.digest("hex"); if (actual !== pack2.hash) { await writer.close(); closed = true; await removeFile(partial); throw hashFailure("HashMismatch", pack2.hash, actual); } } abortCheck(signal); await writer.sync(); await writer.close(); closed = true; await retryFile(() => fs5.rename(partial, file2)); await this.disk.remember(pack2.hash, await fs5.stat(file2, { bigint: true })); return { filePath: file2, source: "downloaded", resumedBytes, downloadedBytes: pack2.size - resumedBytes }; } finally { if (!closed) await writer.close().catch(() => { }); } } abortAll(message3 = "Pack transfers stopped") { for (const task of [...this.pending.values(), ...this.validation.values(), ...this.opening.values()]) task.controller.abort(failure("Aborted", message3)); } async drain() { while (this.inflightCount) await Promise.allSettled([...this.pending.values(), ...this.validation.values(), ...this.opening.values()].map((task) => task.promise)); } async abortAndDrain(message3) { this.abortAll(message3); await this.drain(); } async invalidate(hash) { this.disk.verified.delete(hash); await removeFile(this.disk.receipt(hash)); } async discardCorruptPack(descriptor) { this.assertAvailable(); const pack2 = packDescriptor(descriptor); await this.invalidate(pack2.hash); await this.closePooled(pack2.hash); if (this.pending.has(pack2.hash)) return false; return this.disk.removeIdle({ hash: pack2.hash, file: this.packPath(pack2.hash) }); } async openMember(descriptor, segment, signal) { this.assertAvailable(); const pack2 = packDescriptor(descriptor); const member = memberDescriptor(pack2, segment); abortCheck(signal); const release = await this.disk.lease(pack2.hash, signal); let handle; try { handle = await fs5.open(this.packPath(pack2.hash), "r"); const size = Number((await handle.stat({ bigint: true })).size); if (size !== pack2.size) throw sizeFailure(pack2.size, size); const actual = await hashRange(handle, member.offset, member.length, signal); if (actual !== member.hash) throw hashFailure("MemberHashMismatch", member.hash, actual); this.disk.access.set(pack2.hash, Date.now()); } catch (error) { await handle?.close().catch(() => { }); await release(); if (["AssetPackSizeMismatchError", "AssetPackMemberHashMismatchError"].includes(error.name) || error.message === "Content file ended before the requested range") { await this.invalidate(pack2.hash); throw failure("LocalCorruption", "The installed asset pack is corrupt", { packHash: pack2.hash, corruptionCause: error }, error); } throw error; } return new ContentReader(handle, release, member.offset, member.length, { length: member.length }); } async readMember(pack2, member, signal) { const reader = await this.openMember(pack2, member, signal); try { return await reader.read(0, reader.length, signal); } finally { await reader.close(); } } // Khaos (asset-fast-path 2026-11-09): the read behind every packed asset the game asks for. The pack is opened and // verified once (the lease, open and receipt check of hasPack), then stays open with its lease: a read is one // positional read and a SHA-256 of the very bytes it returns, so a member is still checked on every read. The same // answer through hasPack + readMember took three lock-and-lease cycles, three opens and read the member twice: // 9 ms per asset on the main process, which a map change pays a few hundred times. // Returns null when the pack is not installed; a member that fails its hash is reported as readMember reports it. async readInstalledMember(descriptor, segment, signal) { this.assertAvailable(); const pack2 = packDescriptor(descriptor); const member = memberDescriptor(pack2, segment); abortCheck(signal); if (!this.maxOpenPacks || this.poolClosed) return await this.hasPack(pack2, signal) ? this.readMember(pack2, member, signal) : null; const entry = await this.borrowPack(pack2, signal); if (!entry) return null; let corruption; try { const bytes = await readRange(entry.handle, member.offset, member.length, signal); const actual = await memberDigest(bytes, signal); if (actual === member.hash) { this.disk.access.set(pack2.hash, Date.now()); return bytes; } corruption = hashFailure("MemberHashMismatch", member.hash, actual); } catch (error) { if (error.message !== "Content file ended before the requested range") throw error; corruption = error; } finally { this.returnPack(entry); } await this.closePooled(pack2.hash); await this.invalidate(pack2.hash); throw failure("LocalCorruption", "The installed asset pack is corrupt", { packHash: pack2.hash, corruptionCause: corruption }, corruption); } async borrowPack(pack2, signal) { for (; ; ) { this.assertAvailable(); const entry = this.pool.get(pack2.hash); if (entry) { if (entry.size !== pack2.size) return null; entry.refs += 1; entry.lastUsed = Date.now(); return entry; } const key = `${pack2.hash}:${pack2.size}`; const task = this.opening.get(key) ?? startTask(this.opening, key, (taskSignal) => this.openPooled(pack2, taskSignal)); if (!await joinTask(task, signal)) return null; } } returnPack(entry) { entry.refs -= 1; entry.lastUsed = Date.now(); if (!entry.refs && entry.evicted) entry.finish(); } async openPooled(pack2, signal) { const file2 = this.packPath(pack2.hash); if (!this.pending.has(pack2.hash) && !await maybeStat(file2) && !await maybeStat(`${file2}.lock`)) return false; const release = await this.disk.lease(pack2.hash, signal); let handle = null; let kept = false; try { try { handle = await fs5.open(file2, "r"); } catch (error) { if (error.code === "ENOENT") return false; throw error; } if (!await this.disk.verify(handle, pack2.hash, pack2.size, signal, this.onHash)) return false; abortCheck(signal); if (this.poolClosed) throw failure("Aborted", "Pack store closed"); if (this.pool.has(pack2.hash)) return true; const entry = { hash: pack2.hash, size: pack2.size, handle, refs: 0, lastUsed: Date.now(), evicted: false }; entry.closed = new Promise((resolve) => { entry.finish = () => resolve(entry.handle.close().catch(() => { }).then(release).catch(() => { })); }); this.pool.set(pack2.hash, entry); kept = true; this.trimPool(entry); this.watchPool(); this.onPackOpen?.({ packHash: pack2.hash, openPacks: this.pool.size }); return true; } finally { if (!kept) { await handle?.close().catch(() => { }); await release(); } } } // Closes a pooled pack once its reads in flight are done; resolves when its handle and lease are gone. closePooled(hash) { const entry = this.pool.get(hash); if (!entry) return Promise.resolve(); this.pool.delete(hash); entry.evicted = true; this.closing.add(entry.closed); entry.closed.then(() => this.closing.delete(entry.closed)); if (!entry.refs) entry.finish(); return entry.closed; } trimPool(newest) { const excess = this.pool.size - this.maxOpenPacks; if (excess <= 0) return; const idle = [...this.pool.values()].filter((entry) => !entry.refs && entry !== newest).sort((left, right) => left.lastUsed - right.lastUsed); for (const entry of idle.slice(0, excess)) this.closePooled(entry.hash); } watchPool() { if (this.poolTimer) return; this.poolTimer = setInterval(() => { const cutoff = Date.now() - this.idlePackMs; for (const entry of [...this.pool.values()]) if (!entry.refs && entry.lastUsed <= cutoff) this.closePooled(entry.hash); if (!this.pool.size) { clearInterval(this.poolTimer); this.poolTimer = null; } }, Math.ceil(this.idlePackMs / 2)); this.poolTimer.unref(); } async closePool() { clearInterval(this.poolTimer); this.poolTimer = null; for (const hash of [...this.pool.keys()]) this.closePooled(hash); await Promise.all([...this.closing]); } // The client is quitting: the pooled packs give their leases back, and a late read opens its pack for itself. async close() { this.poolClosed = true; for (const task of this.opening.values()) task.controller.abort(failure("Aborted", "Pack store closed")); await Promise.allSettled([...this.opening.values()].map((task) => task.promise)); await this.closePool(); } async fetchMember(descriptor, segment, fetcher, { signal } = {}) { this.assertAvailable(); const pack2 = packDescriptor(descriptor); const member = memberDescriptor(pack2, segment); abortCheck(signal); const rangeEnd = member.offset + member.length - 1; const response = await raceAbort(fetcher({ pack: pack2, rangeStart: member.offset, rangeEnd, rangeHeader: `bytes=${member.offset}-${rangeEnd}`, signal: signal ?? new AbortController().signal }), signal); try { inspectResponse(response, pack2, member.offset, member.length, true); } catch (error) { await response.body?.cancel().catch(() => { }); throw error; } const bytes = Buffer.allocUnsafe(member.length); let count2 = 0; await consumeBody2(response.body, signal, (chunk) => { if (count2 + chunk.length > member.length) throw sizeFailure(member.length, count2 + chunk.length); bytes.set(chunk, count2); count2 += chunk.length; }); if (count2 !== member.length) throw sizeFailure(member.length, count2); const actual = digest3(bytes); if (actual !== member.hash) throw hashFailure("MemberHashMismatch", member.hash, actual); return bytes; } async usage() { this.assertAvailable(); const totals = { packCount: 0, logicalBytes: 0, allocatedBytes: 0 }; for (const entry of await this.disk.inventory()) { totals.packCount += 1; totals.logicalBytes += entry.size; totals.allocatedBytes += allocatedBytes(entry.size); } return totals; } async pruneToBudget(retained, options) { this.assertAvailable(); return this.disk.prune(retained, options, this.pending, "removedPacks"); } clear() { if (this.clearing) return this.clearing; this.clearing = (async () => { await this.abortAndDrain("Pack cache cleared"); await this.closePool(); await this.disk.clear(); })(); const active = this.clearing; active.finally(() => { if (this.clearing === active) this.clearing = null; }).catch(() => { }); return active; } }; // src/electron/khaos/completionStore.js var import_node_path10 = __toESM(require("node:path"), 1); var fs6 = __toESM(require("node:fs/promises"), 1); var import_node_fs2 = require("node:fs"); var import_node_child_process = require("node:child_process"); var import_node_crypto10 = require("node:crypto"); var formats = { generation: "khaos-asset-cache-generation", receipt: "khaos-required-assets-complete", marker: "khaos-asset-cache-invalidation" }; var localTokens = /* @__PURE__ */ new Set(); var token = () => (0, import_node_crypto10.randomBytes)(32).toString("hex"); var signed = (body) => ({ ...body, signature: digest3(JSON.stringify(body)) }); var validSignature = (record7, body) => record7?.signature === digest3(JSON.stringify(body)); function integer3(value, field) { if (!Number.isSafeInteger(value) || value < 0) throw new TypeError(`Invalid completion ${field}`); return value; } function planDescriptor(input) { if (typeof input?.sourceKey !== "string" || !/^[A-Za-z\d][A-Za-z\d._-]{0,127}$/.test(input.sourceKey)) throw new TypeError("Invalid completion source key"); if (!["desktop-bc7", "desktop-compatibility"].includes(input.profile)) throw new TypeError("Invalid completion profile"); const seen = /* @__PURE__ */ new Set(); if (!Array.isArray(input.categories)) throw new TypeError("Completion categories must be an array"); const categories2 = input.categories.map((entry) => { const category2 = {}; for (const [field, maximum] of [["id", 128], ["label", 256]]) { const value = entry[field]; if (typeof value !== "string" || !value || value !== value.trim() || value.length > maximum) throw new TypeError(`Invalid completion category ${field}`); category2[field] = value; } if (seen.has(category2.id)) throw new TypeError("Duplicate completion category"); seen.add(category2.id); for (const field of ["assetCount", "logicalBytes"]) category2[field] = integer3(entry[field], field); return category2; }); return { sourceKey: input.sourceKey, profile: input.profile, planHash: sha256(input.planHash), categories: categories2, uniqueAssetCount: integer3(input.uniqueAssetCount, "asset count"), uniqueLogicalBytes: integer3(input.uniqueLogicalBytes, "logical bytes") }; } function generationBody(generation) { return { format: formats.generation, schemaVersion: 1, generation }; } function receiptBody(plan, generation) { const body = { format: formats.receipt, schemaVersion: 1, generation }; for (const field of ["sourceKey", "profile"]) body[field] = plan[field]; body.role = "required"; for (const field of ["planHash", "categories", "uniqueAssetCount", "uniqueLogicalBytes"]) body[field] = plan[field]; return body; } function processIdentity(pid) { try { if (process.platform === "linux") { const raw = (0, import_node_fs2.readFileSync)(`/proc/${pid}/stat`, "utf8"); const fields3 = raw.substring(raw.lastIndexOf(")") + 1).trim().split(/\s+/); const start = fields3.at(19); return /^\d+$/.test(start ?? "") ? `linux:${start}` : null; } if (process.platform === "win32") { const expression = `[DateTimeOffset]::new([Diagnostics.Process]::GetProcessById(${pid}).StartTime.ToUniversalTime()).ToUnixTimeMilliseconds()`; const bytes = (0, import_node_child_process.execFileSync)("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", expression], { timeout: 5e3, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }); const milliseconds = bytes.toString().trim(); return /^\d+$/.test(milliseconds) ? `windows:${milliseconds}` : null; } if (process.platform === "darwin") { const birth = (0, import_node_child_process.execFileSync)("ps", ["-p", `${pid}`, "-o", "lstart="], { timeout: 5e3, encoding: "utf8", env: { ...process.env, LC_ALL: "C" }, stdio: ["ignore", "pipe", "ignore"] }).trim(); return birth ? `darwin:${birth.split(/\s+/).join(" ")}` : null; } } catch { return null; } return null; } function markerBody(record7) { const body = { format: formats.marker, schemaVersion: 1 }; for (const field of ["pid", "processIdentity", "token", "createdAt"]) body[field] = record7[field]; return body; } function markerAlive(record7) { if (!record7 || record7.format !== formats.marker || record7.schemaVersion !== 1 || !Number.isSafeInteger(record7.pid) || record7.pid < 1 || typeof record7.processIdentity !== "string" || !validSignature(record7, markerBody(record7))) return false; try { sha256(record7.token); integer3(record7.createdAt, "marker creation time"); } catch { return false; } if (record7.pid === process.pid && localTokens.has(record7.token)) return true; const actual = processIdentity(record7.pid); return actual === null ? processAlive(record7.pid) : actual === record7.processIdentity; } var CompletionStore = class { constructor(root) { if (typeof root !== "string" || !root.trim()) throw new TypeError("Completion cache root is required"); this.root = import_node_path10.default.resolve(root); this.generationFile = import_node_path10.default.join(this.root, "asset-cache-generation.json"); this.markerRoot = import_node_path10.default.join(this.root, "asset-cache-invalidations"); this.lock = new DiskLock(); this.ownedMarker = null; this.transition = false; this.finishPending = false; } async transaction(operation, signal) { const lock = await this.lock.acquire(import_node_path10.default.join(this.root, ".asset-completion.lock"), signal); try { abortCheck(signal); return await operation(); } finally { await this.lock.release(lock); } } receiptPath(plan) { return import_node_path10.default.join(this.root, "sources", plan.sourceKey, "install-receipts", plan.profile, `${plan.planHash}.json`); } markerPath(value) { return import_node_path10.default.join(this.markerRoot, `${sha256(value)}.json`); } async generation(signal) { const record7 = await readJson(this.generationFile, 4096, signal); if (!record7 || record7.format !== formats.generation || record7.schemaVersion !== 1) return null; try { sha256(record7.generation); } catch { return null; } return validSignature(record7, generationBody(record7.generation)) ? record7.generation : null; } async rotate() { const generation = token(); await atomicWrite(this.generationFile, JSON.stringify(signed(generationBody(generation))), this.root); return generation; } async markers() { try { return (await fs6.readdir(this.markerRoot, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => import_node_path10.default.join(this.markerRoot, entry.name)); } catch (error) { if (error.code === "ENOENT") return []; throw error; } } async recover(signal) { for (const file2 of await this.markers()) { abortCheck(signal); if (markerAlive(await readJson(file2, 4096, signal))) continue; await this.rotate(); await removeFile(file2); } } async recoverInterruptedInvalidation() { await this.transaction(async () => { await this.recover(); if (!await this.generation()) await this.rotate(); }); } async checkRequiredCompletion(input, signal) { const plan = planDescriptor(input); return this.transaction(async () => { await this.recover(signal); if ((await this.markers()).length) return { complete: false, generation: null }; const generation = await this.generation(signal) ?? await this.rotate(); const expected = receiptBody(plan, generation); const record7 = await readJson(this.receiptPath(plan), 65536, signal); const complete = record7 !== null && JSON.stringify(record7) === JSON.stringify(signed(expected)); return { complete, generation }; }, signal); } async recordRequiredCompletion(input, expectedGeneration, signal) { const plan = planDescriptor(input); sha256(expectedGeneration); return this.transaction(async () => { await this.recover(signal); if ((await this.markers()).length || await this.generation(signal) !== expectedGeneration) return false; await atomicWrite(this.receiptPath(plan), JSON.stringify(signed(receiptBody(plan, expectedGeneration))), this.root); abortCheck(signal); return true; }, signal); } async beginInvalidation() { if (this.transition) throw new Error("This store already owns an invalidation"); if (this.ownedMarker && this.finishPending) await this.finishInvalidation(); if (this.ownedMarker) throw new Error("This store already owns an invalidation"); this.transition = true; try { await this.transaction(async () => { const identity = processIdentity(process.pid); if (!identity) throw new Error("Unable to identify the invalidating process"); const record7 = signed(markerBody({ pid: process.pid, processIdentity: identity, token: token(), createdAt: Date.now() })); localTokens.add(record7.token); this.ownedMarker = record7; try { await atomicWrite(this.markerPath(record7.token), JSON.stringify(record7), this.root); await this.rotate(); } catch (error) { try { await removeFile(this.markerPath(record7.token)); localTokens.delete(record7.token); this.ownedMarker = null; } catch (cleanup) { this.finishPending = true; throw new AggregateError([error, cleanup], "Invalidation setup failed and its marker remains owned"); } throw error; } }); } finally { this.transition = false; } } async finishInvalidation() { if (this.transition || !this.ownedMarker) throw new Error("This store does not own an invalidation"); this.transition = true; this.finishPending = true; try { await this.transaction(async () => { const record7 = this.ownedMarker; await removeFile(this.markerPath(record7.token)); localTokens.delete(record7.token); this.ownedMarker = null; this.finishPending = false; }); } finally { this.transition = false; } } }; // src/electron/khaos/downloadPolicy.js var KHAOS_FOREGROUND_CAP = 12; function khaosSlotLimit(profileCap) { return profileCap + KHAOS_FOREGROUND_CAP; } function khaosMayStart(priority, state) { if (priority === "background") { return state.activeBackground < state.cap && !state.liveBusy; } return state.active - state.activeBackground < Math.max(KHAOS_FOREGROUND_CAP, state.cap); } var KHAOS_PRUNE_GROWTH_BYTES = 256 * 1024 * 1024; var KHAOS_PRUNE_MAX_INTERVAL_MS = 60 * 6e4; function khaosShouldPrune(downloadedBytes, now, last) { if (last === null) return true; return downloadedBytes - last.bytes >= KHAOS_PRUNE_GROWTH_BYTES || now - last.at >= KHAOS_PRUNE_MAX_INTERVAL_MS; } var KHAOS_BACKGROUND_IDLE_RECHECK_MS = 30 * 6e4; function khaosBackgroundRecheckMs(state, baseMs) { return state?.phase === "done" && !state.failedFiles && !state.error ? KHAOS_BACKGROUND_IDLE_RECHECK_MS : baseMs; } // src/electron/khaos/downloadCoordinator.js var profiles = /* @__PURE__ */ new Map([["eco", 2], ["balanced", 8], ["max", 16]]); var lanes = ["live", "required", "background"]; var metricNames = "networkBytes verifiedBytes resumedBytes queueWaitMs ttfbMs ttfbSamples hashMs writeMs retries".split(" "); var counters = () => Object.fromEntries(metricNames.map((name) => [name, 0])); var laneCounts = () => Object.fromEntries(lanes.map((name) => [name, 0])); var stopped = (reason) => reason instanceof Error || reason instanceof DOMException ? reason : new DOMException("Asset transfer stopped", "AbortError"); var finite2 = (number, label) => { if (typeof number === "number" && Number.isFinite(number) && number >= 0) return number; throw new TypeError(`${label} must be a finite non-negative number`); }; var integer4 = (number, label, minimum = 0) => { finite2(number, label); if (Number.isSafeInteger(number) && number >= minimum) return number; throw new TypeError(`${label} must be a safe integer of at least ${minimum}`); }; var attemptsLimit = (value) => value === null ? null : integer4(value, "Attempt limit", 1); var INDIVIDUAL_MODE_MS = 5 * 6e4; var profileLimit = (value) => { if (profiles.has(value)) return profiles.get(value); throw new TypeError(`Unknown asset speed profile: ${value}`); }; var AssetDownloadRetryableError = class extends Error { constructor(message3, details = {}) { super(message3); Object.assign(this, { name: "AssetDownloadRetryableError", congestion: details.congestion === true, retryAfterMs: details.retryAfterMs ?? null }); } }; function classifyDownloadError(error) { const retryable = error instanceof AssetDownloadRetryableError; return { retry: retryable, congestion: retryable && error.congestion, retryAfterMs: retryable ? error.retryAfterMs : null }; } function pause2(milliseconds, signal) { return new Promise((resolve, reject) => { let timer; const release = () => signal.removeEventListener("abort", cancelled2); const cancelled2 = () => { clearTimeout(timer); release(); reject(stopped(signal.reason)); }; if (signal.aborted) { cancelled2(); return; } timer = setTimeout(() => { release(); resolve(); }, Math.min(milliseconds, 2 ** 31 - 1)); signal.addEventListener("abort", cancelled2, { once: true }); }); } function carrierContract(carrier2) { if (!carrier2 || typeof carrier2.carrierHash !== "string" || !/^[a-f0-9]{64}$/u.test(carrier2.carrierHash)) throw new TypeError("Asset carrier needs a lowercase SHA-256"); integer4(carrier2.byteLength, "Carrier byte length"); if (typeof carrier2.execute !== "function") throw new TypeError("Asset carrier needs an execute function"); } function leader(job) { let choice2; for (const request of job.requests) { const rank = lanes.indexOf(request.priority); const current = choice2 ? lanes.indexOf(choice2.priority) : Infinity; if (rank < current || rank === current && request.sequence < choice2.sequence) choice2 = request; } return choice2; } function notify(callback, value) { try { callback?.(value); } catch { } } var DownloadCoordinator = class { #options; #jobs = /* @__PURE__ */ new Map(); #running = /* @__PURE__ */ new Map(); #observers = /* @__PURE__ */ new Set(); #drains = /* @__PURE__ */ new Set(); #modes = /* @__PURE__ */ new Map(); #individualSince = /* @__PURE__ */ new Map(); #lastSources = /* @__PURE__ */ new Map(); #totals = Object.assign(counters(), Object.fromEntries(["completed", "failed", "aborted", "congestionEvents"].map((name) => [name, 0]))); #profile; #maximum; #capacity; #backgroundBudget; #sequence = 0; #ticket = 0; #recoveries = 0; #scheduled = false; #closed = false; constructor(options = {}) { this.#profile = options.speedProfile ?? "balanced"; this.#maximum = profileLimit(this.#profile); this.#capacity = this.#maximum; const budget = integer4(options.inflightBudgetBytes ?? 128 * 1024 * 1024, "Inflight budget", 1); const firstDelay = finite2(options.retryBaseDelayMs ?? 250, "First retry delay"); const lastDelay = finite2(options.retryMaxDelayMs ?? 1e4, "Maximum retry delay"); if (lastDelay < firstDelay) throw new RangeError("Maximum retry delay is below the first retry delay"); this.#backgroundBudget = budget - Math.min(8 * 1024 * 1024, Math.floor(budget / 2)); this.#options = { budget, attempts: attemptsLimit(options.defaultMaxAttempts === void 0 ? 3 : options.defaultMaxAttempts), individualModeMs: finite2(options.individualModeMs ?? INDIVIDUAL_MODE_MS, "Individual mode duration"), now: options.now ?? Date.now, classify: options.classifyError ?? classifyDownloadError, backoff: options.backoff ?? ((attempt) => Math.min(lastDelay, firstDelay * 2 ** Math.min(attempt - 1, 20))), jitter: options.jitter ?? ((delay3) => delay3 * (0.5 + Math.random() / 2)), sleep: options.sleep ?? pause2, onNetworkBytes: options.onNetworkBytes, onCompletedTrace: options.onCompletedTrace }; for (const name of ["now", "classify", "backoff", "jitter", "sleep"]) { if (typeof this.#options[name] !== "function") throw new TypeError(`Coordinator ${name} must be a function`); } } enqueue(specification) { if (this.#closed) return Promise.reject(stopped()); carrierContract(specification); if (typeof specification.sourceKey !== "string" || !specification.sourceKey.length) throw new TypeError("Asset source key is required"); if (!lanes.includes(specification.priority)) throw new TypeError("Unknown asset priority"); const transport = specification.transport ?? { kind: "individual" }; if (!["individual", "pack-member"].includes(transport.kind)) throw new TypeError("Unknown asset transport kind"); if (transport.kind === "pack-member") carrierContract(transport.individual); const limit = attemptsLimit(specification.maxAttempts === void 0 ? this.#options.attempts : specification.maxAttempts); if (specification.signal?.aborted) return Promise.reject(stopped(specification.signal.reason)); let accept, decline; const result = new Promise((resolve, reject) => { accept = resolve; decline = reject; }); const request = { sequence: this.#sequence++, sourceKey: specification.sourceKey, priority: specification.priority, execute: specification.execute, kind: transport.kind, fallback: transport.individual, fullPackResponseAllowed: transport.fullPackResponseAllowed === true, limit, classify: specification.classifyError ?? this.#options.classify, signal: specification.signal, accept, decline, job: null, attempts: 0, done: false }; if (typeof request.classify !== "function") { decline(new TypeError("Request classifier must be a function")); return result; } if (request.kind === "pack-member" && this.getTransportMode(request.sourceKey) === "individual") { this.#useFallback(request); } request.cancel = () => this.#cancel(request, stopped(request.signal.reason)); this.#attach(request, request.kind === "individual" && transport.kind === "pack-member" ? transport.individual : specification); if (!request.done) { request.signal?.addEventListener("abort", request.cancel, { once: true }); if (request.signal?.aborted) request.cancel(); } this.#changed(); return result; } /** "unknown", "pack" or "individual"; an "individual" mode older than `individualModeMs` is "unknown" again. */ getTransportMode(sourceKey2) { const mode = this.#modes.get(sourceKey2) ?? "unknown"; if (mode === "individual" && this.#options.now() - this.#individualSince.get(sourceKey2) >= this.#options.individualModeMs) { this.#modes.delete(sourceKey2); this.#individualSince.delete(sourceKey2); return "unknown"; } return mode; } /** * "pack" once a byte range worked, "individual" when one was answered wrongly (packed files then come with their * whole pack, assetCache.js #wholePack). Only "pack" -> "unknown" is refused: "individual" is left for "pack" (a * range answered right) or "unknown" (to ask again), as it also is by itself after `individualModeMs`. */ setTransportMode(sourceKey2, mode) { if (typeof sourceKey2 !== "string" || !sourceKey2) throw new TypeError("Asset source key is required"); if (!["unknown", "pack", "individual"].includes(mode)) throw new TypeError("Unknown asset transport mode"); const previous = this.getTransportMode(sourceKey2); if (mode === previous) return; if (previous === "pack" && mode === "unknown") throw new Error(`Asset transport cannot move from ${previous} to ${mode}`); if (mode === "unknown") this.#modes.delete(sourceKey2); else this.#modes.set(sourceKey2, mode); if (mode === "individual") { this.#individualSince.set(sourceKey2, this.#options.now()); for (const job of [...this.#jobs.values()]) if (!this.#running.has(job)) this.#moveFallbacks(job, sourceKey2); } else this.#individualSince.delete(sourceKey2); this.#changed(); } setSpeedProfile(profile) { const maximum = profileLimit(profile); if (profile === this.#profile) return; this.#profile = profile; this.#maximum = this.#capacity = maximum; this.#recoveries = 0; this.#changed(); } getMetrics() { const queuedByPriority = laneCounts(); const activeByPriority = laneCounts(); let queued = 0, delayed = 0, inflightBytes = 0; for (const [job, lease] of this.#running) { activeByPriority[lease.priority]++; inflightBytes += lease.bytes; } for (const job of this.#jobs.values()) { if (this.#running.has(job)) continue; if (job.phase === "delayed") delayed++; else { queued++; queuedByPriority[leader(job).priority]++; } } return { ...this.#totals, speedProfile: this.#profile, active: this.#running.size, cap: this.#capacity, profileCap: this.#maximum, queued, delayed, inflightBytes, inflightBudgetBytes: this.#options.budget, queuedByPriority, activeByPriority }; } onMetricsChanged(callback) { if (typeof callback !== "function") throw new TypeError("Metrics observer must be a function"); this.#observers.add(callback); notify(callback, this.getMetrics()); return () => this.#observers.delete(callback); } abortSource(sourceKey2, reason) { this.#abortWhere((request) => request.sourceKey === sourceKey2, reason); } abortAll(reason) { this.#abortWhere(() => true, reason); } close(reason) { this.#closed = true; this.abortAll(reason); return this.drain(); } drain() { return this.#jobs.size ? new Promise((resolve) => this.#drains.add(resolve)) : Promise.resolve(); } #attach(request, carrier2) { const existing = this.#jobs.get(carrier2.carrierHash); if (existing && (existing.size !== carrier2.byteLength || existing.kind !== request.kind || existing.controller.signal.aborted)) { this.#settle(request, new Error("Conflicting or cancelled asset carrier")); return; } const job = existing ?? { hash: carrier2.carrierHash, size: carrier2.byteLength, kind: request.kind, sequence: request.sequence, requests: /* @__PURE__ */ new Set(), controller: new AbortController(), stats: Object.assign(counters(), { attempts: 0, initialQueueWaitMs: 0 }), phase: "queued", readyAt: this.#options.now(), createdAt: this.#options.now() }; request.job = job; job.requests.add(request); this.#jobs.set(job.hash, job); } #settle(request, error, completion) { if (request.done) return; request.done = true; request.signal?.removeEventListener("abort", request.cancel); request.job?.requests.delete(request); request.job = null; if (completion === void 0) request.decline(error); else request.accept(completion); } #cancel(request, reason) { const job = request.job; this.#settle(request, reason); if (job && !job.requests.size) { job.controller.abort(reason); if (!this.#running.has(job)) this.#finish(job, "aborted", reason); } this.#changed(); } #abortWhere(predicate, reason) { const error = stopped(reason); for (const job of [...this.#jobs.values()]) for (const request of [...job.requests]) if (predicate(request)) this.#cancel(request, error); } #changed() { if (this.#observers.size) { const metrics = this.getMetrics(); for (const observer of [...this.#observers]) notify(observer, metrics); } if (this.#scheduled) return; this.#scheduled = true; queueMicrotask(() => { this.#scheduled = false; this.#pump(); if (!this.#jobs.size) { for (const resolve of this.#drains) resolve(); this.#drains.clear(); } }); } #pump() { while (this.#running.size < khaosSlotLimit(this.#capacity)) { const selected = this.#select(); if (!selected) break; void this.#run(selected.job, selected.request, selected.bytes); } } #select() { let activeBytes = 0, backgroundBytes = 0, backgroundCount = 0, liveBusy = false; for (const lease of this.#running.values()) { activeBytes += lease.bytes; if (lease.priority === "background") { backgroundBytes += lease.bytes; backgroundCount++; } if (lease.priority === "live") liveBusy = true; } const waiting = []; for (const job of this.#jobs.values()) { const request = leader(job); if (request?.priority === "live") liveBusy = true; if (job.phase === "queued" && request) waiting.push({ job, request }); } waiting.sort((left, right) => left.job.sequence - right.job.sequence); const state = { active: this.#running.size, activeBackground: backgroundCount, cap: this.#capacity, liveBusy }; for (let step = 0; step < 13; step++) { const slot = (this.#ticket + step) % 13; const priority = slot < 8 ? "live" : slot < 12 ? "required" : "background"; if (!khaosMayStart(priority, state)) continue; const available = waiting.filter(({ job, request }) => { if (request.priority !== priority) return false; const reservation = Math.min(job.size, priority === "background" ? this.#backgroundBudget : this.#options.budget); return reservation + activeBytes <= this.#options.budget && (priority !== "background" || reservation + backgroundBytes <= this.#backgroundBudget); }); const sources = [...new Set(available.map(({ request }) => request.sourceKey))]; if (!sources.length) continue; const after = sources.indexOf(this.#lastSources.get(priority)); const source = sources[(after + 1) % sources.length]; const chosen = available.find(({ request }) => request.sourceKey === source); this.#ticket = (slot + 1) % 13; this.#lastSources.set(priority, source); return { ...chosen, bytes: Math.min(chosen.job.size, priority === "background" ? this.#backgroundBudget : this.#options.budget) }; } return null; } #context(job, request, valid2, startedAt) { const context = { carrierHash: job.hash, sourceKey: request.sourceKey, priority: request.priority, attempt: job.stats.attempts, signal: job.controller.signal, fullPackResponseAllowed: request.fullPackResponseAllowed }; const record7 = (name, amount, isInteger) => { if (!valid2.current) throw new Error("Transfer metric arrived after its execution lease expired"); const value = isInteger ? integer4(amount, name) : finite2(amount, name); job.stats[name] += value; this.#totals[name] += value; if (name === "networkBytes") notify(this.#options.onNetworkBytes, value); this.#changed(); }; for (const [method, name, integral] of [["reportNetworkBytes", "networkBytes", true], ["reportVerifiedBytes", "verifiedBytes", true], ["reportResumedBytes", "resumedBytes", true], ["recordHashDuration", "hashMs", false], ["recordWriteDuration", "writeMs", false]]) { context[method] = (amount) => record7(name, amount, integral); } let responded = false; context.markResponseStarted = () => { if (responded) throw new Error("Transfer response was already recorded"); record7("ttfbMs", Math.max(0, this.#options.now() - startedAt), false); responded = true; job.stats.ttfbSamples++; this.#totals.ttfbSamples++; this.#changed(); }; return context; } async #run(job, request, bytes) { const start = this.#options.now(); const elapsed = finite2(Math.max(0, start - job.readyAt), "Queue time"); job.stats.queueWaitMs += elapsed; this.#totals.queueWaitMs += elapsed; if (!job.stats.attempts) job.stats.initialQueueWaitMs = elapsed; job.stats.attempts++; for (const waiter of job.requests) waiter.attempts++; job.phase = "active"; this.#running.set(job, { priority: request.priority, sourceKey: request.sourceKey, bytes }); const valid2 = { current: true }; this.#changed(); let error; let failed = false; try { await request.execute(this.#context(job, request, valid2, start)); } catch (failure3) { failed = true; error = failure3; } valid2.current = false; this.#running.delete(job); if (job.controller.signal.aborted || !job.requests.size || error?.name === "AbortError") { this.#finish(job, "aborted", stopped(job.controller.signal.aborted ? job.controller.signal.reason : error)); return; } if (!failed) { if (request.kind === "pack-member" && this.getTransportMode(request.sourceKey) === "unknown") this.setTransportMode(request.sourceKey, "pack"); this.#recoveries++; if (this.#capacity < this.#maximum && this.#recoveries >= Math.max(4, this.#capacity)) { this.#capacity++; this.#recoveries = 0; } notify(this.#options.onCompletedTrace, { k: "job", pri: leader(job).priority, kind: request.kind, bytes: job.size, net: job.stats.networkBytes, wait: Math.round(job.stats.queueWaitMs), ttfb: Math.round(job.stats.ttfbMs), hash: Math.round(job.stats.hashMs), write: Math.round(job.stats.writeMs), ms: Math.round(this.#options.now() - job.createdAt), cap: this.#capacity, profile: this.#profile, active: this.#running.size, jobs: this.#jobs.size }); this.#finish(job, "completed"); return; } if (request.kind === "pack-member" && (error?.name === "AssetPackRangeUnsupportedError" || this.getTransportMode(request.sourceKey) === "individual")) { if (this.getTransportMode(request.sourceKey) !== "individual") this.setTransportMode(request.sourceKey, "individual"); else this.#moveFallbacks(job, request.sourceKey); if (job.requests.size) { job.phase = "queued"; job.readyAt = this.#options.now(); } this.#changed(); return; } this.#retry(job, error); } #retry(job, failure3) { let retryAfter = 0, congestion = false; for (const request of [...job.requests]) { try { const disposition = request.classify(failure3, request.attempts); if (typeof disposition?.retry !== "boolean" || typeof disposition.congestion !== "boolean") throw new TypeError("Invalid download error classification"); const delay4 = disposition.retryAfterMs === null ? 0 : finite2(disposition.retryAfterMs, "Retry-After"); congestion ||= disposition.congestion; if (!disposition.retry || request.limit !== null && request.attempts >= request.limit) this.#settle(request, failure3); else retryAfter = Math.max(retryAfter, delay4); } catch (error) { this.#settle(request, error); } } if (congestion) { this.#capacity = Math.max(2, Math.floor(this.#capacity / 2)); this.#recoveries = 0; this.#totals.congestionEvents++; } if (!job.requests.size) { this.#finish(job, "failed", failure3); return; } let delay3; try { const backoff = finite2(this.#options.backoff(job.stats.attempts, job.hash), "Retry backoff"); delay3 = Math.max(retryAfter, finite2(this.#options.jitter(backoff, job.stats.attempts, job.hash), "Retry jitter")); } catch (error) { this.#finish(job, "failed", error); return; } job.stats.retries++; this.#totals.retries++; job.phase = "delayed"; this.#changed(); Promise.resolve().then(() => this.#options.sleep(delay3, job.controller.signal)).then(() => { if (this.#jobs.get(job.hash) !== job || job.phase !== "delayed") return; job.phase = "queued"; job.readyAt = this.#options.now(); this.#changed(); }, (error) => { if (this.#jobs.get(job.hash) === job && job.phase === "delayed") this.#finish(job, "aborted", stopped(error)); }); } #useFallback(request) { request.kind = "individual"; request.execute = request.fallback.execute; request.fullPackResponseAllowed = false; } #moveFallbacks(job, sourceKey2) { const requests = [...job.requests].filter((request) => request.kind === "pack-member" && request.sourceKey === sourceKey2); for (const request of requests) { job.requests.delete(request); request.job = null; this.#useFallback(request); this.#attach(request, request.fallback); } if (!job.requests.size && !this.#running.has(job)) { job.controller.abort(stopped()); this.#jobs.delete(job.hash); } } #finish(job, outcome, error) { if (this.#jobs.get(job.hash) !== job) return; const completion = { carrierHash: job.hash, byteLength: job.size, ...job.stats }; this.#totals[outcome]++; for (const request of [...job.requests]) this.#settle(request, error, completion); this.#jobs.delete(job.hash); this.#changed(); } }; // src/electron/khaos/metadataHost.js var import_node_worker_threads = require("node:worker_threads"); var import_promises8 = require("node:fs/promises"); var record5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var count = (value) => Number.isSafeInteger(value) && value >= 0; var failure2 = (message3) => Object.assign(new Error(message3), { name: "AssetMetadataProtocolError" }); var MetadataHost = class { constructor({ filename, createWorker = async () => new import_node_worker_threads.Worker(await (0, import_promises8.readFile)(filename, "utf8"), { eval: true }), idleMs = 2e4, requestMs = 12e4 } = {}) { if (![idleMs, requestMs].every((value) => Number.isSafeInteger(value) && value > 0)) throw new Error("Invalid metadata worker timing"); Object.assign(this, { createWorker, idleMs, requestMs }); this.worker = null; this.starting = null; this.requests = /* @__PURE__ */ new Map(); this.sequence = 0; this.retirement = null; this.closed = false; } parseShard(filePath, label, shardId, integrity) { return this.submit(filePath, label, integrity, { kind: "shard", shardId }); } parseCatalog(filePath, label, integrity) { return this.submit(filePath, label, integrity, { kind: "catalog" }); } parseInstallPlan(filePath, label, profile, integrity) { return this.submit(filePath, label, integrity, { kind: "install-plan", profile }); } // Khaos (prune-pass 2026-11-09): the storage pruner's summary of one stored source (assetMetadata.js // summarizePruneSource). The request names its own files; the summary it carries in (`previous`) is copied to the // worker, the one that comes back is handed over. summarizePrune(request) { return this.post({ request }); } async acquire() { if (this.closed) throw new Error("Metadata host is closed"); if (this.worker) return this.worker; if (!this.starting) { this.starting = Promise.resolve().then(this.createWorker).then((worker) => { if (this.closed) { void worker.terminate(); throw new Error("Metadata host closed during startup"); } this.worker = worker; worker.unref?.(); worker.on("message", (packet) => { if (this.worker === worker) this.receive(packet); }); for (const name of ["error", "messageerror"]) worker.on(name, (error) => this.failed(worker, error)); worker.on("exit", (code) => this.failed(worker, new Error(`Metadata worker exited (${code})`))); return worker; }).finally(() => { this.starting = null; }); } return this.starting; } submit(filePath, label, integrity, request) { return this.post({ filePath, label, integrity: { hash: integrity?.hash, size: integrity?.size }, request }); } async post(command) { const { request } = command; clearTimeout(this.retirement); this.retirement = null; const worker = await this.acquire(); clearTimeout(this.retirement); this.retirement = null; const id = ++this.sequence; if (!Number.isSafeInteger(id)) throw new Error("Metadata request IDs exhausted"); return new Promise((resolve, reject) => { const ticket = { request, resolve, reject, plan: null, counts: null, timer: setTimeout(() => this.failed(worker, new Error("Metadata request timed out")), this.requestMs) }; ticket.timer.unref?.(); this.requests.set(id, ticket); try { worker.postMessage({ id, ...command }); } catch (error) { this.finish(id, error); } }); } finish(id, error, value) { const ticket = this.requests.get(id); if (!ticket) return; clearTimeout(ticket.timer); this.requests.delete(id); if (error) ticket.reject(error); else ticket.resolve(value); if (!this.requests.size && this.worker && !this.retirement) { this.retirement = setTimeout(() => { const worker = this.worker; this.retirement = null; if (!worker || this.requests.size || this.starting) return; this.worker = null; void worker.terminate(); }, this.idleMs); this.retirement.unref?.(); } } receive(packet) { if (!record5(packet) || !Number.isSafeInteger(packet.id) || typeof packet.ok !== "boolean") return this.failed(this.worker, failure2("Invalid metadata reply")); const ticket = this.requests.get(packet.id); if (!ticket) return; try { if (!packet.ok) { if (!record5(packet.error) || typeof packet.error.message !== "string" || typeof packet.error.name !== "string") throw failure2("Invalid metadata error"); const error = Object.assign(new Error(packet.error.message), { name: packet.error.name }); if (typeof packet.error.stack === "string") error.stack = packet.error.stack; if (record5(packet.error.artifact) && typeof packet.error.artifact.kind === "string") error.artifact = { kind: packet.error.artifact.kind, id: typeof packet.error.artifact.id === "string" ? packet.error.artifact.id : null }; this.finish(packet.id, error); return; } const event = packet.event; if (!record5(event)) throw failure2("Missing metadata event"); if (ticket.request.kind !== "install-plan") { if (event.kind !== "result" || !record5(event.result) || event.result.kind !== ticket.request.kind || !count(event.result.itemCount) || !record5(event.result.value)) throw failure2("Unexpected scalar metadata result"); if (ticket.request.kind === "prune-summary" && !isPruneSummary(event.result.value)) throw failure2("Invalid prune summary"); this.finish(packet.id, null, event.result); return; } switch (event.kind) { case "install-plan-header": { const header = event.header; if (ticket.plan || !record5(header) || header.schemaVersion !== 1 || header.format !== "desktop-install-plan" || header.profile !== ticket.request.profile || !Array.isArray(header.categories)) throw failure2("Invalid install header"); for (const field of ["requiredCategories", "backgroundCategories", "optionalCategories"]) if (!Array.isArray(header[field]) || !header[field].every((id) => typeof id === "string")) throw failure2("Invalid install selection"); const entries2 = header.categories.map(({ id, ...category2 }) => { if (typeof id !== "string" || !id || !count(category2.assetCount)) throw failure2("Invalid install category"); return [id, { ...category2, assets: [] }]; }); if (new Set(entries2.map(([id]) => id)).size !== entries2.length) throw failure2("Duplicate install category"); const { categories: categories2, ...values } = header; ticket.plan = { ...values, categories: Object.fromEntries(entries2) }; break; } case "install-plan-assets": { const category2 = ticket.plan?.categories[event.categoryId]; if (!category2 || !Array.isArray(event.assets) || event.offset !== category2.assets.length || event.assets.length > category2.assetCount - category2.assets.length) throw failure2("Out-of-order install chunk"); for (const asset2 of event.assets) category2.assets.push(asset2); break; } case "install-plan-complete": if (!ticket.plan || !count(event.itemCount) || Object.values(ticket.plan.categories).some((category2) => category2.assetCount !== category2.assets.length)) throw failure2("Truncated install plan"); this.finish(packet.id, null, { value: ticket.plan, itemCount: event.itemCount }); break; default: throw failure2("Unexpected streamed metadata event"); } } catch (error) { this.failed(this.worker, error); } } failed(worker, error) { if (!worker || worker !== this.worker) return; this.worker = null; clearTimeout(this.retirement); this.retirement = null; for (const id of Array.from(this.requests.keys())) this.finish(id, error); void worker.terminate(); } async close() { this.closed = true; if (this.starting) await this.starting.catch(() => { }); this.failed(this.worker, new Error("Metadata host stopped")); } }; // src/electron/khaos/assetPredownloader.js var speeds = /* @__PURE__ */ new Set(["eco", "balanced", "max"]); var LATE_CATEGORIES = /* @__PURE__ */ new Set(["audio-music-bank"]); var roles = /* @__PURE__ */ new Set(["required", "background", "complete"]); function planRoleCategoryIds(plan, role) { if (!plan) return []; if (role === "required") return Array.from(plan.requiredCategories ?? []); const all = Array.from(plan.backgroundCategories ?? []); return role === "background" ? all.filter((id) => !LATE_CATEGORIES.has(id)) : all; } var networkCodes = /* @__PURE__ */ new Set(["EAI_AGAIN", "ECONNABORTED", "ECONNREFUSED", "ECONNRESET", "EHOSTUNREACH", "ENETDOWN", "ENETUNREACH", "ETIMEDOUT"]); var message = (error) => error instanceof Error ? error.message : String(error); var aborted = () => new DOMException("Asset installation stopped", "AbortError"); var isAbort = (error) => error?.name === "AbortError"; var stale = (error) => error?.name === "StaleManifestError"; var transportFailure = (error) => error?.name === "AssetPackTransportUnavailableError"; function retryablePlanError(error) { if (networkCodes.has(error?.code)) return true; if (["AssetNetworkError", "StaleManifestError"].includes(error?.name)) return true; return error?.name === "AssetHttpError" && ([408, 425, 429].includes(error.status) || error.status >= 500); } function installationError(error) { switch (error?.failureKind) { case "disk-full": return "Espace disque insuffisant pour installer les ressources du jeu."; case "blocked": case "vanished": return "Un fichier du jeu a \xE9t\xE9 bloqu\xE9 ou modifi\xE9 (antivirus ?)."; case "network": return "Connexion au serveur de t\xE9l\xE9chargement interrompue."; case "mismatch": return "Un fichier du jeu est arriv\xE9 incomplet ou modifi\xE9."; default: break; } switch (error?.code) { case "EDQUOT": case "ENOSPC": return "Espace disque insuffisant pour installer les ressources du jeu."; case "EACCES": case "EPERM": case "EROFS": return "Impossible d'\xE9crire les ressources du jeu. V\xE9rifiez les droits du dossier de cache."; default: break; } if (stale(error)) return "Les ressources du serveur ont chang\xE9 pendant le t\xE9l\xE9chargement."; return retryablePlanError(error) ? "Serveur de t\xE9l\xE9chargement injoignable." : "Impossible de pr\xE9parer les ressources du jeu."; } var CategorySelectionError = class extends Error { }; function uniqueAssets(categories2) { const inventory = /* @__PURE__ */ new Map(); for (const category2 of categories2) { for (const asset2 of category2.assets) { if (inventory.has(asset2.hash)) { if (inventory.get(asset2.hash).size !== asset2.size) throw new Error(`Conflicting size for install asset ${asset2.hash}`); } else inventory.set(asset2.hash, asset2); } } return Array.from(inventory.values()); } var AvailableHashes = class extends Set { constructor(owner) { super(); this.owner = owner; } add(hash) { if (!this.has(hash)) { super.add(hash); this.owner.counted(hash, 1); } return this; } delete(hash) { if (!super.delete(hash)) return false; this.owner.counted(hash, -1); return true; } clear() { super.clear(); this.owner.tally = null; this.owner.transferTally = null; } }; var TransferTargets = class extends Map { constructor(owner) { super(); this.owner = owner; } set(hash, size) { const tally = this.owner.transferTally; if (!this.has(hash) && tally?.targets === this) { tally.filesTotal += 1; tally.bytesTotal += size; if (this.owner.available.has(hash)) { tally.filesDone += 1; tally.bytesDone += size; } } else if (this.has(hash) && tally?.targets === this) this.owner.transferTally = null; return super.set(hash, size); } }; function targetsFor(missing, inventory, packed) { if (!packed) return missing.map((asset2) => ({ asset: asset2, assets: [asset2] })); const requestedPacks = new Set(missing.filter((asset2) => asset2.carrier.kind === "pack").map((asset2) => asset2.carrier.packHash)); const members = new Map(Array.from(requestedPacks, (hash) => [hash, []])); for (const asset2 of inventory) members.get(asset2.carrier.packHash)?.push(asset2); const targets = Array.from(members, ([packHash, assets]) => ({ packHash, assets })); for (const asset2 of missing) if (asset2.carrier.kind !== "pack") targets.push({ asset: asset2, assets: [asset2] }); return targets; } function delay2(milliseconds, signal) { return new Promise((resolve, reject) => { if (signal.aborted) { reject(signal.reason ?? aborted()); return; } const cancel = () => { clearTimeout(timer); reject(signal.reason ?? aborted()); }; const timer = setTimeout(() => { signal.removeEventListener("abort", cancel); resolve(); }, milliseconds); signal.addEventListener("abort", cancel, { once: true }); }); } var AssetPredownloader = class { constructor(cache2, sourceKey2, installProfile, options = {}) { if (typeof sourceKey2 !== "string" || !sourceKey2.trim()) throw new Error("Asset installation requires a source key"); if (!["desktop-bc7", "desktop-compatibility"].includes(installProfile)) throw new Error("Unsupported install profile"); this.cache = cache2; this.sourceKey = sourceKey2; this.installProfile = installProfile; this.timing = { heartbeat: options.stateHeartbeatMs ?? 1e3, window: options.speedWindowMs ?? 5e3, retry: options.planRetryBaseDelayMs ?? 250, ceiling: options.planRetryMaxDelayMs ?? 1e4, // Khaos (owner 2026-11-04, a player stuck on "Vérification des assets du serveur..." at 5 %): a required stage // retried a failing index download forever with nothing on screen. After this many failed tries the stage ends // with its error; the loading screen shows it ("Serveur de téléchargement injoignable. Nouvelle tentative...") // and runs the stage again a few seconds later (serverAssetProgress installAllStages). visibleFailures: options.planVisibleFailures ?? 5 }; if (Object.values(this.timing).some((value) => !Number.isFinite(value) || value <= 0) || this.timing.ceiling < this.timing.retry) throw new Error("Invalid installation timing"); this.clock = options.clock ?? { now: Date.now, interval: setInterval, clearInterval, sleep: delay2 }; this.onListenerError = options.onListenerError ?? (() => { }); this.logger = options.logger ?? null; this.scanProgress = null; this.listeners = /* @__PURE__ */ new Set(); this.epoch = 0; this.presenceSequence = 0; this.plan = null; this.planRevision = null; this.checked = /* @__PURE__ */ new Set(); this.completedRoles = /* @__PURE__ */ new Set(); this.planLoad = null; this.scanTask = null; this.tally = null; this.transferTally = null; this.available = new AvailableHashes(this); this.phase = "idle"; this.speedProfile = "balanced"; this.selected = []; this.run = null; this.progress = { targets: new TransferTargets(this), samples: [], active: 0, failed: 0, last: null, error: null }; this.heartbeat = null; this.lastNotification = 0; } /** The per-category counts of the loaded plan: counted once per plan, then kept by AvailableHashes. */ categoryTally() { const plan = this.plan?.plan ?? null; if (this.tally?.plan === plan) return this.tally; const byHash = /* @__PURE__ */ new Map(), rows = []; for (const [id, category2] of Object.entries(plan?.categories ?? {})) { const row = { id, label: category2.label, assetCount: category2.assets.length, bytesTotal: 0, filesDone: 0, bytesDone: 0 }; rows.push(row); for (const asset2 of category2.assets) { row.bytesTotal += asset2.size; let entries2 = byHash.get(asset2.hash); if (!entries2) byHash.set(asset2.hash, entries2 = []); const last = entries2.at(-1); if (last?.row === row) { last.count += 1; last.bytes += asset2.size; } else entries2.push({ row, count: 1, bytes: asset2.size }); if (this.available.has(asset2.hash)) { row.filesDone += 1; row.bytesDone += asset2.size; } } } this.tally = { plan, byHash, rows }; return this.tally; } /** The totals of this run's transfer targets: counted once per run, then kept by TransferTargets and AvailableHashes. */ transferCounts() { const targets = this.progress.targets; if (this.transferTally?.targets === targets) return this.transferTally; const tally = { targets, filesTotal: 0, bytesTotal: 0, filesDone: 0, bytesDone: 0 }; for (const [hash, size] of targets) { tally.filesTotal += 1; tally.bytesTotal += size; if (this.available.has(hash)) { tally.filesDone += 1; tally.bytesDone += size; } } this.transferTally = tally; return tally; } /** `hash` became available (delta 1) or not (-1): the counts that name it follow. */ counted(hash, delta) { for (const entry of this.tally?.byHash.get(hash) ?? []) { entry.row.filesDone += delta * entry.count; entry.row.bytesDone += delta * entry.bytes; } const transfer = this.transferTally; if (transfer?.targets.has(hash)) { transfer.filesDone += delta; transfer.bytesDone += delta * transfer.targets.get(hash); } } getState() { const plan = this.plan?.plan; const categories2 = this.categoryTally().rows.map((row) => ({ id: row.id, label: row.label, assetCount: row.assetCount, bytesTotal: row.bytesTotal, filesDone: row.filesDone, bytesDone: row.bytesDone })); let transfer = null; if (this.progress.targets.size) { const totals = this.transferCounts(); transfer = { filesTotal: totals.filesTotal, filesDone: totals.filesDone, bytesTotal: totals.bytesTotal, bytesDone: totals.bytesDone }; } const samples = this.progress.samples; const cutoff = this.clock.now() - this.timing.window; while (samples.length && samples[0].time < cutoff) samples.shift(); const total = samples.reduce((sum, sample) => ({ bytes: sum.bytes + sample.bytes, files: sum.files + sample.files }), { bytes: 0, files: 0 }); const active = this.phase === "downloading"; return { sourceKey: this.sourceKey, installProfile: this.installProfile, phase: this.phase, scanned: Boolean(plan), categories: categories2, scan: this.phase === "scanning" && this.scanProgress ? { ...this.scanProgress } : null, requiredCategoryIds: planRoleCategoryIds(plan, "required"), backgroundCategoryIds: planRoleCategoryIds(plan, "background"), lateCategoryIds: Array.from(plan?.backgroundCategories ?? []).filter((id) => LATE_CATEGORIES.has(id)), optionalCategoryIds: Array.from(plan?.optionalCategories ?? []), activeCategoryIds: Array.from(this.selected), transfer, speedProfile: this.speedProfile, speedBps: active ? Math.round(total.bytes * 1e3 / this.timing.window) : 0, filesPerSecond: active ? Math.round(total.files * 1e4 / this.timing.window) / 10 : 0, activeFiles: this.progress.active, retryingFiles: 0, lastProgressAt: this.progress.last, failedFiles: this.progress.failed, error: this.progress.error }; } onStateChanged(listener) { if (typeof listener !== "function") throw new TypeError("State listener must be a function"); this.listeners.add(listener); this.notifyOne(listener); return () => this.listeners.delete(listener); } notifyOne(listener) { try { listener(this.getState()); } catch (error) { try { this.onListenerError(error); } catch { } } } publish(force = true) { if (!force && this.clock.now() - this.lastNotification < 500) return; this.lastNotification = this.clock.now(); for (const listener of Array.from(this.listeners)) this.notifyOne(listener); } transition(phase) { this.phase = phase; if (phase !== "scanning") this.scanProgress = null; if (this.heartbeat !== null && phase !== "downloading") { this.clock.clearInterval(this.heartbeat); this.heartbeat = null; } if (this.heartbeat === null && phase === "downloading") { this.heartbeat = this.clock.interval(() => this.publish(), this.timing.heartbeat); this.heartbeat.unref?.(); } this.publish(); } clearPlan() { this.epoch += 1; this.presenceSequence += 1; this.plan = this.planLoad = this.scanTask = null; this.planRevision = null; this.available.clear(); this.checked.clear(); this.completedRoles.clear(); } /** The categories of `role`'s stage in the loaded plan. */ roleCategoryIds(role) { return planRoleCategoryIds(this.plan?.plan, role); } /** * The final state of `role`'s stage when it already ended complete for the loaded plan in this session and every * one of its files is still known present; null otherwise. Lets a caller of a finished stage get its answer while * another stage runs, without stopping that one. */ stageState(role) { if (!roles.has(role) || this.plan === null || !this.completedRoles.has(role)) return null; const ids = this.roleCategoryIds(role); if (!ids.every((id) => this.checked.has(id) && this.plan.plan.categories[id]?.assets.every((asset2) => this.available.has(asset2.hash)))) return null; return { ...this.getState(), phase: "done", scan: null, activeCategoryIds: ids, transfer: null, speedBps: 0, filesPerSecond: 0, activeFiles: 0, failedFiles: 0, error: null }; } async loadPlan() { if (this.plan) return this.plan; if (this.planLoad) return this.planLoad; const epoch = this.epoch; const loading = Promise.resolve().then(() => this.cache.loadInstallPlan(this.installProfile)).then((snapshot2) => { if (snapshot2.plan.profile !== this.installProfile) throw new Error(`Install profile differs from ${this.installProfile}`); if (epoch !== this.epoch) return null; this.plan = snapshot2; this.available.clear(); this.checked.clear(); this.completedRoles.clear(); if (this.run?.selection.role) this.selectRole(this.run.selection.role); this.publish(); return snapshot2; }); this.planLoad = loading; try { return await loading; } finally { if (this.planLoad === loading) this.planLoad = null; } } scan() { if (this.scanTask) return this.scanTask; const epoch = this.epoch; const idle = this.phase === "idle"; if (idle) this.transition("scanning"); const task = Promise.resolve().then(async () => { const snapshot2 = await this.loadPlan(); if (epoch !== this.epoch || !snapshot2) return; const unknown = this.run ? [] : Object.keys(snapshot2.plan.categories).filter((id) => !this.checked.has(id)); if (unknown.length) await this.checkPresence(unknown.map((id) => snapshot2.plan.categories[id]), void 0, this.available.size ? new Set(this.available) : null); if (epoch === this.epoch && idle && this.phase === "scanning") this.transition("idle"); }).catch((error) => { if (epoch !== this.epoch) return; if (idle && !this.run) { this.progress.error = message(error); this.transition("error"); } throw error; }).finally(() => { if (this.scanTask === task) this.scanTask = null; }); this.scanTask = task; return task; } start(categoryIds2, speed = this.speedProfile, options = {}) { if (!Array.isArray(categoryIds2) || categoryIds2.some((id) => typeof id !== "string" || !id)) return Promise.reject(new CategorySelectionError("Invalid predownload categories")); return this.begin({ ids: Array.from(new Set(categoryIds2)) }, speed, options); } startPlanCategories(role, speed = this.speedProfile, options = {}) { if (!roles.has(role)) return Promise.reject(new CategorySelectionError(`Unknown install role: ${role}`)); return this.begin({ role }, speed, { ...options, requireComplete: role === "required" }); } selectRole(role) { this.selected = planRoleCategoryIds(this.plan.plan, role); } selectedCategories() { const unknown = this.selected.filter((id) => !Object.hasOwn(this.plan.plan.categories, id)); if (unknown.length) throw new CategorySelectionError(`Unknown predownload categories: ${unknown.join(", ")}`); return this.selected.map((id) => this.plan.plan.categories[id]); } assertRunning(run) { if (this.run !== run || run.controller.signal.aborted) throw run.controller.signal.reason ?? aborted(); } async begin(selection, speed, options) { if (!speeds.has(speed)) throw new Error("Unknown download speed profile"); if (this.run) this.logger?.info?.("Install run replaced", { sourceKey: this.sourceKey, stopped: this.run.selection.role ?? "categories", by: selection.role ?? "categories" }); this.run?.controller.abort(aborted()); const run = { controller: new AbortController(), selection }; this.run = run; this.selected = selection.ids ?? (this.plan ? planRoleCategoryIds(this.plan.plan, selection.role) : []); this.speedProfile = speed; this.progress = { targets: new TransferTargets(this), samples: [], active: 0, failed: 0, last: null, error: null }; const required = options.requireComplete === true; try { this.cache.setDownloadSpeedProfile(speed); const stopMetadata = this.followMetadata(run); try { if (options.refreshManifest === true) { this.transition("scanning"); const revision = await this.planOperation(() => this.cache.refreshManifestIndex(), required, run); this.assertRunning(run); if (this.plan === null || this.planRevision === null || revision !== this.planRevision) { this.clearPlan(); this.planRevision = revision ?? null; } } if (!this.plan) { this.transition("scanning"); await this.planOperation(() => this.loadPlan(), required, run); } } finally { stopMetadata(); } this.assertRunning(run); if (selection.role) this.selectRole(selection.role); this.selectedCategories(); await this.install(run, required); } catch (error) { if (this.run !== run || run.controller.signal.aborted || isAbort(error)) return; this.progress.samples = []; this.progress.active = 0; this.progress.error = installationError(error); this.transition("error"); if (required || error instanceof CategorySelectionError) throw error; } finally { if (this.run === run) this.run = null; } } pause() { if (!["scanning", "downloading"].includes(this.phase)) return; this.run?.controller.abort(aborted()); this.run = null; this.presenceSequence += 1; Object.assign(this.progress, { samples: [], active: 0, last: null }); this.transition("paused"); } reset() { this.run?.controller.abort(aborted()); this.run = null; this.selected = []; this.progress = { targets: new TransferTargets(this), samples: [], active: 0, failed: 0, last: null, error: null }; this.clearPlan(); this.transition("idle"); } /** * While `run` loads its index files, the cache's metadata bytes are this stage's scan progress * ({ role, kind: "metadata", bytesDone, bytesTotal }). Returns the function that stops following them. */ followMetadata(run) { if (typeof this.cache.onMetadataProgress !== "function") return () => { }; let progress = null; const stop = this.cache.onMetadataProgress(({ bytesDone, bytesTotal }) => { if (this.run !== run || this.phase !== "scanning" || !(bytesTotal > 0)) return; if (progress === null || this.scanProgress !== progress) { progress = { role: run.selection.role ?? null, kind: "metadata", bytesDone: 0, bytesTotal: 0 }; this.scanProgress = progress; } Object.assign(progress, { bytesDone: Math.min(bytesDone, bytesTotal), bytesTotal }); this.publish(false); }); return () => { stop(); if (progress !== null && this.scanProgress === progress) this.scanProgress = null; }; } async planOperation(operation, required, run) { for (let attempt = 0; ; attempt += 1) { this.assertRunning(run); try { const value = await operation(); this.assertRunning(run); return value; } catch (error) { this.assertRunning(run); if (!required || !retryablePlanError(error)) throw error; if (attempt + 1 >= this.timing.visibleFailures) { this.logger?.warn?.("Install index unavailable after retries", { sourceKey: this.sourceKey, tries: attempt + 1, error: message(error) }); throw error; } await this.clock.sleep(Math.min(this.timing.ceiling, this.timing.retry * 2 ** Math.min(attempt, 10)), run.controller.signal); } } } /** * Which assets of `categories` are on disk. `trusted` (a Set of hashes, or null) are known present already and are * not looked at again. While it runs, the state's `scan` counts the assets checked (published at most every 500 ms). */ async checkPresence(categories2, run, trusted = null) { const epoch = this.epoch; const sequence = ++this.presenceSequence; const assets = uniqueAssets(categories2); const checked = trusted === null ? assets : assets.filter((asset2) => !trusted.has(asset2.hash)); const startedAt = this.clock.now(); const progress = { role: run?.selection.role ?? null, filesChecked: assets.length - checked.length, filesTotal: assets.length }; this.scanProgress = progress; this.publish(); const found = await this.cache.findAvailableAssetHashes(checked, run?.controller.signal, (count2) => { if (this.scanProgress !== progress) return; progress.filesChecked = Math.min(progress.filesTotal, progress.filesChecked + count2); this.publish(false); }); if (run) this.assertRunning(run); if (epoch !== this.epoch || sequence !== this.presenceSequence) return false; for (const asset2 of assets) { this.available.delete(asset2.hash); if (found.has(asset2.hash) || trusted !== null && trusted.has(asset2.hash)) this.available.add(asset2.hash); } for (const [id, category2] of Object.entries(this.plan?.plan.categories ?? {})) if (categories2.includes(category2)) this.checked.add(id); this.logger?.info?.("Install check", { sourceKey: this.sourceKey, role: run?.selection.role ?? null, assets: assets.length, checked: checked.length, present: assets.filter((asset2) => this.available.has(asset2.hash)).length, ms: this.clock.now() - startedAt }); this.publish(); return true; } /** * The background stage after a complete required stage: the required receipt (signed, bound to this plan and to the * cache generation; the required stage itself opens the game on it without checking a file) already vouches for the * required assets, so only the background-only ones are checked. Before, the background check looked at every * required file again right after the required stage (most of the 1.5-3 min on an install the update outdated). */ async receiptTrustedAssets(snapshot2, run) { if (run.selection.role !== "background" && run.selection.role !== "complete") return null; const current = await this.cache.checkRequiredInstallCompletion(snapshot2, run.controller.signal); this.assertRunning(run); if (!current.complete) return null; const required = Array.from(snapshot2.plan.requiredCategories ?? [], (id) => snapshot2.plan.categories[id]).filter(Boolean); return new Set(uniqueAssets(required).map((asset2) => asset2.hash)); } /** Hashes not to look at again: those this session already knows present, plus the required receipt's. */ async knownPresent(snapshot2, run) { const receipt = await this.receiptTrustedAssets(snapshot2, run); if (receipt === null) return this.available.size ? new Set(this.available) : null; for (const hash of this.available) receipt.add(hash); return receipt; } finish(run = null) { if (run?.selection.role) this.completedRoles.add(run.selection.role); this.progress.samples = []; this.progress.active = 0; this.transition("done"); } backgroundFinished(categories2, error) { this.progress.failed = categories2.reduce((count2, category2) => count2 + category2.assets.filter((asset2) => !this.available.has(asset2.hash)).length, 0); if (this.progress.failed) this.progress.error = `${this.progress.failed} asset(s) en \xE9chec${error === void 0 ? "" : ` - dernier: ${message(error)}`}`; this.finish(); } async install(run, required) { const request = { priority: required ? "required" : "background", signal: run.controller.signal, maxAttempts: required ? null : 3 }; let receipt = null; let staleRevision; let presenceKnown = this.selected.every((id) => this.checked.has(id)); let verifyAll = false; this.progress.last = this.clock.now(); for (; ; ) { this.assertRunning(run); const snapshot2 = this.plan; const categories2 = this.selectedCategories(); const assets = uniqueAssets(categories2); const needsReceipt = required && run.selection.role === "required"; if (needsReceipt && receipt?.hash !== snapshot2.hash) { const current = await this.cache.checkRequiredInstallCompletion(snapshot2, request.signal); this.assertRunning(run); if (current.complete) { for (const asset2 of assets) this.available.add(asset2.hash); for (const id of this.selected) this.checked.add(id); this.finish(run); return; } if (current.generation === null) { await this.clock.sleep(this.timing.retry, request.signal); continue; } receipt = { hash: snapshot2.hash, generation: current.generation }; } if (!presenceKnown) { presenceKnown = await this.checkPresence(categories2, run, verifyAll ? null : await this.knownPresent(snapshot2, run)); if (!presenceKnown) continue; verifyAll = false; } const missing = assets.filter((asset2) => !this.available.has(asset2.hash)); if (!missing.length) { const complete = !needsReceipt || await this.cache.recordRequiredInstallCompletion(snapshot2, receipt.generation, request.signal); this.assertRunning(run); if (complete) { this.finish(run); return; } receipt = null; presenceKnown = false; verifyAll = true; continue; } for (const asset2 of missing) this.progress.targets.set(asset2.hash, asset2.size); this.transition("downloading"); let mode = this.cache.getTransportMode(); if (mode === "unknown" && missing.some((asset2) => asset2.carrier.kind === "pack")) { try { mode = await this.cache.probePackTransport(request); } catch (error) { if (required) throw error; this.backgroundFinished(categories2, error); return; } } this.assertRunning(run); const targets = targetsFor(missing, uniqueAssets(Object.values(snapshot2.plan.categories)), mode === "pack"); const failures = await this.transferTargets(targets, request, run); presenceKnown = await this.checkPresence(categories2, run, new Set(this.available)); if (failures.some(transportFailure) || mode === "pack" && this.cache.getTransportMode() === "individual") continue; const staleError = failures.find(stale); if (required && staleError) { const revision = await this.planOperation(() => this.cache.refreshManifestIndex(), true, run); if (revision === staleRevision) throw staleError; staleRevision = revision; this.clearPlan(); this.planRevision = revision ?? null; await this.planOperation(() => this.loadPlan(), true, run); presenceKnown = false; continue; } if (failures.length) { if (required) throw failures[0]; this.backgroundFinished(categories2, failures.at(-1)); return; } if (!required && assets.some((asset2) => !this.available.has(asset2.hash))) { this.backgroundFinished(categories2); return; } } } async transferTargets(targets, request, run) { let cursor = 0; const results = new Array(targets.length); const worker = async () => { while (cursor < targets.length) { this.assertRunning(run); const index = cursor++; const target = targets[index]; this.progress.active += 1; this.publish(false); try { const result = target.packHash ? await this.cache.ensureInstallPack(target.packHash, request) : await this.cache.ensureInstallAsset(target.asset, request); this.assertRunning(run); const files6 = target.assets.filter((asset2) => this.progress.targets.has(asset2.hash) && !this.available.has(asset2.hash)).length; for (const asset2 of target.assets) this.available.add(asset2.hash); this.progress.last = this.clock.now(); this.progress.samples.push({ time: this.progress.last, bytes: result.completion?.networkBytes ?? 0, files: files6 }); this.publish(false); } catch (error) { results[index] = error; } finally { if (this.run === run) { this.progress.active -= 1; this.publish(false); } } } }; await Promise.allSettled(Array.from({ length: Math.min(64, targets.length) }, worker)); this.assertRunning(run); return results.filter((error) => error !== void 0); } }; // src/electron/khaos/assetPrefetch.js var AssetPrefetch = class { constructor(dependencies) { this.dependencies = dependencies; this.running = /* @__PURE__ */ new Map(); } isRunning(key) { return this.running.has(key); } async start(key) { const deps = this.dependencies; if (this.running.has(key)) return; const lease = { cancelled: false }; this.running.set(key, lease); try { for (const role of ["required", "background"]) { if (lease.cancelled) break; const state = await deps.prepare(key, role); if (state?.phase === "paused") break; } } catch (error) { try { deps.onError(error); } catch { } } finally { if (this.running.get(key) === lease) this.running.delete(key); try { deps.onSettled(); } catch { } } } stop(key) { const lease = this.running.get(key); if (!lease) return; lease.cancelled = true; this.running.delete(key); } }; // src/electron/khaos/assetTrace.js var import_node_fs3 = __toESM(require("node:fs"), 1); var file = process.env.KHAOS_ASSET_TRACE ? `${process.env.KHAOS_ASSET_TRACE}.main` : ""; var stream = null; var khaosAssetTraceOn = file !== ""; function khaosAssetTrace(rec) { if (!khaosAssetTraceOn) return; try { stream ??= import_node_fs3.default.createWriteStream(file, { flags: "a" }); stream.write(`${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), ...rec })} `); } catch { } } if (khaosAssetTraceOn) { let last = performance.now(); const timer = setInterval(() => { const now = performance.now(), late = now - last - 20; last = now; if (late >= 30) khaosAssetTrace({ k: "lag", ms: Math.round(late) }); }, 20); timer.unref?.(); const mib = (bytes) => Math.round(bytes / 1048576); const memory = setInterval(() => { const used = process.memoryUsage(); khaosAssetTrace({ k: "mem", rss: mib(used.rss), heap: mib(used.heapUsed), external: mib(used.external), buffers: mib(used.arrayBuffers) }); }, 5e3); memory.unref?.(); } // src/electron/khaos/assetProtocol.js var import_promises9 = __toESM(require("node:fs/promises"), 1); var import_node_path11 = __toESM(require("node:path"), 1); var import_node_zlib = require("node:zlib"); var import_node_util = require("node:util"); var expandBrotli = (0, import_node_util.promisify)(import_node_zlib.brotliDecompress); var contentTypes = { bin: "application/octet-stream", json: "application/json; charset=utf-8", gz: "application/gzip", jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", webp: "image/webp", avif: "image/avif", svg: "image/svg+xml", mp3: "audio/mpeg", ogg: "audio/ogg", wav: "audio/wav", css: "text/css; charset=utf-8", js: "text/javascript; charset=utf-8", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf" }; var assetMimeType = (filename) => contentTypes[import_node_path11.default.extname(filename).slice(1).toLowerCase()] ?? "application/octet-stream"; function assetRange(header, size) { if (header == null) return { start: 0, length: size, status: 200 }; const match = /^bytes=([0-9]+)-([0-9]*)$/u.exec(header.trim()); const first = match ? Number(match[1]) : NaN, last = match?.[2] ? Number(match[2]) : size - 1; if (!Number.isSafeInteger(first) || !Number.isSafeInteger(last) || first < 0 || last < first || first >= size) return { status: 416, start: 0, length: 0 }; return { status: 206, start: first, length: Math.min(last, size - 1) - first + 1 }; } function representationHeaders(record7) { const headers = new Headers(); for (const [name, value] of Object.entries({ "content-type": record7.contentType, "cache-control": "public, max-age=31536000, immutable", "accept-ranges": "bytes", "x-dofus-asset-source": record7.source, "x-dofus-asset-hash": record7.hash, "x-dofus-asset-version": record7.version })) { if (value !== void 0) headers.set(name, String(value)); } return headers; } async function assetResponse(request, record7) { const size = record7.file ? record7.file.size : record7.bytes.byteLength; const range = assetRange(request.headers?.get("range"), size); let headers; try { headers = representationHeaders(record7); } catch (error) { await record7.file?.close().catch(() => { }); throw error; } headers.set("content-length", String(range.length)); if (range.status !== 200) headers.set("content-range", range.status === 416 ? `bytes */${size}` : `bytes ${range.start}-${range.start + range.length - 1}/${size}`); if (request.method === "HEAD" || range.length === 0) { await record7.file?.close(); return new Response(null, { status: range.status, headers }); } if (!record7.file) return new Response(record7.bytes.subarray(range.start, range.start + range.length), { status: range.status, headers }); const file2 = record7.file; let offset = range.start, remaining = range.length, closed = false; const release = async () => { if (!closed) { closed = true; await file2.close(); } }; const body = new ReadableStream({ async pull(destination) { try { checkSignal(request.signal); if (remaining === 0) { await release(); destination.close(); return; } const bytes = await file2.read(offset, Math.min(remaining, 128 * 1024), request.signal); if (closed) return; if (bytes.length === 0 || bytes.length > remaining) throw new Error("Asset file ended before its advertised response range"); offset += bytes.length; remaining -= bytes.length; destination.enqueue(bytes); } catch (error) { await release().catch(() => { }); destination.error(error); } }, cancel: release }); return new Response(body, { status: range.status, headers }); } async function coreAsset(request, directory) { try { const url = new URL(request.url); if (url.host !== "core") return new Response(null, { status: 404 }); const target = assetDirectory(directory, decodeURIComponent(url.pathname.replace(/^\/+/, ""))); const stat4 = await import_promises9.default.lstat(target); if (!stat4.isFile() || stat4.isSymbolicLink()) return new Response(null, { status: 404 }); const relative = import_node_path11.default.relative(import_node_path11.default.resolve(directory), import_node_path11.default.dirname(target)).split(import_node_path11.default.sep).filter(Boolean); let parent = import_node_path11.default.resolve(directory); for (const component of ["", ...relative]) { if (component) parent = import_node_path11.default.join(parent, component); const entry = await import_promises9.default.lstat(parent); if (entry.isSymbolicLink() || !entry.isDirectory()) return new Response(null, { status: 404 }); } const handle = await import_promises9.default.open(target, "r"); const file2 = { size: stat4.size, async read(offset, length) { const bytes = Buffer.allocUnsafe(length), result = await handle.read(bytes, 0, length, offset); return bytes.subarray(0, result.bytesRead); }, close: () => handle.close() }; return assetResponse(request, { file: file2, source: "core", contentType: assetMimeType(target) }); } catch (error) { if (request.signal?.aborted) throw error; return new Response(null, { status: 404 }); } } async function expandMapAsset(record7) { const bytes = await expandBrotli(record7.bytes, { maxOutputLength: 256 * 1024 * 1024 }); return { ...record7, bytes, contentType: "application/octet-stream" }; } // src/electron/khaos/assetStorage.js var import_promises10 = __toESM(require("node:fs/promises"), 1); var import_node_path12 = __toESM(require("node:path"), 1); var import_node_crypto11 = require("node:crypto"); var sourceKey = (key) => typeof key === "string" && /^[0-9a-f]{16}$/u.test(key); var safeState = (record7) => record7?.schemaVersion === 1 && record7.sources && typeof record7.sources === "object" && !Array.isArray(record7.sources); var AssetSourceRegistry = class { #file; #queue = Promise.resolve(); #entries; constructor(filename) { this.#file = import_node_path12.default.resolve(filename); } #serial(operation) { const task = this.#queue.then(operation); this.#queue = task.catch(() => { }); return task; } async #load() { if (this.#entries) return this.#entries; const entries2 = /* @__PURE__ */ new Map(); try { const bytes = await storedBytes(this.#file, 1024 * 1024), record7 = bytes ? JSON.parse(bytes.toString("utf8")) : null; if (safeState(record7)) for (const [key, value] of Object.entries(record7.sources)) { if (sourceKey(key) && typeof value?.remoteBaseUrl === "string" && value.remoteBaseUrl && Number.isFinite(value.lastUsedAt) && value.lastUsedAt >= 0) entries2.set(key, { remoteBaseUrl: value.remoteBaseUrl, lastUsedAt: value.lastUsedAt }); } } catch (error) { if (error?.code && error.code !== "ENOENT") throw error; } this.#entries = entries2; return entries2; } entries() { return this.#serial(async () => new Map(Array.from(await this.#load(), ([key, value]) => [key, { ...value }]))); } #update(change) { return this.#serial(async () => { const entries2 = new Map(await this.#load()); change(entries2); const bytes = Buffer.from(JSON.stringify({ schemaVersion: 1, sources: Object.fromEntries(entries2) })); await persistBytes(import_node_path12.default.dirname(this.#file), this.#file, bytes); this.#entries = entries2; }); } touch(key, remoteBaseUrl, lastUsedAt = Date.now()) { if (!sourceKey(key) || typeof remoteBaseUrl !== "string" || !remoteBaseUrl || !Number.isFinite(lastUsedAt) || lastUsedAt < 0) return Promise.reject(new Error("Invalid asset source registry entry")); return this.#update((entries2) => entries2.set(key, { remoteBaseUrl, lastUsedAt })); } remove(keys) { return this.#update((entries2) => keys.forEach((key) => entries2.delete(key))); } }; async function fileIdentity(filename) { const stat4 = await import_promises10.default.lstat(filename); if (!stat4.isFile() || stat4.isSymbolicLink()) throw new Error("Migration input is not a regular file"); const handle = await import_promises10.default.open(filename, "r"), digest4 = (0, import_node_crypto11.createHash)("sha256"); let bytes = 0; try { for await (const chunk of handle.createReadStream({ autoClose: false })) { digest4.update(chunk); bytes += chunk.length; } } finally { await handle.close(); } if (bytes !== stat4.size) throw new Error("Migration input changed while hashing"); return { hash: digest4.digest("hex"), size: bytes }; } var sameFile = (left, right) => left.size === right.size && left.hash === right.hash; async function regularDirectories(directory) { try { const parent = await import_promises10.default.lstat(directory); if (!parent.isDirectory() || parent.isSymbolicLink()) throw new Error("Asset cache directory is linked or invalid"); return (await import_promises10.default.readdir(directory, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.isSymbolicLink()).map((entry) => entry.name); } catch (error) { if (error.code === "ENOENT") return []; throw error; } } async function migrateAssetRoot(source, target) { source = import_node_path12.default.resolve(source); target = import_node_path12.default.resolve(target); if (source === target) return { moved: 0, retained: 0 }; const relative = import_node_path12.default.relative(source, target), reverse = import_node_path12.default.relative(target, source); if (![relative, reverse].every((value) => import_node_path12.default.isAbsolute(value) || value.split(import_node_path12.default.sep)[0] === "..")) throw new Error("Asset migration roots overlap"); try { const stat4 = await import_promises10.default.lstat(source); if (!stat4.isDirectory() || stat4.isSymbolicLink()) throw new Error("Asset migration root is linked or invalid"); } catch (error) { if (error.code === "ENOENT") return { moved: 0, retained: 0 }; throw error; } await import_promises10.default.mkdir(target, { recursive: true }); const destination = await import_promises10.default.lstat(target); if (!destination.isDirectory() || destination.isSymbolicLink()) throw new Error("Asset migration target is linked or invalid"); const physicalSource = await import_promises10.default.realpath(source), physicalTarget = await import_promises10.default.realpath(target); const separate = (a, b) => { const difference = import_node_path12.default.relative(a, b); return import_node_path12.default.isAbsolute(difference) || difference.split(import_node_path12.default.sep)[0] === ".."; }; if (!separate(physicalSource, physicalTarget) || !separate(physicalTarget, physicalSource)) throw new Error("Asset migration roots overlap through linked ancestors"); const result = { moved: 0, retained: 0 }; const visit = async (original, copied) => { await import_promises10.default.mkdir(copied, { recursive: true }); if ((await import_promises10.default.lstat(copied)).isSymbolicLink()) throw new Error("Asset migration destination is linked"); for (const entry of await import_promises10.default.readdir(original, { withFileTypes: true })) { const from = import_node_path12.default.join(original, entry.name), to = import_node_path12.default.join(copied, entry.name); if (entry.isDirectory() && !entry.isSymbolicLink()) { await visit(from, to); continue; } if (!entry.isFile() || entry.isSymbolicLink()) { result.retained++; continue; } const expected = await fileIdentity(from); let existing = null; try { existing = await fileIdentity(to); } catch (error) { if (error.code !== "ENOENT") throw error; } if (existing && !sameFile(existing, expected)) { result.retained++; continue; } if (!existing) { const temporary = import_node_path12.default.join(copied, `.khaos-migrate-${(0, import_node_crypto11.randomUUID)()}`); try { await import_promises10.default.copyFile(from, temporary); const copiedFile = await import_promises10.default.open(temporary, "r+"); try { await copiedFile.sync(); } finally { await copiedFile.close(); } if (!sameFile(await fileIdentity(temporary), expected)) throw new Error("Asset migration copy failed verification"); try { await import_promises10.default.link(temporary, to); } catch (error) { if (error.code !== "EEXIST" || !sameFile(await fileIdentity(to), expected)) throw error; } } finally { await import_promises10.default.rm(temporary, { force: true }); } } if (!sameFile(await fileIdentity(from), expected) || !sameFile(await fileIdentity(to), expected)) throw new Error("Asset migration changed before cleanup"); await import_promises10.default.unlink(from); result.moved++; } try { await import_promises10.default.rmdir(original); } catch (error) { if (!["ENOTEMPTY", "EEXIST"].includes(error.code)) throw error; } }; await visit(source, target); return result; } async function migrateSourceBlobs(root, store2) { const result = { moved: 0, deduped: 0, retained: 0 }, sources = import_node_path12.default.join(root, "sources"); for (const source of await regularDirectories(sources)) { if (!sourceKey(source)) continue; const legacy = import_node_path12.default.join(sources, source, "blobs"); try { const stat4 = await import_promises10.default.lstat(legacy); if (!stat4.isDirectory() || stat4.isSymbolicLink()) throw new Error("Legacy blob directory is linked or invalid"); } catch (error) { if (error.code === "ENOENT") continue; throw error; } const folder = import_node_path12.default.join(legacy, "sha256"); for (const prefix of await regularDirectories(folder)) { for (const entry of await import_promises10.default.readdir(import_node_path12.default.join(folder, prefix), { withFileTypes: true })) { if (!entry.isFile() || entry.isSymbolicLink() || !/^[0-9a-f]{64}$/u.test(entry.name)) continue; const file2 = import_node_path12.default.join(folder, prefix, entry.name), identity = await fileIdentity(file2); if (identity.hash !== entry.name) { result.retained++; continue; } const installed = await store2.hasVerifiedBlob(identity.hash, identity.size); if (!installed) await store2.ensureStored(identity.hash, identity.size, async (write) => { const handle = await import_promises10.default.open(file2, "r"); try { for await (const chunk of handle.createReadStream({ autoClose: false })) await write(chunk); } finally { await handle.close(); } }); if (!await store2.hasVerifiedBlob(identity.hash, identity.size) || !sameFile(await fileIdentity(file2), identity)) throw new Error("Shared blob migration changed before cleanup"); await import_promises10.default.unlink(file2); result[installed ? "deduped" : "moved"]++; } } } return result; } async function pruneDesktopAssets({ registry, caches, cacheForSource, blobStore, packStore, root, maxBytes = 12.5 * 1024 ** 3, minAgeMs = 6e5, now = Date.now(), onFailure = null, onPruned = null }) { if (!Number.isFinite(maxBytes) || maxBytes < 0 || !Number.isFinite(minAgeMs) || minAgeMs < 0) throw new Error("Invalid shared cache budget"); const entries2 = await registry.entries(), sourceRoot = import_node_path12.default.join(root, "sources"), staleMs = 30 * 864e5; const obsolete = [...entries2].filter(([key, entry]) => !caches.has(key) && now - entry.lastUsedAt > staleMs).map(([key]) => key); for (const key of obsolete) { await import_promises10.default.rm(import_node_path12.default.join(sourceRoot, key), { recursive: true, force: true }); entries2.delete(key); } if (obsolete.length) await registry.remove(obsolete); for (const key of await regularDirectories(sourceRoot)) { if (entries2.has(key) || caches.has(key)) continue; if (!sourceKey(key)) return "skipped-unknown-source"; const stat4 = await import_promises10.default.lstat(import_node_path12.default.join(sourceRoot, key)); if (now - stat4.mtimeMs <= staleMs) return "skipped-unknown-source"; await import_promises10.default.rm(import_node_path12.default.join(sourceRoot, key), { recursive: true, force: true }); } let summary = null; try { for (const key of /* @__PURE__ */ new Set([...entries2.keys(), ...caches.keys()])) summary = await (caches.get(key) ?? cacheForSource(key, entries2.get(key))).loadPruneSummary(summary); } catch (error) { onFailure?.(error); return "skipped-manifest-failure"; } const kept = pruneLookups(summary); const retained = { blob: kept.blob.retained, pack: kept.pack.retained }, protectedHashes = { blob: kept.blob.protected, pack: kept.pack.protected }, sizes = retained; const stores = { blob: blobStore, pack: packStore }, totals = {}; for (const kind of ["blob", "pack"]) totals[kind] = await stores[kind].pruneToBudget(retained[kind], { maxBytes: Infinity, minAgeMs, protectedHashes: protectedHashes[kind], sizesByHash: sizes[kind] }); if (totals.blob.bytesAfter + totals.pack.bytesAfter > maxBytes) { const protectedBytes = totals.blob.protectedBytes + totals.pack.protectedBytes; const allowance = Math.max(0, maxBytes - protectedBytes); const mutable = Object.fromEntries(["blob", "pack"].map((kind) => [kind, Math.max(0, totals[kind].bytesAfter - totals[kind].protectedBytes)])); const total = mutable.blob + mutable.pack; const packBudget = totals.pack.protectedBytes + (total ? Math.min(mutable.pack, Math.floor(allowance * mutable.pack / total)) : 0); const blobBudget = Math.max(totals.blob.protectedBytes, maxBytes - packBudget); for (const [kind, budget] of [["pack", packBudget], ["blob", blobBudget]]) totals[kind] = await stores[kind].pruneToBudget(retained[kind], { maxBytes: budget, minAgeMs, protectedHashes: protectedHashes[kind], sizesByHash: sizes[kind] }); for (const kind of ["blob", "pack"]) { const other = kind === "blob" ? "pack" : "blob"; if (totals.blob.bytesAfter + totals.pack.bytesAfter <= maxBytes) break; totals[kind] = await stores[kind].pruneToBudget(retained[kind], { maxBytes: Math.max(totals[kind].protectedBytes, maxBytes - totals[other].bytesAfter), minAgeMs, protectedHashes: protectedHashes[kind], sizesByHash: sizes[kind] }); } } onPruned?.(totals); return "pruned"; } // src/electron/khaos/desktopAssets.js var profileName = (profile) => { if (!manifestProfiles.includes(profile)) throw new Error("Invalid desktop install profile"); return profile; }; var speedName = (speed, optional = false) => { if (optional && speed === void 0) return; if (!["eco", "balanced", "max"].includes(speed)) throw new Error("Invalid asset transfer speed profile"); return speed; }; var categories = (ids) => { if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string" || !id)) throw new Error("Predownload category ids must be nonempty strings"); return [...new Set(ids)]; }; var sourceIdentity = (base) => manifestHash(base).substring(0, 16); var sessionKey = (source, profile) => `${source}/${profile}`; var message2 = (error) => String(error?.message ?? error); var optionalCall = (callback, ...args) => { try { return callback?.(...args); } catch { } }; var defaultAssetSource = "https://download.khaosdofus.com/khaos/assets"; var AssetClientUpdateRequiredError = class extends Error { constructor(variant, currentVersion, minimumVersion) { super(`ASSET_CLIENT_UPDATE_REQUIRED: Khaos ${variant} ${currentVersion} cannot read this asset release; version ${minimumVersion} or newer is required`); Object.assign(this, { name: "AssetClientUpdateRequiredError", variant, currentVersion, minimumVersion }); } }; function releaseVersion(version) { const parts = typeof version === "string" ? version.split(".") : []; if (parts.length !== 3 || parts.some((part) => !/^(0|[1-9][0-9]*)$/u.test(part) || !Number.isSafeInteger(Number(part)))) throw new Error("Asset client version must have three safe integer components"); return parts.map(Number); } function assertAssetClientVersion(variant, current, minimums) { const required = minimums[variant], left = releaseVersion(current), right = releaseVersion(required); const difference = left.map((value, index) => Math.sign(value - right[index])).find((value) => value !== 0) ?? 0; if (difference < 0) throw new AssetClientUpdateRequiredError(variant, current, required); } function assetRequestTimeout(bytes) { if (bytes === void 0) return 12e4; if (!Number.isSafeInteger(bytes) || bytes < 0) throw new Error("Invalid expected asset byte length"); return Math.min(216e5, Math.max(12e4, 6e4 + Math.ceil(bytes * 1e3 / 32768))); } function assetBase(value, configured) { const supplied = (value ?? "").trim().replace(/\/+$/u, ""); const base = supplied && supplied !== defaultAssetSource ? supplied : configured.trim().replace(/\/+$/u, ""); const url = new URL(base); if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("Invalid asset source URL"); return base; } var DesktopAssets = class { constructor(options) { this.options = options; this.electron = options.electron; this.logger = options.logger ?? console; this.config = { variant: "game", ...options.config }; this.paths = options.paths; this.dependencies = options.dependencies ?? {}; this.clock = this.dependencies.clock ?? { now: Date.now, timeout: setTimeout, clear: clearTimeout }; this.root = null; this.activeKey = ""; this.currentCache = null; this.caches = /* @__PURE__ */ new Map(); this.installers = /* @__PURE__ */ new Map(); this.preparations = /* @__PURE__ */ new Map(); this.preparationControllers = /* @__PURE__ */ new Map(); this.rendererSources = /* @__PURE__ */ new Map(); this.touched = /* @__PURE__ */ new Map(); this.background = /* @__PURE__ */ new Map(); this.localized = /* @__PURE__ */ new Map(); this.downloadedBytes = 0; this.lastPrune = null; this.pruneTimer = null; this.prunePromise = null; this.initializing = null; this.closed = false; this.changingLocation = false; this.coordinator = this.dependencies.coordinator ?? new DownloadCoordinator({ onNetworkBytes: (count2) => { this.downloadedBytes += count2; }, onCompletedTrace: (record7) => { if (khaosAssetTraceOn) khaosAssetTrace(record7); } }); this.metadata = this.dependencies.metadataParser ?? new MetadataHost({ filename: this.paths.metadataWorker }); this.pruneMetadata = this.dependencies.pruneSummarizer ?? new MetadataHost({ filename: this.paths.metadataWorker, idleMs: 1, requestMs: 6e5 }); this.location = options.location ?? new GameDataLocation({ app: this.electron.app, dialog: this.electron.dialog, BrowserWindow: this.electron.BrowserWindow, logger: this.logger }); this.prefetcher = new AssetPrefetch({ prepare: (installKey, role) => { const [key, profile] = installKey.split("/"); return this.#prepareStage(key, profile, role); }, onSettled: () => this.schedulePrune(), onError: (error) => this.logger.warn("Asset prefetch stopped", { message: message2(error) }) }); } initialize(root) { if (this.closed) return Promise.reject(new Error("Asset runtime is closed")); root = import_node_path13.default.resolve(root); if (this.root && this.root !== root) return Promise.reject(new Error("Asset runtime already has a different storage root")); if (!this.initializing) { this.root = root; this.initializing = (async () => { const legacy = this.paths.legacyCache ?? import_node_path13.default.join(this.electron.app.getPath("userData"), "asset-cache"); const migration = await migrateAssetRoot(legacy, root); if (migration.retained) this.logger.warn("Conflicting legacy assets preserved", migration); const onLockWait = (wait2) => this.logger.warn("Waiting on a content lock", wait2); this.blobs = this.dependencies.blobStore ?? new BlobStore(import_node_path13.default.join(root, "blobs", "sha256"), { onLockWait }); this.packs = this.dependencies.packStore ?? new PackStore({ root: import_node_path13.default.join(root, "packs", "sha256"), onLockWait, onPackOpen: khaosAssetTraceOn ? (opened) => khaosAssetTrace({ k: "pack", pack: opened.packHash.slice(0, 16), open: opened.openPacks }) : void 0 }); this.completion = this.dependencies.completionStore ?? new CompletionStore(root); this.registry = this.dependencies.registry ?? new AssetSourceRegistry(import_node_path13.default.join(root, "sources.json")); await this.completion.recoverInterruptedInvalidation(); await migrateSourceBlobs(root, this.blobs); this.activeKey = this.registerSource(null); this.currentCache = this.cacheForKey(this.activeKey); this.electron.protocol?.handle("dofus-assets", (request) => this.handleProtocol(request)); this.pruneTimer = this.clock.timeout(() => { this.pruneTimer = null; void this.prune().catch((error) => this.logger.warn("Asset cache prune failed", { message: message2(error) })); }, 3e5); this.pruneTimer.unref?.(); return root; })(); void this.initializing.catch(() => { this.initializing = null; this.root = null; }); } return this.initializing; } registerSource(url) { if (url !== null && url !== void 0 && typeof url !== "string") throw new Error("Asset source requires a URL or null"); if (!this.blobs) throw new Error("Asset cache root is not configured"); const base = assetBase(url || null, this.config.baseUrl), key = sourceIdentity(base); if (!this.caches.has(key)) this.caches.set(key, this.#makeCache(base, key)); const now = this.clock.now(); if (!this.touched.has(key) || now - this.touched.get(key) >= 6e5) { this.touched.set(key, now); void this.registry.touch(key, base, now).catch((error) => { this.touched.delete(key); this.logger.warn("Asset registry write failed", { message: message2(error) }); }); } return key; } #makeCache(base, key) { const configured = assetBase(null, this.config.baseUrl); const factory = this.dependencies.cacheFactory ?? ((options) => new AssetCache(options)); return factory({ sourceKey: key, manifestRoot: import_node_path13.default.join(this.root, "sources", key, "manifests"), blobStore: this.blobs, packStore: this.packs, completionStore: this.completion, downloadCoordinator: this.coordinator, remoteBaseUrl: base, manifestUrl: base === configured ? this.config.manifestUrl || `${base}/asset-manifest.json` : `${base}/asset-manifest.json`, metadataParser: this.metadata, pruneSummarizer: this.pruneMetadata, fetcher: this.dependencies.fetcher ?? ((target, request) => { const timeout = AbortSignal.timeout(assetRequestTimeout(request.expectedBytes)); const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout; return this.electron.net.fetch(target, { signal, headers: request.headers, cache: "no-store" }); }), validateRoot: (manifest) => assertAssetClientVersion(this.config.variant, this.config.version ?? this.electron.app.getVersion(), manifest.minimumClients), releaseMemory: this.options.releaseMemory, logger: this.logger, trace: khaosAssetTraceOn ? khaosAssetTrace : void 0, record: (line) => optionalCall(globalThis.__khaosStabilityLine, line) }); } cacheForKey(key) { return this.caches.get(key) ?? null; } async #protocolCache(url) { const key = new URL(url).pathname.split("/").filter(Boolean)[0]; if (key === "current") return this.currentCache; if (this.caches.has(key)) return this.caches.get(key); const source = (await this.registry.entries()).get(key); if (!source) return null; const actual = this.registerSource(source.remoteBaseUrl); return actual === key ? this.cacheForKey(key) : null; } async selectSource(rendererId, url, profile) { profileName(profile); const key = this.registerSource(url); this.activeKey = key; this.currentCache = this.cacheForKey(key); this.config.installProfile = profile; this.installer(profile, key); await this.options.onSourceSelected?.(rendererId, key); this.rendererSources.set(rendererId, key); return key; } forgetRenderer(rendererId) { this.rendererSources.delete(rendererId); } async handleProtocol(request) { if (!["GET", "HEAD"].includes(request.method)) return new Response(null, { status: 405, headers: { allow: "GET, HEAD" } }); const started = khaosAssetTraceOn ? performance.now() : 0; try { const url = new URL(request.url); if (url.protocol !== "dofus-assets:") return new Response(null, { status: 404 }); if (url.host === "core") return coreAsset(request, this.paths.core); if (url.host !== "game") return new Response(null, { status: 404 }); const localized = await this.#localizedRequest(request); if (localized) { const response = await this.handleProtocol(localized); if (response.ok) return response; } const cache2 = await this.#protocolCache(request.url); if (!cache2) return new Response(null, { status: 503 }); let record7; try { record7 = await cache2.open(request.url, request.signal); } catch (error) { if (error.name === "AssetClientUpdateRequiredError" || !url.pathname.includes("/map3/") || !url.pathname.endsWith("/map.bin")) throw error; const compressed = new URL(request.url); compressed.pathname += ".br"; try { record7 = await expandMapAsset(await cache2.get(compressed.toString(), request.signal)); } catch (compressedError) { throw compressedError?.status === 404 ? error : compressedError; } } if (khaosAssetTraceOn) khaosAssetTrace({ k: "req", path: url.pathname, src: record7.source, ms: Math.round(performance.now() - started) }); return assetResponse(request, record7); } catch (error) { if (request.signal?.aborted) throw error; const update = error?.name === "AssetClientUpdateRequiredError", status = update ? 426 : error?.status === 404 ? 404 : 502; if (update) this.#updateRequired(error); const headers = new Headers({ "content-type": "text/plain; charset=utf-8" }); headers.set("x-dofus-asset-error", message2(error).replace(/[^\x20-\x7e]/gu, " ").slice(0, 1e3)); if (update) for (const [header, value] of [["client-variant", error.variant], ["client-version", error.currentVersion], ["minimum-version", error.minimumVersion]]) headers.set(`x-dofus-asset-${header}`, value); this.logger.warn("Asset request failed", { url: request.url, status, message: message2(error) }); return new Response(request.method === "HEAD" ? null : message2(error), { status, headers }); } } async #localizedRequest(request) { const language = this.options.option?.("interfaceLanguage") ?? "fr"; if (!["en", "es"].includes(language)) return null; const url = new URL(request.url), parts = url.pathname.split("/").filter(Boolean); if (parts[1] !== "data" || parts[2] === "i18n") return null; const table2 = parts.slice(2).join("/"); if (!/^(?:grist\/)?[A-Za-z0-9_]+\.bin$/u.test(table2)) return null; const prefix = `${url.protocol}//${url.host}/${parts[0]}`; let entry = this.localized.get(prefix); if (!entry || entry.failed && this.clock.now() - entry.at >= 6e4) { entry = { at: this.clock.now(), failed: false }; entry.promise = this.handleProtocol({ url: `${prefix}/khaos/data/i18n.json`, method: "GET", headers: new Headers(), signal: request.signal }).then((response) => response.ok ? response.json() : Promise.reject(new Error("Localization list unavailable"))).catch(() => { entry.failed = true; return {}; }); this.localized.set(prefix, entry); } const index = await entry.promise; return Array.isArray(index[language]) && index[language].includes(table2) ? { url: `${prefix}/data/i18n/${language}/${table2}`, method: request.method, headers: request.headers, signal: request.signal } : null; } #updateRequired(error) { void Promise.resolve().then(() => this.options.onUpdateRequired?.(error)).catch((failure3) => this.logger.warn("Asset update check failed", { message: message2(failure3) })); } installer(profile, key = this.activeKey) { profileName(profile); const cache2 = this.cacheForKey(key); if (!cache2) throw new Error(`Unknown asset source key: ${key}`); const identity = sessionKey(key, profile); if (!this.installers.has(identity)) { const factory = this.dependencies.installerFactory ?? ((...args) => new AssetPredownloader(...args)); const installer = factory(cache2, key, profile, { logger: this.logger }); installer.onStateChanged((state) => { optionalCall(this.options.broadcast, "desktop:predownload-state", state); if (state.sourceKey === this.activeKey && state.installProfile === this.config.installProfile) optionalCall(this.options.onProgress, state); }); this.installers.set(identity, installer); } return this.installers.get(identity); } prepareRequired(url, profile) { return this.#prepare(url, profile, "required"); } prepareBackground(url, profile) { return this.#prepare(url, profile, "background"); } #prepare(url, profile, role) { if (this.closed || this.clearing) return Promise.reject(new Error("Asset preparations are stopped")); return this.#prepareStage(this.registerSource(url), profileName(profile), role); } /** * One install per source and profile, shared by every caller (early download, loading screen, server hub): one * preparation per stage, which later callers join; one stage runs at a time, the background stage waiting for a * required one rather than racing it (each stopped the other's run before: transfers aborted, files checked again). * A required call while the background stage runs answers at once when the required stage already ended complete * this session. Only Pause (Options), clearing the cache and quitting stop a preparation; a caller that goes away * (a renderer AbortSignal, an unmounted hub) only stops waiting for it. */ #prepareStage(key, profile, role) { if (this.closed || this.clearing) return Promise.reject(new Error("Asset preparations are stopped")); const installKey = sessionKey(key, profileName(profile)), identity = `${installKey}/${role}`, requiredIdentity = `${installKey}/required`; const installer = this.installer(profile, key); if (this.preparations.has(identity)) { this.logger.info?.("Install stage joined", { sourceKey: key, stage: role }); return this.preparations.get(identity); } if (role === "required" && this.preparations.has(`${installKey}/background`)) { const done = installer.stageState?.("required"); if (done) { this.logger.info?.("Install stage already complete", { sourceKey: key, stage: role }); return Promise.resolve(done); } } const controller = new AbortController(); this.preparationControllers.set(identity, controller); const startedAt = this.clock.now(); this.logger.info?.("Install stage started", { sourceKey: key, stage: role }); const task = (async () => { for (let attempt = 0; !controller.signal.aborted; ) { if (role === "background") { let waiting; while (!controller.signal.aborted && (waiting = this.preparations.get(requiredIdentity))) await waiting.catch(() => { }); } if (controller.signal.aborted) break; try { await installer.startPlanCategories(role, "max", { refreshManifest: true }); } catch (error) { if (role !== "required" || ["AssetClientUpdateRequiredError", "AbortError"].includes(error?.name) || error instanceof CategorySelectionError) throw error; return this.#failedStage(installer, key, role, error, startedAt); } const state = installer.getState(), ids = role === "required" ? state.requiredCategoryIds : state.backgroundCategoryIds; const complete = state.phase === "done" && !state.failedFiles && !state.error && ids.every((id) => state.categories.some((entry) => entry.id === id && entry.filesDone === entry.assetCount)); if (!complete && role === "background" && this.preparations.has(requiredIdentity)) continue; if (complete || state.phase === "paused" || role === "background" && attempt >= 2) { this.logger.info?.("Install stage finished", { sourceKey: key, stage: role, complete, phase: state.phase, attempts: attempt + 1, ms: this.clock.now() - startedAt }); if (complete && role === "background" && this.root) await this.location.markComplete?.(this.root); this.schedulePrune(); return state; } attempt++; await new Promise((resolve) => { const done = () => { this.clock.clear(timer); controller.signal.removeEventListener("abort", done); resolve(); }; const timer = this.clock.timeout(done, Math.min(1e4, 250 * 2 ** Math.min(attempt - 1, 5))); timer.unref?.(); controller.signal.addEventListener("abort", done, { once: true }); if (controller.signal.aborted) done(); }); } return installer.getState(); })(); this.preparations.set(identity, task); void task.catch((error) => { if (error?.name === "AssetClientUpdateRequiredError") this.#updateRequired(error); }).finally(() => { if (this.preparations.get(identity) === task) { this.preparations.delete(identity); this.preparationControllers.delete(identity); } }); return task; } /** * Khaos (asset-verify 2026-10-15): a failed required stage now returns its error state instead of rejecting. The * loading screen and the early download show its short French cause and try the stage again a few seconds later. * Before, a rejection left the player on a dead loading screen showing the raw exception. The cause and its * evidence go to the main log, with one line in the stability log (an F11 report carries both). */ #failedStage(installer, key, role, error, startedAt) { const state = installer.getState(); const cause = { sourceKey: key, stage: role, error: error?.name ?? typeof error, code: error?.code ?? null, failureKind: error?.failureKind ?? null, message: message2(error).slice(0, 500), evidence: error?.evidence ?? null, ms: this.clock.now() - startedAt }; this.logger.warn("Install stage failed; the loading screen tries it again", cause); const evidence = cause.evidence ? ` ${JSON.stringify(cause.evidence).slice(0, 1500)}` : ""; optionalCall(globalThis.__khaosStabilityLine, `ASSET STAGE FAILED ${role} kind=${cause.failureKind ?? "-"} ${cause.error}: ${cause.message.replace(/\s+/gu, " ").slice(0, 300)}${evidence}`); return { ...state, phase: "error", error: state.error ?? installationError(error) }; } prefetch(url, profile, speed) { speedName(speed); const key = this.registerSource(url); this.installer(profile, key); if (!this.closed && !this.clearing) void this.prefetcher.start(sessionKey(key, profile)); return key; } stopPrefetch(url, profile) { const key = this.registerSource(url); this.installer(profile, key); this.prefetcher.stop(sessionKey(key, profile)); } startBackgroundUpdate(url, profile, speed) { speedName(speed); const key = this.registerSource(url), identity = sessionKey(key, profileName(profile)); const previous = this.background.get(identity); if (previous) { previous.cancelled = true; this.clock.clear(previous.timer); } const lease = { cancelled: false, timer: null }; this.background.set(identity, lease); const run = async (refresh) => { if (this.closed || lease.cancelled) return; const installer = this.installer(profile, key), state = installer.getState(); const preparing = this.preparations.has(`${identity}/required`) || this.preparations.has(`${identity}/background`); if (!this.clearing && !preparing && !["scanning", "downloading"].includes(state.phase)) { try { await installer.startPlanCategories("complete", speed, { refreshManifest: refresh }); this.schedulePrune(); } catch (error) { this.logger.warn("Background asset update failed", { message: message2(error) }); } } if (this.closed || lease.cancelled) return; lease.timer = this.clock.timeout(() => void run(true), khaosBackgroundRecheckMs(installer.getState(), 3e5)); lease.timer.unref?.(); }; void run(false); } schedulePrune() { this.clock.clear(this.pruneTimer); if (this.closed) return; this.pruneTimer = this.clock.timeout(() => { this.pruneTimer = null; if (khaosShouldPrune(this.downloadedBytes, this.clock.now(), this.lastPrune)) void this.prune().catch((error) => this.logger.warn("Post-install prune failed", { message: message2(error) })); }, 3e4); this.pruneTimer.unref?.(); } prune() { if (this.clearing || this.closed) return Promise.resolve("skipped-clearing"); if (!this.prunePromise) { const task = pruneDesktopAssets({ registry: this.registry, caches: this.caches, cacheForSource: (key, source) => { const base = assetBase(source.remoteBaseUrl, this.config.baseUrl); if (sourceIdentity(base) !== key) throw new Error("Stored asset source key does not match its URL"); return this.#makeCache(base, key); }, blobStore: this.blobs, packStore: this.packs, root: this.root, now: this.clock.now(), onFailure: (error) => this.logger.warn("Asset prune skipped", { message: message2(error) }), onPruned: khaosAssetTraceOn ? (totals) => khaosAssetTrace({ k: "prune-stores", blob: totals.blob, pack: totals.pack }) : null }); this.prunePromise = task; if (khaosAssetTraceOn) { const started = performance.now(), ended = (state) => khaosAssetTrace({ k: "prune", state, ms: Math.round(performance.now() - started) }); khaosAssetTrace({ k: "prune", state: "start", open: [...this.caches.keys()] }); void task.then((result) => ended(String(result)), () => ended("failed")); } void task.then((result) => { if (result === "pruned") this.lastPrune = { bytes: this.downloadedBytes, at: this.clock.now() }; }).finally(() => { if (this.prunePromise === task) this.prunePromise = null; }).catch(() => { }); } return this.prunePromise; } async clearCache() { if (this.clearing) throw new Error("Asset cache is already being cleared"); this.clearing = true; for (const controller of this.preparationControllers.values()) controller.abort(); for (const installer of this.installers.values()) installer.pause(); for (const key of this.prefetcher.running.keys()) this.prefetcher.stop(key); let invalidated = false; try { await this.options.beforeClear?.(); await this.prunePromise?.catch(() => { }); await this.completion.beginInvalidation(); invalidated = true; this.coordinator.abortAll(new Error("Asset cache is being cleared")); await this.coordinator.drain(); await this.packs.clear(); for (const cache2 of this.caches.values()) await cache2.clearManifests(); await this.blobs.clear(); for (const installer of this.installers.values()) installer.reset(); this.localized.clear(); } finally { try { if (invalidated) await this.completion.finishInvalidation(); } finally { this.clearing = false; } } } async storageLocation() { if (!this.root) throw new Error("Asset storage is not configured"); return { root: this.root, freeBytes: await (this.dependencies.freeBytes ?? freeStorageBytes)(this.root) }; } async changeStorageLocation(sender) { if (this.changingLocation) throw new Error("Un changement d\u2019emplacement est d\xE9j\xE0 en cours."); this.changingLocation = true; try { const result = await this.location.schedule(this.root, this.electron.BrowserWindow?.fromWebContents(sender)); if (result.status === "scheduled") this.clock.timeout(() => { this.electron.app.relaunch(); this.electron.app.quit(); }, 250); return result; } finally { this.changingLocation = false; } } /** * The sign-in screen's "Change install folder" and its low-space notice ({ reason: "space", neededBytes }): the * folder step over the game window; Khaos restarts on a new folder (GameDataLocation.changeBeforeLogin). */ async chooseStorageLocation(sender, request = {}) { if (this.changingLocation) throw new Error("Un changement d\u2019emplacement est d\xE9j\xE0 en cours."); if (!this.root) throw new Error("Asset storage is not configured"); this.changingLocation = true; try { const reason = request?.reason === "space" ? "space" : null; const neededBytes = Number.isSafeInteger(request?.neededBytes) && request.neededBytes >= 0 ? request.neededBytes : null; const window = this.electron.BrowserWindow?.fromWebContents?.(sender) ?? null; const result = this.location.changeBeforeLogin ? await this.location.changeBeforeLogin(this.root, { window, reason, neededBytes }) : await this.location.schedule(this.root, window); if (result.status === "scheduled" || result.status === "restart") this.clock.timeout(() => { this.electron.app.relaunch(); this.electron.app.quit(); }, 250); return result; } finally { this.changingLocation = false; } } async diagnostics(rendererId) { const location = await this.storageLocation(), predownloads = [...this.installers.values()].map((installer) => installer.getState()); const stalls = Object.fromEntries([...this.caches].map(([key, cache2]) => [key, cache2.stallCount ?? 0])); let transfers = null; try { transfers = this.coordinator.getMetrics?.() ?? null; } catch { } return { cacheRoot: location.root, cacheFreeBytes: location.freeBytes, sourceKey: this.rendererSources.get(rendererId) ?? null, predownloads, transportModes: Object.fromEntries(predownloads.map((state) => [state.sourceKey, this.cacheForKey(state.sourceKey)?.getTransportMode()])), stalls, transfers, mainProcessLogs: this.options.recentLogs?.({ count: 600, argMaxChars: 500 }) ?? [] }; } registerIpc(ipc = this.electron.ipcMain) { const routes = { "desktop:assets:clear-cache": () => this.clearCache(), "desktop:assets:storage-location": () => this.storageLocation(), "desktop:assets:change-storage-location": (event) => this.changeStorageLocation(event.sender), "desktop:assets:choose-storage-location": (event, request) => this.chooseStorageLocation(event.sender, request), "desktop:assets:register-source": (_event, url) => this.registerSource(url), "desktop:assets:set-source": (event, url, profile) => this.selectSource(event.sender.id, url, profile), "desktop:assets:prepare-required": (_event, url, profile) => this.prepareRequired(url, profile), "desktop:assets:prepare-background": (_event, url, profile) => this.prepareBackground(url, profile), "desktop:assets:prefetch": (_event, url, profile, speed) => this.prefetch(url, profile, speed), "desktop:assets:stop-prefetch": (_event, url, profile) => this.stopPrefetch(url, profile), "desktop:assets:diagnostics": (event) => this.diagnostics(event.sender.id), "desktop:assets:start-background-update": (_event, url, profile, speed) => { this.startBackgroundUpdate(url, profile, speed); }, "desktop:predownload:status": (_event, profile, key) => this.installer(profile, key).getState(), "desktop:predownload:scan": (_event, profile, key) => { void this.installer(profile, key).scan().catch((error) => this.logger.warn("Asset scan failed", { message: message2(error) })); }, "desktop:predownload:start": (_event, profile, ids, speed, key) => { void this.installer(profile, key).start(categories(ids), speedName(speed, true)).then(() => this.schedulePrune()).catch((error) => this.logger.warn("Asset installation failed", { message: message2(error) })); }, "desktop:predownload:pause": (_event, profile, key) => { this.installer(profile, key).pause(); } }; for (const [channel2, operation] of Object.entries(routes)) ipc.handle(channel2, (event, ...args) => operation(event, ...args)); return Object.keys(routes); } async close() { this.closed = true; this.clock.clear(this.pruneTimer); for (const controller of this.preparationControllers.values()) controller.abort(); for (const lease of this.background.values()) { lease.cancelled = true; this.clock.clear(lease.timer); } for (const key of this.prefetcher.running.keys()) this.prefetcher.stop(key); for (const installer of this.installers.values()) installer.pause(); for (const cache2 of this.caches.values()) cache2.invalidateManifest(); await this.coordinator.close(); await this.metadata.close?.(); await this.pruneMetadata.close?.(); await this.packs?.close?.(); await Promise.allSettled([...this.preparations.values()]); await this.registry?.entries().catch(() => { }); } }; // src/renderer/khaos/binary/realmBytes.js var typedArrayName = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get; var arrayBufferLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get; function isUint8Array(value) { return typedArrayName.call(value) === "Uint8Array"; } // src/electron/khaos/desktopWindows.js var import_node_path14 = __toESM(require("node:path"), 1); var import_node_fs4 = __toESM(require("node:fs"), 1); // src/electron/khaos/surfaceManager.js var SurfaceManager = class { constructor(electron2, options) { this.host = electron2; this.options = options; this.surfaces = /* @__PURE__ */ new Map(); this.opening = /* @__PURE__ */ new Map(); this.focusListeners = /* @__PURE__ */ new Set(); this.accelerators = /* @__PURE__ */ new Set(); this.settings = options.settings; this.dock = null; this.started = false; this.disposed = false; } start(factory) { if (this.disposed) throw new Error("Game window controller is closed"); this.factory = factory; if (this.started) return; this.started = true; const { app, ipcMain } = this.host; const actions = { "open-window": (_event, account) => this.openAccount(account), "open-login-window": () => this.open(null), "report-identity": (event, identity) => this.identify(event.sender.id, identity), "notify-turn-start": (event) => this.turn(event.sender.id, true), "notify-turn-end": (event) => this.turn(event.sender.id, false), "close-surface": (_event, id) => this.close(id), "reorder-surfaces": (_event, ids) => this.reorder(ids), "focus-surface": (_event, id) => this.focus(id), list: () => this.list(), "own-surface-id": (event) => this.surfaces.get(event.sender.id)?.id ?? null }; for (const [name, action] of Object.entries(actions)) { ipcMain.handle(`desktop:multi:${name}`, async (...args) => action(...args)); } this.onAppFocus = () => setImmediate(() => { if (!this.disposed) this.shortcuts(); }); app.on("browser-window-focus", this.onAppFocus); app.on("browser-window-blur", this.onAppFocus); app.once("will-quit", () => this.dispose()); } subscribeFocused(callback) { this.focusListeners.add(callback); return () => this.focusListeners.delete(callback); } configure(settings) { this.settings = { ...settings, autoSwitchOnTurn: false }; this.shortcuts(); this.syncDock(); this.publish(); } findAccount(account) { return Array.from(this.surfaces.values()).find((surface) => surface.accountId === account); } openAccount(account) { const present = this.findAccount(account); if (present) { this.focus(present.id); return Promise.resolve(); } if (this.opening.has(account)) return this.opening.get(account); const work = this.open(account); this.opening.set(account, work); work.finally(() => { if (this.opening.get(account) === work) this.opening.delete(account); }).catch(() => { }); return work; } async open(account) { if (!this.factory || this.disposed) throw new Error("Game window controller is unavailable"); const window = await this.factory(); let view; let contents; let surface; try { if (this.disposed || window.isDestroyed()) throw new Error("Game window closed during startup"); view = new this.host.WebContentsView({ webPreferences: this.options.webPreferences() }); contents = view.webContents; this.options.devTools.attach(contents); surface = { id: contents.id, contents, view, window, accountId: account, characterName: null, breed: null, level: null, hasTurn: false }; this.surfaces.set(surface.id, surface); const resize = () => { if (window.isDestroyed() || contents.isDestroyed()) return; const [width, height] = window.getContentSize(); view.setBounds({ x: 0, y: 0, width, height }); }; const release = () => this.release(surface); contents.once("destroyed", () => { const closeCarrier = !surface.closing; surface.closing = true; release(); if (closeCarrier) setImmediate(() => { if (!window.isDestroyed()) window.close(); }); }); window.once("closed", () => { surface.closing = true; release(); setImmediate(() => { if (!contents.isDestroyed()) contents.close(); }); }); window.on("resize", resize); window.on("focus", () => { if (contents.isDestroyed()) return; window.flashFrame(false); contents.focus(); for (const listener of this.focusListeners) { try { listener(surface.id); } catch (error) { this.report(error); } } this.publish(); }); window.on("blur", () => this.publish()); window.contentView.addChildView(view); resize(); this.changed(); await this.options.load(contents, account); } catch (error) { if (surface) this.release(surface); if (contents && !contents.isDestroyed()) contents.close(); if (!window.isDestroyed()) window.close(); throw error; } } release(surface) { if (this.surfaces.get(surface.id) !== surface) return; this.surfaces.delete(surface.id); setImmediate(() => { if (!surface.window.isDestroyed() && !surface.contents.isDestroyed()) { surface.window.contentView.removeChildView(surface.view); } this.options.devTools.revoke(surface.contents); this.changed(); }); } changed() { this.shortcuts(); this.syncDock(); this.publish(); } report(error) { this.options.onError?.(error); } windowFor(contents) { const window = this.surfaces.get(contents.id)?.window; return window && !window.isDestroyed() ? window : null; } focus(id) { const surface = this.surfaces.get(id); if (!surface || surface.window.isDestroyed() || surface.contents.isDestroyed()) return; const { window, contents } = surface; if (window.isMinimized()) window.restore(); window.show(); window.focus(); contents.focus(); } close(id) { const surface = this.surfaces.get(id); if (!surface) return; if (!surface.window.isDestroyed()) { surface.closing = true; surface.window.close(); } else { this.release(surface); if (!surface.contents.isDestroyed()) surface.contents.close(); } } reorder(ids) { if (!Array.isArray(ids)) throw new Error("Surface order must be an array"); const ordered2 = new Set(ids.filter((id) => this.surfaces.has(id))); for (const id of this.surfaces.keys()) ordered2.add(id); const values = Array.from(ordered2, (id) => this.surfaces.get(id)); this.surfaces.clear(); for (const value of values) this.surfaces.set(value.id, value); this.shortcuts(); this.publish(); } identify(id, identity) { const surface = this.surfaces.get(id); if (!surface) return; if (!identity || typeof identity !== "object") throw new Error("Invalid game identity"); const other = this.findAccount(identity.accountId); if (other && other !== surface) { this.focus(other.id); this.close(id); return; } for (const key of ["accountId", "characterName", "breed", "level"]) surface[key] = identity[key]; if (!surface.window.isDestroyed()) surface.window.setTitle(`Khaos - ${identity.characterName}`); this.publish(); } turn(id, active) { const surface = this.surfaces.get(id); if (surface) { surface.hasTurn = active; this.publish(); } } describe(surface, slot, diagnostics) { const { window, view, contents } = surface; const alive = !contents.isDestroyed(); const carrier2 = !window.isDestroyed(); const visible = alive && view.getVisible(); const result = { surfaceId: surface.id, accountId: surface.accountId, characterName: surface.characterName, breed: surface.breed, level: surface.level, hasTurn: surface.hasTurn, focused: carrier2 && window.isFocused(), container: "float", active: visible, shortcut: this.settings.slotShortcuts[slot] ?? null, frameScheduling: { viewVisible: visible, carrierWindowFocused: carrier2 && window.isFocused(), carrierWindowVisible: carrier2 && window.isVisible(), carrierWindowMinimized: carrier2 && window.isMinimized(), webContentsFocused: alive && contents.isFocused(), backgroundThrottling: alive && contents.getBackgroundThrottling(), devToolsOpened: alive && contents.isDevToolsOpened() } }; if (diagnostics) Object.assign(result, { webContentsId: surface.id, osProcessId: alive ? contents.getOSProcessId() : 0, chromiumProcessId: alive ? contents.getProcessId() : 0, url: alive ? contents.getURL() : "", title: alive ? contents.getTitle() : "" }); return result; } list(diagnostics = false) { return Array.from(this.surfaces.values(), (surface, slot) => this.describe(surface, slot, diagnostics)); } publish() { const state = this.list(); for (const contents of this.host.webContents.getAllWebContents()) { if (contents.isDestroyed()) continue; try { contents.send("desktop:multi-state", state); } catch (error) { this.report(error); } } } shortcuts() { for (const accelerator of this.accelerators) this.host.globalShortcut.unregister(accelerator); this.accelerators.clear(); if (this.disposed || this.surfaces.size < 2) return; const focused = this.host.BrowserWindow.getFocusedWindow(); const inGame = Array.from(this.surfaces.values()).some((surface) => surface.window === focused); if (!this.settings.globalScope && !inGame) return; this.settings.slotShortcuts.forEach((accelerator, slot) => { try { const registered = this.host.globalShortcut.register(accelerator, () => { const surface = Array.from(this.surfaces.values())[slot]; if (surface) this.focus(surface.id); }); if (registered) this.accelerators.add(accelerator); } catch (error) { this.report(error); } }); } syncDock() { if (this.disposed || !this.settings.showDock || this.surfaces.size < 2) { const old = this.dock; this.dock = null; if (old && !old.isDestroyed()) old.close(); return; } if (this.dock) return; const area = this.host.screen.getPrimaryDisplay().workArea; const width = 460; const window = new this.host.BrowserWindow({ width, height: 88, x: area.x + Math.round((area.width - width) / 2), y: area.y + 8, icon: this.options.icon(), frame: false, resizable: false, alwaysOnTop: true, skipTaskbar: true, show: false, backgroundColor: "#101014", webPreferences: this.options.webPreferences() }); this.dock = window; window.once("closed", () => { if (this.dock === window) this.dock = null; }); Promise.resolve().then(() => { if (!window.isDestroyed()) return this.options.load(window, "/dock"); }).catch((error) => { if (this.dock === window) this.dock = null; if (!window.isDestroyed()) window.close(); this.report(error); }); } dispose() { if (this.disposed) return; this.disposed = true; if (this.onAppFocus) { this.host.app.off("browser-window-focus", this.onAppFocus); this.host.app.off("browser-window-blur", this.onAppFocus); } this.shortcuts(); this.syncDock(); this.focusListeners.clear(); } }; // src/electron/khaos/devToolsPolicy.js var DevToolsPolicy = class { permitted = /* @__PURE__ */ new WeakSet(); allow(contents, value) { if (contents.isDestroyed()) throw new Error("Cannot authorize a closed game page"); if (value === true) this.permitted.add(contents); else this.revoke(contents); } revoke(contents) { this.permitted.delete(contents); this.enforce(contents); } enforce(contents) { if (contents.isDestroyed()) return false; if (this.permitted.has(contents)) return true; if (contents.isDevToolsOpened()) contents.closeDevTools(); return false; } open(contents) { if (!this.enforce(contents)) throw new Error("Administrator access is required for DevTools"); contents.openDevTools({ activate: true, mode: "detach" }); } toggle(contents) { if (!this.enforce(contents)) return false; if (contents.isDevToolsOpened()) contents.closeDevTools(); else this.open(contents); return true; } attach(contents) { contents.on("devtools-opened", () => this.enforce(contents)); contents.on("did-start-navigation", (details, _url, _inPlace, mainFrame) => { if (details?.isMainFrame ?? mainFrame) this.revoke(contents); }); contents.on("render-process-gone", () => this.revoke(contents)); contents.on("destroyed", () => this.permitted.delete(contents)); contents.on("before-input-event", (event, input) => { if (input.type !== "keyDown") return; const key = input.key.toLowerCase(); const command = input.control || input.meta; const inspect2 = key === "f12" || "cij".includes(key) && key.length === 1 && (input.shift && command || input.meta && input.alt); if (inspect2) { event.preventDefault(); this.toggle(contents); } else if (command && key === "r") { event.preventDefault(); if (input.shift) contents.reloadIgnoringCache(); else contents.reload(); } }); } }; // src/electron/khaos/systemNotices.js var NOTICE_TAG_MS = 10 * 60 * 1e3; var NOTICE_KEEP_MS = 5 * 60 * 1e3; function systemNoticeRequest(input) { if (!input || typeof input !== "object" || Array.isArray(input)) throw new TypeError("Invalid system notice request"); const output = {}; for (const [name, maximum] of [["title", 120], ["body", 400]]) { const value = input[name]; if (typeof value !== "string" || !value.trim() || value.length > maximum) throw new TypeError(`Invalid system notice ${name}`); output[name] = value; } if (typeof input.tag !== "string" || !/^[\w:.-]{1,64}$/u.test(input.tag)) throw new TypeError("Invalid system notice tag"); output.tag = input.tag; if (input.whenFocused !== void 0 && typeof input.whenFocused !== "boolean") throw new TypeError("Invalid system notice focus option"); output.whenFocused = input.whenFocused === true; return output; } var SystemNotices = class { /** * @param electron the Electron module (Notification, app) * @param options { icon(): string, focus(window, surfaceId), platform, now, setTimeout, clearTimeout, logger } */ constructor(electron2, options = {}) { this.electron = electron2; this.options = options; this.platform = options.platform ?? process.platform; this.now = options.now ?? Date.now; this.schedule = options.setTimeout ?? setTimeout; this.cancel = options.clearTimeout ?? clearTimeout; this.tags = /* @__PURE__ */ new Map(); this.live = /* @__PURE__ */ new Map(); this.closed = false; } /** Whether `tag` was shown less than NOTICE_TAG_MS ago (older tags are forgotten here). */ seen(tag, now) { for (const [known, at] of this.tags) if (now - at >= NOTICE_TAG_MS) this.tags.delete(known); return this.tags.has(tag); } /** * Shows `input` for the game page `surfaceId` of carrier `window`: "shown"; "seen" when its tag was already shown; * "focused" when the window is focused and shown and the request did not ask for that case (nothing is recorded: the * page asks again later); "closed" when the service or window is gone. The taskbar flashes (the Dock bounces) only * while the window is not focused; SurfaceManager stops the flash on focus. */ show(window, surfaceId, input) { const request = systemNoticeRequest(input); if (this.closed || !window || window.isDestroyed()) return "closed"; const focused = window.isFocused() && !window.isMinimized?.() && window.isVisible?.() !== false; if (focused && !request.whenFocused) return "focused"; const now = this.now(); if (this.seen(request.tag, now)) return "seen"; this.tags.set(request.tag, now); const { Notification, app } = this.electron; if (Notification && (typeof Notification.isSupported !== "function" || Notification.isSupported())) { try { const icon = this.options.icon?.(); const notice = new Notification({ title: request.title, body: request.body, ...icon ? { icon } : {} }); const forget = () => { const timer2 = this.live.get(notice); if (timer2 === void 0) return; this.cancel(timer2); this.live.delete(notice); }; notice.on("click", () => { forget(); try { notice.close(); } catch { } if (!this.closed && !window.isDestroyed()) this.options.focus?.(window, surfaceId); }); notice.on("show", () => this.options.logger?.info?.("System notice shown", request.tag)); notice.on("failed", (_event, error) => { forget(); this.options.logger?.warn?.("System notice failed", request.tag, error); }); const timer = this.schedule(() => this.live.delete(notice), NOTICE_KEEP_MS); timer?.unref?.(); this.live.set(notice, timer); notice.show(); } catch (error) { this.options.logger?.warn?.("System notice could not be shown", error); } } if (!focused) { window.flashFrame(true); if (this.platform === "darwin") app?.dock?.bounce?.("informational"); } return "shown"; } close() { this.closed = true; for (const timer of this.live.values()) this.cancel(timer); this.live.clear(); this.tags.clear(); } }; // src/electron/khaos/desktopWindows.js var GRAB_WIDTH = 160; var GRAB_HEIGHT = 16; var TOP_STRIP = 32; var overlap = (start, size, areaStart, areaSize) => Math.min(start + size, areaStart + areaSize) - Math.max(start, areaStart); function onScreenWindowBounds(dimensions, displays, primary = displays[0]) { const areas = displays.map((display) => display?.workArea).filter((area2) => area2 && area2.width > 0 && area2.height > 0); if (!areas.length) return { ...dimensions }; const result = { ...dimensions }; const placed = Number.isFinite(result.x) && Number.isFinite(result.y); const width = Number.isFinite(result.width) ? result.width : 0; const host = placed ? areas.find((area2) => overlap(result.x, width, area2.x, area2.width) >= Math.min(GRAB_WIDTH, width) && overlap(result.y, TOP_STRIP, area2.y, area2.height) >= GRAB_HEIGHT) : void 0; if (placed && !host) { delete result.x; delete result.y; } const area = host ?? primary?.workArea ?? areas[0]; if (Number.isFinite(result.width)) result.width = Math.min(result.width, area.width); if (Number.isFinite(result.height)) result.height = Math.min(result.height, area.height); return result; } var DesktopWindows = class { constructor(electron2, { settings, appDirectory, preload, rendererUrl, rendererFile, iconPath, resourcesDirectory = process.resourcesPath, logger = console, setTimeout: schedule = setTimeout, clearTimeout: cancel = clearTimeout }) { Object.assign(this, { electron: electron2, settings, appDirectory, preload, rendererUrl, rendererFile, iconPath, resourcesDirectory, logger, schedule, cancel }); this.policy = new DevToolsPolicy(); this.carriers = /* @__PURE__ */ new Set(); this.ipcChannels = /* @__PURE__ */ new Set(); this.persistence = /* @__PURE__ */ new Map(); this.starting = null; this.started = false; this.closed = false; this.surfaces = new SurfaceManager(electron2, { settings: { slotShortcuts: [], showDock: false }, devTools: this.policy, webPreferences: () => this.preferences(), icon: () => this.icon(), onError: (error) => logger.error?.("Window operation failed", error), load: (contents, target) => this.load(contents, target) }); this.notices = new SystemNotices(electron2, { icon: () => this.icon(), logger, focus: (window, surfaceId) => this.bringBack(window, surfaceId) }); } bringBack(window, surfaceId) { this.surfaces.focus(surfaceId); if (window.isDestroyed()) return; if (window.isMinimized()) window.restore(); window.show(); window.focus(); } preferences() { return { preload: this.preload, sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false, spellcheck: false }; } icon() { if (this.iconPath) return this.iconPath; const packaged = this.resourcesDirectory ? import_node_path14.default.join(this.resourcesDirectory, "icon.png") : null; if (this.electron.app.isPackaged && packaged && import_node_fs4.default.existsSync(packaged)) return packaged; return import_node_path14.default.join(this.appDirectory, "build", "icons", "icon.png"); } load(contents, target = null) { const route = typeof target === "string" && target.startsWith("/") ? target : target === null ? null : `/?account=${encodeURIComponent(target)}`; const loading = this.rendererFile || this.electron.app.isPackaged ? contents.loadFile(this.rendererFile ?? import_node_path14.default.join(this.appDirectory, "dist", "index.html"), route ? { hash: route } : void 0) : contents.loadURL(route ? `${this.rendererUrl}/#${route}` : this.rendererUrl); return Promise.resolve(loading).catch((error) => { if (error?.code !== "ERR_ABORTED" && error?.errno !== -3) throw error; this.logger.warn?.("Renderer load replaced by a newer navigation", { url: error?.url }); }); } loadAudio(window) { return this.electron.app.isPackaged || this.rendererFile ? window.loadFile(import_node_path14.default.join(this.appDirectory, "dist", "audio.html")) : window.loadURL(`${this.rendererUrl}/audio.html`); } forSender(sender) { return this.surfaces.windowFor(sender) ?? this.electron.BrowserWindow.fromWebContents(sender); } state(window) { return { bounds: window.getBounds(), maximized: window.isMaximized(), fullscreen: window.isFullScreen() }; } async carrier() { const saved = await this.settings.load(); if (this.closed) throw new Error("Desktop window host is closed"); let dimensions = { width: saved.windowWidth, height: saved.windowHeight, minWidth: 1024, minHeight: 600 }; if (saved.windowX !== null && saved.windowY !== null) Object.assign(dimensions, { x: saved.windowX, y: saved.windowY }); try { const screen = this.electron.screen; if (screen?.getAllDisplays) dimensions = onScreenWindowBounds(dimensions, screen.getAllDisplays(), screen.getPrimaryDisplay?.()); } catch (error) { this.logger.warn?.("Display check failed", error); } const window = new this.electron.BrowserWindow({ ...dimensions, title: "Khaos", icon: this.icon(), show: false, autoHideMenuBar: true, backgroundColor: "#0A0A0A", webPreferences: { sandbox: true, nodeIntegration: false, contextIsolation: true } }); this.carriers.add(window); if (saved.isMaximized) window.maximize(); if (saved.isFullscreen) window.setFullScreen(true); const persistence = { timer: null, listeners: /* @__PURE__ */ new Map() }; this.persistence.set(window, persistence); const publish = () => { this.cancel(persistence.timer); persistence.timer = null; if (this.closed || window.isDestroyed()) return; const value = this.state(window), { bounds } = value; void this.settings.mutate((current) => ({ ...current, windowWidth: bounds.width, windowHeight: bounds.height, windowX: bounds.x, windowY: bounds.y, isMaximized: value.maximized, isFullscreen: value.fullscreen })).catch((error) => this.logger.warn?.("Window persistence failed", error)); this.broadcast("desktop:window-state", value); }; for (const event of ["move", "resize"]) persistence.listeners.set(event, () => { this.cancel(persistence.timer); persistence.timer = this.schedule(publish, 250); persistence.timer?.unref?.(); }); for (const event of ["maximize", "unmaximize", "enter-full-screen", "leave-full-screen"]) persistence.listeners.set(event, publish); for (const [event, listener] of persistence.listeners) window.on(event, listener); window.once("closed", () => { this.releasePersistence(window); this.carriers.delete(window); }); return window; } broadcast(channel2, value) { for (const contents of this.electron.webContents.getAllWebContents()) if (!contents.isDestroyed()) { try { contents.send(channel2, value); } catch { } } } start() { if (this.closed) return Promise.reject(new Error("Desktop window host is closed")); if (this.started) return Promise.resolve(); if (!this.starting) { this.starting = this.install(); this.starting.finally(() => { this.starting = null; }).catch(() => { }); } return this.starting; } async install() { const saved = await this.settings.load(); if (this.closed) throw new Error("Desktop window host is closed"); this.surfaces.configure(saved.multiAccount); this.surfaces.start(() => this.carrier()); this.settings.installIpc(this.electron.ipcMain, { onMultiAccount: (options) => this.surfaces.configure(options) }); const live = (event) => { const window = this.forSender(event.sender); if (!window || window.isDestroyed()) throw new Error("Game window is unavailable"); return window; }; const admin = (event) => { if (!event.senderFrame || event.senderFrame !== event.sender.mainFrame || !this.surfaces.windowFor(event.sender)) throw new Error("Administrator action requires a main game frame"); }; const handlers = { "signal-first-paint": (event) => { const window = live(event); if (!window.isVisible()) window.show(); }, "flash-frame": (event) => { const window = live(event); if (!window.isFocused()) window.flashFrame(true); }, focus: (event) => this.bringBack(live(event), event.sender.id), "notify-system": (event, request) => this.notices.show(live(event), event.sender.id, request), "get-state": (event) => this.state(live(event)), "set-fullscreen": (event, value) => { const window = live(event); if (value !== void 0 && value !== null && typeof value !== "boolean") throw new Error("Fullscreen requires a boolean"); window.setFullScreen(value ?? !window.isFullScreen()); return window.isFullScreen(); }, "open-devtools": (event) => { admin(event); this.policy.open(event.sender); }, "set-admin-devtools-access": (event, value) => { admin(event); if (typeof value !== "boolean") throw new Error("Administrator access requires a boolean"); this.policy.allow(event.sender, value); }, "set-icon": (event, value) => { if (value !== null && (!isUint8Array(value) || value.byteLength > 1048576)) throw new Error("Invalid window icon"); const window = live(event); const image = value === null ? this.electron.nativeImage.createFromPath(this.icon()) : this.electron.nativeImage.createFromBuffer(Buffer.from(value)); if (!image.isEmpty()) window.setIcon(image); }, "capture-screenshot": async (event) => { if (event.sender.isDestroyed()) throw new Error("Screenshot sender is destroyed"); const image = await event.sender.capturePage(void 0, { stayHidden: true }); if (image.isEmpty()) throw new Error("Empty screenshot"); const selected = image.getSize().width > 1280 ? image.resize({ width: 1280, quality: "good" }) : image; return `data:image/jpeg;base64,${selected.toJPEG(60).toString("base64")}`; } }; try { for (const [name, callback] of Object.entries(handlers)) { const channel2 = `desktop:window:${name}`; this.electron.ipcMain.handle(channel2, callback); this.ipcChannels.add(channel2); } this.started = true; } catch (error) { for (const channel2 of this.ipcChannels) this.electron.ipcMain.removeHandler(channel2); this.ipcChannels.clear(); throw error; } } open(account = null) { return this.surfaces.open(account); } releasePersistence(window) { const state = this.persistence.get(window); if (!state) return; this.cancel(state.timer); for (const [event, listener] of state.listeners) window.off(event, listener); this.persistence.delete(window); } close() { if (this.closed) return; this.closed = true; for (const channel2 of this.ipcChannels) this.electron.ipcMain.removeHandler(channel2); this.ipcChannels.clear(); for (const window of this.carriers) { this.releasePersistence(window); if (!window.isDestroyed()) window.close(); } this.carriers.clear(); this.surfaces.dispose(); this.notices.close(); } }; // src/electron/khaos/authSession.js var import_promises11 = __toESM(require("node:fs/promises"), 1); var import_node_path16 = __toESM(require("node:path"), 1); var import_node_crypto12 = require("node:crypto"); // src/electron/khaos/savedAccounts.js var import_node_fs5 = __toESM(require("node:fs"), 1); var import_node_path15 = __toESM(require("node:path"), 1); var SAVED_ACCOUNTS_FILE = "khaos-accounts.json"; var MAX_SAVED_ACCOUNTS = 20; var MAX_LABEL_LENGTH = 32; var EMAIL_DOMAIN = "@khaos.local"; function normalizeLogin(raw) { if (typeof raw !== "string") return null; let login = raw.trim(); if (login.toLowerCase().endsWith(EMAIL_DOMAIN)) login = login.slice(0, -EMAIL_DOMAIN.length); return /^[^@\s]{1,64}$/.test(login) ? login : null; } function subjectOf(accessToken) { if (typeof accessToken !== "string") return null; try { const payload = JSON.parse(Buffer.from(accessToken.split(".")[1] ?? "", "base64url").toString("utf8")); return typeof payload?.sub === "string" ? payload.sub : null; } catch { return null; } } function loginOfAuthState(state) { if (!state || typeof state !== "object") return null; const fromEmail = normalizeLogin(state.email ?? ""); const sub = subjectOf(state.accessToken); const fromSub = sub?.startsWith("khaos:") ? normalizeLogin(sub.slice(4)) : null; if (fromEmail && (!fromSub || fromSub.toLowerCase() === fromEmail.toLowerCase())) return fromEmail; return fromSub; } var keyOf = (login) => login.toLowerCase(); function cleanLabel(label) { if (typeof label !== "string") return ""; return label.replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, MAX_LABEL_LENGTH); } function createSavedAccounts({ file: file2, safeStorage, fs: fs16 = import_node_fs5.default, now = () => /* @__PURE__ */ new Date() }) { let data = null; const empty = () => ({ version: 1, last: null, accounts: [] }); const load = () => { if (data) return data; data = empty(); let raw; try { raw = JSON.parse(fs16.readFileSync(file2, "utf8")); } catch { return data; } if (raw?.version !== 1 || !Array.isArray(raw.accounts)) return data; for (const a of raw.accounts) { const login = normalizeLogin(a?.login); if (!login || data.accounts.some((b) => keyOf(b.login) === keyOf(login))) continue; data.accounts.push({ login, label: cleanLabel(a.label), remember: a.remember === true, token: a.remember === true && typeof a.token === "string" && a.token.length > 0 ? a.token : null, addedAt: typeof a.addedAt === "string" ? a.addedAt : null, usedAt: typeof a.usedAt === "string" ? a.usedAt : null }); if (data.accounts.length >= MAX_SAVED_ACCOUNTS) break; } const last = typeof raw.last === "string" ? raw.last : null; data.last = last && data.accounts.some((a) => keyOf(a.login) === last) ? last : null; return data; }; const save = () => { const d = load(); fs16.mkdirSync(import_node_path15.default.dirname(file2), { recursive: true }); const tmp = `${file2}.tmp`; fs16.writeFileSync(tmp, JSON.stringify(d, null, 1), "utf8"); fs16.renameSync(tmp, file2); }; const find = (login) => { const l = normalizeLogin(login); return l ? load().accounts.find((a) => keyOf(a.login) === keyOf(l)) ?? null : null; }; const canEncrypt = () => { try { return safeStorage.isEncryptionAvailable() === true; } catch { return false; } }; const encrypt = (text3) => safeStorage.encryptString(text3).toString("base64"); const decrypt = (blob) => { try { return safeStorage.decryptString(Buffer.from(blob, "base64")); } catch { return null; } }; return { /** What the login screen shows: names and flags only (never a token). */ list() { const d = load(); return { last: d.last, encryption: canEncrypt(), accounts: d.accounts.map((a) => ({ login: a.login, label: a.label, remember: a.remember, hasToken: a.token !== null, last: keyOf(a.login) === d.last, usedAt: a.usedAt })) }; }, /** * Records the account behind a desktop auth state that was just stored (sign-in, token refresh). `ephemeral` * (the session ends with the client, "Remember password" unticked): the account is listed without a token. * Returns the account name, or null when the state names no account. */ note(state, ephemeral) { const login = loginOfAuthState(state); if (!login || typeof state.refreshToken !== "string" || state.refreshToken.length === 0) return null; const d = load(); let entry = find(login); if (!entry) { if (d.accounts.length >= MAX_SAVED_ACCOUNTS) { const oldest = [...d.accounts].sort((a, b) => String(a.usedAt).localeCompare(String(b.usedAt)))[0]; d.accounts.splice(d.accounts.indexOf(oldest), 1); } entry = { login, label: "", remember: false, token: null, addedAt: now().toISOString(), usedAt: null }; d.accounts.push(entry); } entry.remember = !ephemeral && canEncrypt(); entry.token = entry.remember ? encrypt(state.refreshToken) : null; entry.usedAt = now().toISOString(); d.last = keyOf(entry.login); save(); return entry.login; }, /** The remembered refresh token of an account, or null (not saved, not remembered, cannot be decrypted). */ tokenOf(login) { const entry = find(login); return entry?.token ? decrypt(entry.token) : null; }, /** True when this state's refresh token is the one remembered for its account (signing out keeps it valid). */ keeps(state) { const entry = find(loginOfAuthState(state) ?? ""); return !!entry?.remember && !!entry.token && decrypt(entry.token) === state.refreshToken; }, /** The remembered token no longer works (expired, password changed): the account asks for its password. */ dropToken(login) { const entry = find(login); if (!entry || entry.token === null) return; entry.token = null; save(); }, rename(login, label) { const entry = find(login); if (!entry) return false; entry.label = cleanLabel(label); save(); return true; }, /** Removes an account; returns its name, or null when it was not saved. */ remove(login) { const entry = find(login); if (!entry) return null; const d = load(); d.accounts.splice(d.accounts.indexOf(entry), 1); if (d.last === keyOf(entry.login)) d.last = null; save(); return entry.login; }, /** "Forget all": the file is deleted. */ clear() { data = empty(); try { fs16.rmSync(file2, { force: true }); fs16.rmSync(`${file2}.tmp`, { force: true }); } catch { save(); } } }; } // src/electron/khaos/authSession.js var AUTH_API_BASE = "https://api.khaos.invalid/api"; var fields2 = ["accessToken", "refreshToken", "email"]; var record6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value); var isAuthState = (value) => record6(value) && fields2.every((key) => Object.hasOwn(value, key) && (value[key] === null || typeof value[key] === "string")); var isTokenResponse = (value) => record6(value) && ["access_token", "refresh_token"].every((key) => typeof value[key] === "string" && value[key].length > 0); var snapshot = (state) => state === null ? null : Object.fromEntries(fields2.map((key) => [key, state[key]])); var denied = (response) => [400, 401, 403].includes(response?.status); var wait = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); function canonicalBase(value) { if (typeof value !== "string") throw new TypeError("Auth API base requires a string"); const url = new URL(value); if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash) throw new Error("Auth API base is not allowed"); url.pathname = url.pathname.replace(/\/+$/u, ""); return url.href.replace(/\/$/u, ""); } var AuthSession = class { #options; #state; #ephemeral = false; #queue = Promise.resolve(); #accounts; #ipcHosts = /* @__PURE__ */ new WeakSet(); constructor(options = {}) { const timeout = (value, fallback) => { const result = value ?? fallback; if (!Number.isSafeInteger(result) || result < 1 || result >= 2 ** 31) throw new TypeError("Invalid auth request timeout"); return result; }; this.#options = { ...options, files: options.files ?? import_promises11.default, fetcher: options.fetcher ?? globalThis.fetch, apiBase: options.apiBase ?? AUTH_API_BASE, uuid: options.uuid ?? import_node_crypto12.randomUUID, wait: options.wait ?? wait, refreshTimeoutMs: timeout(options.refreshTimeoutMs, 1e4), logoutTimeoutMs: timeout(options.logoutTimeoutMs, 5e3) }; if (!this.#options.safeStorage) throw new TypeError("Desktop authentication needs safeStorage"); if (!options.filename && !options.app) throw new TypeError("Desktop authentication needs its own profile path"); this.#accounts = options.accounts; } #filename(name = "auth-session.json") { if (name === "auth-session.json" && this.#options.filename) return typeof this.#options.filename === "function" ? this.#options.filename() : this.#options.filename; return import_node_path16.default.join(this.#options.app.getPath("userData"), name); } #warn(message3) { try { this.#options.logger?.warn(message3); } catch { } } #vault() { this.#accounts ??= (this.#options.accountsFactory ?? createSavedAccounts)({ file: this.#filename(SAVED_ACCOUNTS_FILE), safeStorage: this.#options.safeStorage }); return this.#accounts; } #remember(state, ephemeral) { try { this.#vault().note(snapshot(state), ephemeral); } catch { this.#warn("Saved account update failed"); } } #keeps(state) { try { return this.#vault().keeps(snapshot(state)) === true; } catch { this.#warn("Saved account lookup failed"); return false; } } #publish(state) { if (this.#options.broadcast) { try { this.#options.broadcast(snapshot(state)); } catch { this.#warn("Auth state notification failed"); } return; } let contents; try { contents = this.#options.webContents?.getAllWebContents() ?? []; } catch { this.#warn("Auth state notification failed"); return; } for (const content of contents) { try { if (!content.isDestroyed()) content.send("desktop:auth:changed", snapshot(state)); } catch { this.#warn("Auth state notification failed"); } } } #serialize(operation) { const task = this.#queue.then(operation); this.#queue = task.catch(() => { }); return task; } async #read() { if (this.#state !== void 0) return this.#state; let text3; try { text3 = await this.#options.files.readFile(this.#filename(), "utf8"); } catch (error) { if (error?.code !== "ENOENT") throw error; this.#state = null; return null; } let stored; try { stored = JSON.parse(text3); } catch { await this.#discard(); this.#state = null; return null; } const version = stored?.version; if (version === 2 && stored.ephemeral === true) { await this.#options.files.rm(this.#filename(), { force: true }); this.#state = null; return null; } const validEnvelope = record6(stored) && (version === 1 || version === 2 && stored.ephemeral === false); if (!validEnvelope || typeof stored.ciphertext !== "string" || !stored.ciphertext.length || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(stored.ciphertext)) { await this.#discard(); this.#state = null; return null; } if (this.#options.safeStorage.isEncryptionAvailable() !== true) throw new Error("Credential encryption is unavailable"); try { const decoded = this.#options.safeStorage.decryptString(Buffer.from(stored.ciphertext, "base64")); const state = JSON.parse(decoded); if (!isAuthState(state)) throw new Error("Invalid session state"); this.#state = snapshot(state); this.#ephemeral = false; } catch { await this.#discard(); this.#state = null; } return this.#state; } async #discard() { this.#warn("Discarding an unreadable encrypted auth session"); await this.#options.files.rm(this.#filename(), { force: true }).catch(() => { }); } async #commit(state, ephemeral) { if (ephemeral) await this.#options.files.rm(this.#filename(), { force: true }); else { if (this.#options.safeStorage.isEncryptionAvailable() !== true) throw new Error("OS credential encryption is unavailable"); const ciphertext = this.#options.safeStorage.encryptString(JSON.stringify(state)).toString("base64"); const destination = this.#filename(); const temporary = `${destination}.${this.#options.uuid()}.tmp`; const storage = this.#options.files; await storage.mkdir(import_node_path16.default.dirname(destination), { recursive: true }); let handle, acquired = false; try { handle = await storage.open(temporary, "wx", 384); acquired = true; await handle.writeFile(JSON.stringify({ ciphertext, ephemeral: false, version: 2 }), "utf8"); await handle.sync(); await handle.close(); handle = null; const pauses = [25, 100, 250]; for (let attempt = 0; ; attempt++) { try { await storage.rename(temporary, destination); break; } catch (error) { if (!["EPERM", "EACCES", "EBUSY"].includes(error?.code) || attempt === pauses.length) throw error; await this.#options.wait(pauses[attempt]); } } } finally { if (handle) await handle.close().catch(() => { }); if (acquired) await storage.rm(temporary, { force: true }).catch(() => { }); } } this.#state = snapshot(state); this.#ephemeral = ephemeral; this.#remember(this.#state, ephemeral); this.#publish(this.#state); } async #clear() { await this.#options.files.rm(this.#filename(), { force: true }); this.#state = null; this.#ephemeral = false; this.#publish(null); } #base(requested) { const configured = typeof this.#options.apiBase === "function" ? this.#options.apiBase() : this.#options.apiBase; const allowed = canonicalBase(configured); if (requested !== void 0 && canonicalBase(requested) !== allowed) throw new Error("Auth API base is not allowed"); return allowed; } async #post(base, endpoint, payload, json = false) { const controller = new AbortController(); const duration = endpoint === "/v1/auth/logout" ? this.#options.logoutTimeoutMs : this.#options.refreshTimeoutMs; let timer; const deadline = new Promise((_, reject) => { timer = setTimeout(() => { const error = new DOMException("Account API timed out", "TimeoutError"); controller.abort(error); reject(error); }, duration); }); try { const transaction = (async () => { const response = await this.#options.fetcher(base + endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: controller.signal }); let body = null; if (json && response.ok) { try { body = await response.json(); } catch { } } else { try { await response.body?.cancel(); } catch { } } return { ok: response.ok, status: response.status, body }; })(); return await Promise.race([transaction, deadline]); } catch { return null; } finally { clearTimeout(timer); } } load() { return this.#serialize(async () => snapshot(await this.#read())); } store(state, replaceSession, ephemeral) { if (!isAuthState(state)) return Promise.reject(new TypeError("Invalid desktop auth state")); if (typeof replaceSession !== "boolean" || typeof ephemeral !== "boolean") return Promise.reject(new TypeError("Auth session options require booleans")); const captured = snapshot(state); return this.#serialize(async () => { const current = await this.#read(); if (!replaceSession && current !== null && current.refreshToken !== captured.refreshToken) return snapshot(current); await this.#commit(captured, ephemeral); return snapshot(this.#state); }); } refresh(apiBase, expectedToken) { let base; try { base = this.#base(apiBase); } catch (error) { return Promise.reject(error); } if (expectedToken !== null && typeof expectedToken !== "string") return Promise.reject(new TypeError("Expected refresh token requires a string or null")); return this.#serialize(async () => { const current = await this.#read(); if (!current?.refreshToken) return { status: "rejected" }; if (expectedToken !== null && current.refreshToken !== expectedToken) return { status: "refreshed", state: snapshot(current) }; const response = await this.#post(base, "/v1/auth/refresh", { refresh_token: current.refreshToken }, true); if (denied(response)) { try { const login = loginOfAuthState(current); if (login) this.#vault().dropToken(login); } catch { this.#warn("Saved account revocation failed"); } await this.#clear(); return { status: "rejected" }; } if (!response?.ok || !isTokenResponse(response.body)) return { status: "transient" }; await this.#commit({ accessToken: response.body.access_token, refreshToken: response.body.refresh_token, email: current.email }, this.#ephemeral); return { status: "refreshed", state: snapshot(this.#state) }; }); } logout(apiBase) { let base; try { base = this.#base(apiBase); } catch (error) { return Promise.reject(error); } return this.#serialize(async () => { const current = await this.#read(); if (current !== null) this.#remember(current, this.#ephemeral); if (current?.refreshToken && !this.#keeps(current)) await this.#post(base, "/v1/auth/logout", { refresh_token: current.refreshToken }); await this.#clear(); }); } listAccounts() { return this.#serialize(async () => { const state = await this.#read().catch(() => null); if (state) this.#remember(state, this.#ephemeral); return this.#vault().list(); }); } renameAccount(login, label) { if (typeof label !== "string") return Promise.reject(new TypeError("Account label requires a string")); return this.#serialize(() => this.#vault().rename(login, label)); } signInSaved(login) { const name = normalizeLogin(login); if (name === null) return Promise.reject(new TypeError("Invalid account name")); return this.#serialize(async () => { const vault = this.#vault(); const token2 = vault.tokenOf(name); if (token2 === null) return { status: "password-needed" }; const base = this.#base(); const response = await this.#post(base, "/v1/auth/refresh", { refresh_token: token2 }, true); if (denied(response)) { vault.dropToken(name); return { status: "password-needed" }; } if (!response?.ok || !isTokenResponse(response.body)) return { status: "unavailable" }; const previous = await this.#read(); const email = vault.list().accounts.find((account) => account.login.toLowerCase() === name.toLowerCase())?.login ?? name; const state = { email, accessToken: response.body.access_token, refreshToken: response.body.refresh_token }; if (previous?.refreshToken && previous.refreshToken !== state.refreshToken && !this.#keeps(previous)) await this.#post(base, "/v1/auth/logout", { refresh_token: previous.refreshToken }); await this.#commit(state, false); return { status: "ok" }; }); } forgetAccounts(login) { const name = login === null ? null : normalizeLogin(login); if (login !== null && name === null) return Promise.reject(new TypeError("Invalid account name")); return this.#serialize(async () => { const vault = this.#vault(); if (name === null) vault.clear(); else vault.remove(name); await this.#post(this.#base(), "/v1/khaos/forget", name === null ? { all: true } : { login: name }); const current = await this.#read(); if (current && (name === null || loginOfAuthState(current)?.toLowerCase() === name.toLowerCase())) await this.#clear(); }); } installIpc(ipc) { if (this.#ipcHosts.has(ipc)) return; this.#ipcHosts.add(ipc); const families = { auth: { load: () => this.load(), store: (...args) => this.store(...args), refresh: (...args) => this.refresh(...args), logout: (...args) => this.logout(...args) }, accounts: { list: () => this.listAccounts(), "sign-in": (login) => this.signInSaved(login), rename: (...args) => this.renameAccount(...args), remove: (login) => typeof login === "string" ? this.forgetAccounts(login) : Promise.reject(new TypeError("Invalid account name")), "forget-all": () => this.forgetAccounts(null) } }; for (const [family, actions] of Object.entries(families)) for (const [name, action] of Object.entries(actions)) ipc.handle(`desktop:${family}:${name}`, (_event, ...args) => action(...args)); } }; // src/electron/khaos/updateAdapter.js var ResourceUpdaterDiagnostics = class { async claimPending() { return { status: "empty" }; } async complete() { } }; var UpdateAdapter = class { #ipcHosts = /* @__PURE__ */ new WeakSet(); #launcher; constructor({ launcher = () => globalThis.__khaosUpdater } = {}) { this.#launcher = launcher; } diagnostics = new ResourceUpdaterDiagnostics(); getState() { return { phase: "idle" }; } init() { } onStateChanged(observer) { if (typeof observer !== "function") throw new TypeError("Update state observer requires a function"); try { observer(this.getState()); } catch { } return () => { }; } async checkForUpdates() { return { available: false }; } async installDownloadedUpdate() { throw new Error("Khaos updates are installed by the Khaos launcher"); } /** {action: "restarting"} once the installer runs; "unavailable" only when a fresh check found nothing; throws on failure. */ async requestRequiredUpdate() { const flow = this.#launcher(); if (!flow || typeof flow.requestInstall !== "function") return { action: "unavailable" }; const result = await flow.requestInstall(); return result?.action === "restarting" ? { action: "restarting" } : { action: "unavailable" }; } installIpc(ipc) { if (this.#ipcHosts.has(ipc)) return; this.#ipcHosts.add(ipc); const methods = /* @__PURE__ */ new Map([ ["check", () => this.checkForUpdates()], ["status", () => this.getState()], ["install", () => this.installDownloadedUpdate()], ["request-required-update", () => this.requestRequiredUpdate()], ["diagnostics:claim", () => this.diagnostics.claimPending()], ["diagnostics:complete", (id, delivered) => { const valid2 = [typeof id === "string", typeof delivered === "boolean", typeof id === "string" && id.length >= 1 && id.length <= 128].every(Boolean); if (!valid2) return Promise.reject(new TypeError("Invalid resource updater diagnostics completion")); return this.diagnostics.complete(id, delivered); }] ]); for (const [method, callback] of methods) ipc.handle(`desktop:updater:${method}`, (_event, ...args) => callback(...args)); } }; function createUpdateService() { return new UpdateAdapter(); } // src/electron/khaos/desktopLog.js var import_node_util2 = require("node:util"); function printable(value, maximum) { try { const text3 = typeof value === "string" ? value : value instanceof Error ? `${value.name}: ${value.message}` : (0, import_node_util2.inspect)(value, { depth: 2, getters: false, customInspect: false, maxArrayLength: 16, maxStringLength: maximum }); return text3.slice(0, maximum); } catch { return "[unprintable]"; } } function bounded(value, fallback, maximum) { if (!Number.isSafeInteger(value) || value < 0) return fallback; return Math.min(value, maximum); } var DesktopLog = class { constructor({ capacity = 8192, consoleSink = console, now = Date.now } = {}) { if (!Number.isSafeInteger(capacity) || capacity < 0 || capacity > 65536) throw new TypeError("Log capacity must be an integer from zero to 65536"); Object.assign(this, { capacity, consoleSink, now }); this.entries = []; this.sequence = 0; } logger(scope) { scope = printable(scope, 160); return Object.fromEntries(["debug", "info", "warn", "error"].map((level) => [level, (message3, ...args) => { const previous = this.entries.at(-1), time = this.now(); const text3 = printable(message3, 2e3); const preview = args.slice(0, 16).map((value) => printable(value, 4096)).join(" ").slice(0, 4096); const elapsed = previous ? time - previous.wallTime : Infinity; if (previous && previous.scope === scope && previous.level === level && previous.message === text3 && elapsed >= 0 && elapsed < 1e3) Object.assign(previous, { args: preview, wallTime: time, repeat: previous.repeat + 1 }); else if (this.capacity) { this.entries.push({ seq: this.sequence++, wallTime: time, scope, level, message: text3, args: preview, repeat: 1 }); if (this.entries.length > this.capacity) this.entries.splice(0, this.entries.length - this.capacity); } if (["warn", "error"].includes(level)) { try { this.consoleSink[level](`[${scope}]`, message3, ...args); } catch { } } }])); } recent({ count: count2 = 600, argMaxChars = 500 } = {}) { count2 = bounded(count2, 600, this.capacity); argMaxChars = bounded(argMaxChars, 500, 4096); if (!count2) return []; return this.entries.slice(-count2).map((entry) => ({ t: entry.wallTime, scope: entry.scope, level: entry.level, msg: entry.message, repeat: entry.repeat, args: entry.args.slice(0, argMaxChars) })); } }; // src/electron/khaos/desktopDiagnostics.js var import_node_path17 = __toESM(require("node:path"), 1); var nativeFs = __toESM(require("node:fs"), 1); var fs11 = __toESM(require("node:fs/promises"), 1); var import_node_crypto13 = require("node:crypto"); var finite3 = (value) => typeof value === "number" && Number.isFinite(value) ? value : null; function recordFields(input, required, optional) { if (!input || typeof input !== "object") return null; const record7 = {}; for (const field of required) { const value = finite3(input[field]); if (value === null) return null; record7[field] = value; } for (const field of optional) record7[field] = finite3(input[field]); return record7; } function metricRecord(input) { const result = {}; for (const field of ["pid", "creationTime", "type"]) result[field] = input[field]; for (const field of ["name", "serviceName", "sandboxed"]) result[field] = input[field] ?? null; result.memory = {}; for (const field of ["workingSetSize", "peakWorkingSetSize", "privateBytes"]) { const value = finite3(input.memory?.[field]); result.memory[field] = value === null ? null : value * 1024; } result.cpu = Object.fromEntries(["percentCPUUsage", "idleWakeupsPerSecond"].map((field) => [field, input.cpu?.[field] ?? null])); return result; } var DesktopDiagnostics = class { constructor(electron2, options) { this.electron = electron2; this.options = options; this.files = options.fs ?? fs11; this.nativeFiles = options.nativeFs ?? nativeFs; this.clock = options.now ?? (() => /* @__PURE__ */ new Date()); this.durationClock = options.durationClock ?? (() => performance.now()); this.pending = /* @__PURE__ */ new Set(); this.sessions = /* @__PURE__ */ new Map(); this.handlers = /* @__PURE__ */ new Set(); this.disposed = false; } start() { if (this.disposed) throw new Error("Diagnostics service is closed"); if (this.handlers.size) return; const operations = { memory: () => this.memory(), "renderer-diagnostics": (event) => this.renderer(event.sender), "heap-snapshot": (event) => this.heapSnapshot(event.sender) }; for (const [action, handler] of Object.entries(operations)) { const channel2 = `desktop:diagnostics:${action}`; this.electron.ipcMain.handle(channel2, handler); this.handlers.add(channel2); } } memory() { const processes = this.electron.app.getAppMetrics().map(metricRecord); const indexed = new Map(processes.map((entry) => [entry.pid, entry])); const surfaces = this.options.surfaces.list(true).map((surface) => ({ ...surface, process: indexed.get(surface.osProcessId) ?? null })); const totals = { processCount: processes.length, workingSetSize: 0, peakWorkingSetSize: 0, privateBytes: 0, browserWorkingSetSize: 0, tabWorkingSetSize: 0, gpuWorkingSetSize: 0, utilityWorkingSetSize: 0, otherWorkingSetSize: 0 }; const categories2 = { Browser: "browserWorkingSetSize", Tab: "tabWorkingSetSize", GPU: "gpuWorkingSetSize", Utility: "utilityWorkingSetSize" }; for (const process2 of processes) { totals.workingSetSize += process2.memory.workingSetSize ?? 0; totals.peakWorkingSetSize += process2.memory.peakWorkingSetSize ?? 0; if (process2.memory.privateBytes === null) totals.privateBytes = null; else if (totals.privateBytes !== null) totals.privateBytes += process2.memory.privateBytes; totals[categories2[process2.type] ?? "otherWorkingSetSize"] += process2.memory.workingSetSize ?? 0; } return { capturedAt: this.clock().toISOString(), processes, surfaces, totals }; } assertSender(sender) { if (this.disposed || sender.isDestroyed()) throw new Error("Renderer diagnostics are unavailable for a destroyed or closed sender"); } async debuggerSession(sender, operation) { this.assertSender(sender); if (this.sessions.has(sender.id)) throw new Error("Renderer diagnostics are already running for this renderer"); const attached = sender.debugger.isAttached(); const session = { owned: !attached }; this.sessions.set(sender.id, session); try { if (session.owned) sender.debugger.attach("1.3"); return await operation(session); } finally { if (session.owned) { try { if (sender.debugger.isAttached()) sender.debugger.detach(); } catch { } } if (this.sessions.get(sender.id) === session) this.sessions.delete(sender.id); } } async renderer(sender) { return this.debuggerSession(sender, async ({ owned }) => { const capturedAt = this.clock().toISOString(); const errors = []; const command = async (name) => { try { return await sender.debugger.sendCommand(name); } catch (error) { errors.push(`${name}: ${error instanceof Error ? error.message : String(error)}`); return null; } }; let enabled = false; try { const heapUsage = recordFields(await command("Runtime.getHeapUsage"), ["usedSize", "totalSize"], ["embedderHeapUsedSize", "backingStorageSize"]); const domCounters = recordFields(await command("Memory.getDOMCounters"), ["documents", "nodes", "jsEventListeners"], []); if (owned) enabled = await command("Performance.enable") !== null; const metrics = await command("Performance.getMetrics"); const performanceMetrics = []; for (const entry of Array.isArray(metrics?.metrics) ? metrics.metrics : []) { if (typeof entry?.name === "string" && finite3(entry.value) !== null) performanceMetrics.push({ name: entry.name, value: entry.value }); } const result = { capturedAt, heapUsage, domCounters, performanceMetrics, errors }; Object.assign(result, { pid: sender.getOSProcessId(), webContentsId: sender.id, url: sender.getURL(), title: sender.getTitle() }); return result; } finally { if (enabled) await command("Performance.disable"); } }); } async heapSnapshot(sender) { this.assertSender(sender); if (this.pending.has(sender.id)) throw new Error("A heap snapshot is already running for this renderer"); this.pending.add(sender.id); let temporary; let descriptor = null; try { return await this.debuggerSession(sender, async ({ owned }) => { const start = this.durationClock(); const capturedAt = this.clock().toISOString(); const profile = typeof this.options.profileDirectory === "function" ? this.options.profileDirectory() : this.options.profileDirectory; if (typeof profile !== "string" || !profile.trim()) throw new Error("Diagnostics require an explicit profile directory"); const directory = import_node_path17.default.join(profile, "diagnostics", "heap-snapshots"); await this.files.mkdir(directory, { recursive: true }); const title = sender.getTitle(); const label = String(title).replace(/[^\w.-]/g, "-").substring(0, 64) || "renderer"; const fileName = `${capturedAt.replace(/[:.]/g, "-")}-wc${sender.id}-${(0, import_node_crypto13.randomUUID)()}-${label}.heapsnapshot`; const filePath = import_node_path17.default.join(directory, fileName); temporary = `${filePath}.tmp`; descriptor = this.nativeFiles.openSync(temporary, "wx"); let bytesWritten = 0; let writeFailure = null; const message3 = (_event, name, payload) => { if (name !== "HeapProfiler.addHeapSnapshotChunk" || typeof payload?.chunk !== "string" || writeFailure) return; try { const bytes = Buffer.from(payload.chunk, "utf8"); let offset = 0; while (offset < bytes.length) { const written = this.nativeFiles.writeSync(descriptor, bytes, offset, bytes.length - offset, null); if (!written) throw new Error("Heap snapshot write made no progress"); offset += written; bytesWritten += written; } } catch (error) { writeFailure = error; } }; let enabled = false; sender.debugger.on("message", message3); try { if (owned) { await sender.debugger.sendCommand("HeapProfiler.enable"); enabled = true; } await sender.debugger.sendCommand("HeapProfiler.takeHeapSnapshot", { reportProgress: false }); if (writeFailure) throw writeFailure; this.nativeFiles.fsyncSync(descriptor); this.nativeFiles.closeSync(descriptor); descriptor = null; await this.files.rename(temporary, filePath); temporary = null; return { capturedAt, filePath, directory, fileName, bytesWritten, durationMs: Math.round(this.durationClock() - start), webContentsId: sender.id, osProcessId: sender.getOSProcessId(), chromiumProcessId: sender.getProcessId(), url: sender.getURL(), title }; } finally { sender.debugger.off("message", message3); if (enabled) { try { await sender.debugger.sendCommand("HeapProfiler.disable"); } catch { } } } }); } finally { if (descriptor !== null) { try { this.nativeFiles.closeSync(descriptor); } catch { } } if (temporary) await this.files.rm(temporary, { force: true }).catch(() => { }); this.pending.delete(sender.id); } } dispose() { this.disposed = true; for (const channel2 of this.handlers) this.electron.ipcMain.removeHandler(channel2); this.handlers.clear(); } }; // src/electron/khaos/notifications.js var channel = "desktop:external-notifications:"; var stateChannel = channel + "state"; var corners = /* @__PURE__ */ new Set(["bottom-right", "bottom-left", "top-right", "top-left"]); function notificationRequest(input) { if (!input || typeof input !== "object" || Array.isArray(input)) throw new TypeError("Invalid external notification request"); const output = {}; for (const [name, maximum] of [["title", 160], ["text", 1e3]]) { if (typeof input[name] !== "string" || !input[name].length || input[name].length > maximum) throw new TypeError("Invalid notification text"); output[name] = input[name]; } for (const name of ["durationMs", "resetDurationMs"]) { const value = input[name]; if (!Number.isSafeInteger(value) || value < 1e3 || value > 12e4) throw new TypeError("Notification timeout is outside its supported range"); output[name] = value; } if (!Number.isInteger(input.type) || input.type < 0 || input.type > 8) throw new TypeError("Invalid notification type"); if (input.icon !== null && (typeof input.icon !== "string" || !/^[A-Za-z\d]{1,64}$/.test(input.icon))) throw new TypeError("Invalid notification icon"); if (!corners.has(input.corner) || ![1, 3, 5, 10].includes(input.maxCount) || typeof input.reducedOpacity !== "boolean") throw new TypeError("Invalid notification display options"); for (const field of ["type", "icon", "corner", "maxCount", "reducedOpacity"]) output[field] = input[field]; return output; } var ExternalNotifications = class { constructor(electron2, options) { this.electron = electron2; this.options = options; this.now = options.now ?? Date.now; this.schedule = options.setTimeout ?? setTimeout; this.cancel = options.clearTimeout ?? clearTimeout; this.entries = /* @__PURE__ */ new Map(); this.watchers = /* @__PURE__ */ new Map(); this.handlers = /* @__PURE__ */ new Map(); this.window = null; this.loading = null; this.placement = null; this.nextId = 1; this.retireTimer = null; this.unsubscribe = null; this.running = false; this.disposed = false; } start() { if (this.disposed) throw new Error("Notification service is closed"); if (this.running) return; this.running = true; const actions = { show: (event, request) => this.show(event.sender, request), "get-state": (event) => { this.overlayOnly(event.sender); return this.state(); }, activate: (event, id) => { this.overlayOnly(event.sender); const entry = this.entries.get(id); if (entry) this.options.surfaces.focus(entry.surfaceId); this.dismiss(id); }, dismiss: (event, id) => { this.overlayOnly(event.sender); this.dismiss(id); }, "reset-timeout": (event, id) => { this.overlayOnly(event.sender); this.reset(id); } }; for (const [action, handler] of Object.entries(actions)) { const name = channel + action; this.electron.ipcMain.handle(name, handler); this.handlers.set(name, handler); } this.unsubscribe = this.options.surfaces.subscribeFocused((id) => this.dismissSurface(id)); this.quitListener = () => this.dispose(); this.electron.app.once("will-quit", this.quitListener); } state() { return [...this.entries.values()].map((entry) => ({ ...entry.value })); } overlayOnly(sender) { if (!this.window || this.window.isDestroyed() || sender.id !== this.window.webContents.id) throw new Error("Notification action requires the owned overlay"); } height() { return 32 + this.entries.size * 106 + Math.max(0, this.entries.size - 1) * 10; } report(error) { this.options.logger?.error?.("External notifications failed", error); } publish() { const window = this.window; if (!window || window.isDestroyed()) return; if (this.placement) { const { workArea, corner } = this.placement; const height = this.height(); const x = workArea.x + (corner.endsWith("right") ? workArea.width - 418 : 18); const y = workArea.y + (corner.startsWith("bottom") ? workArea.height - height - 18 : 18); window.setBounds({ width: 400, height, x, y }, false); } if (!window.webContents.isDestroyed?.()) window.webContents.send(stateChannel, this.state()); } retire() { if (this.entries.size || this.retireTimer !== null) return; this.retireTimer = this.schedule(() => { this.retireTimer = null; if (this.loading) return; if (!this.entries.size && this.window && !this.window.isDestroyed()) this.window.destroy(); }, 180); this.retireTimer?.unref?.(); } dismiss(id) { const entry = this.entries.get(id); if (!entry) return; this.cancel(entry.timer); this.entries.delete(id); this.publish(); this.retire(); } dismissSurface(id) { for (const entry of [...this.entries.values()]) if (entry.surfaceId === id) this.dismiss(entry.value.id); } arm(entry, milliseconds) { this.cancel(entry.timer); entry.value.expiresAt = this.now() + milliseconds; entry.timer = this.schedule(() => this.dismiss(entry.value.id), milliseconds); entry.timer?.unref?.(); } reset(id) { const entry = this.entries.get(id); if (entry) { this.arm(entry, entry.value.resetDurationMs); this.publish(); } } watch(sender, surfaceId) { if (this.watchers.has(sender.id)) return; const destroyed = () => { this.watchers.delete(sender.id); this.dismissSurface(surfaceId); }; this.watchers.set(sender.id, { sender, destroyed }); sender.once("destroyed", destroyed); } ensureWindow() { if (this.loading) return this.loading; if (this.window && !this.window.isDestroyed()) return Promise.resolve(this.window); const work = (async () => { const specification = { width: 400, height: this.height(), backgroundColor: "#00000000" }; for (const option of ["show", "frame", "resizable", "movable", "minimizable", "maximizable", "fullscreenable", "focusable", "hasShadow"]) specification[option] = false; for (const option of ["transparent", "skipTaskbar", "alwaysOnTop"]) specification[option] = true; let window; try { window = await this.options.createWindow(specification); if (this.disposed || window.isDestroyed()) throw new Error("Notification overlay closed while opening"); this.window = window; window.once("closed", () => { if (this.window === window) this.window = null; }); window.setAlwaysOnTop(true, "floating"); window.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true, skipTransformProcessType: true }); this.publish(); await this.options.load(window, "/external-notifications"); if (this.disposed || window.isDestroyed()) throw new Error("Notification overlay closed while loading"); this.publish(); if (!this.entries.size) this.retire(); return window; } catch (error) { if (this.window === window) this.window = null; if (window && !window.isDestroyed()) window.destroy(); throw error; } })(); this.loading = work; work.finally(() => { if (this.loading === work) this.loading = null; }).catch(() => { }); return work; } async show(sender, input) { const request = notificationRequest(input); if (!this.running || this.disposed || sender.isDestroyed()) throw new Error("Notification service is unavailable"); const surface = this.options.surfaces.list().find((entry2) => entry2.surfaceId === sender.id); const carrier2 = this.options.surfaces.windowFor(sender); if (!surface || !carrier2 || carrier2.isDestroyed()) throw new Error("Notifications require a game surface"); const workArea = this.electron.screen.getDisplayMatching(carrier2.getBounds()).workArea; this.placement = { corner: request.corner, workArea }; if (this.retireTimer !== null) { this.cancel(this.retireTimer); this.retireTimer = null; } const id = this.nextId++; const createdAt = this.now(); const entry = { value: { ...request, id, characterName: surface.characterName, createdAt, expiresAt: createdAt + request.durationMs }, surfaceId: surface.surfaceId, timer: null }; this.entries.set(id, entry); this.arm(entry, request.durationMs); this.watch(sender, surface.surfaceId); const limit = workArea.height - 36; while (this.entries.size && (this.entries.size > request.maxCount || this.height() > limit)) this.dismiss(this.entries.keys().next().value); if (!this.entries.size) return; try { const window = await this.ensureWindow(); if (!window.isDestroyed() && this.entries.size && !this.disposed) { this.publish(); window.showInactive(); } } catch (error) { this.dismiss(id); this.report(error); throw error; } } dispose() { if (this.disposed) return; this.disposed = true; this.running = false; this.unsubscribe?.(); this.unsubscribe = null; this.electron.app.off?.("will-quit", this.quitListener); for (const name of this.handlers.keys()) this.electron.ipcMain.removeHandler(name); this.handlers.clear(); for (const entry of this.entries.values()) this.cancel(entry.timer); this.entries.clear(); if (this.retireTimer !== null) this.cancel(this.retireTimer); this.retireTimer = null; for (const { sender, destroyed } of this.watchers.values()) sender.off("destroyed", destroyed); this.watchers.clear(); if (this.window && !this.window.isDestroyed()) this.window.destroy(); this.window = null; } }; // src/electron/khaos/networkHost.js var NetworkHost = class { constructor(electron2, { filename, requestMs = 3e4, logger = console }) { Object.assign(this, { electron: electron2, filename, requestMs, logger }); this.worker = null; this.sequence = 0; this.session = 0; this.requests = /* @__PURE__ */ new Map(); this.owners = /* @__PURE__ */ new Map(); this.leases = /* @__PURE__ */ new Map(); this.observed = /* @__PURE__ */ new WeakSet(); } launch() { if (this.worker) return this.worker; const worker = this.electron.utilityProcess.fork(this.filename, [], { serviceName: "Khaos Network Service", stdio: "inherit" }); this.worker = worker; worker.on("message", (message3) => { if (worker === this.worker) this.receive(message3?.data ?? message3); }); worker.once("exit", () => { if (this.worker === worker) this.failed(new Error("Network service exited")); }); worker.on("error", (error) => { if (this.worker === worker) this.failed(new Error(String(error))); }); return worker; } receive(message3) { if (!message3 || typeof message3 !== "object") return; if (["connect-result", "send-result"].includes(message3.type)) { const pending = this.requests.get(message3.requestId); if (!pending) return; clearTimeout(pending.timer); this.requests.delete(message3.requestId); if (message3.sessionId !== pending.sessionId || message3.type !== pending.result) pending.reject(new Error("Network service replied for the wrong request")); else if (message3.ok === true) pending.resolve(message3.type === "connect-result" ? { sessionId: message3.sessionId } : void 0); else pending.reject(new Error(message3.error ?? "Network operation failed")); } else { const owner = this.leases.get(message3.sessionId); if (!owner || owner.isDestroyed()) return; const channels = { "network-status": "desktop:network-status", "network-message": "desktop:network-message" }; if (channels[message3.type]) { const { type, ...payload } = message3; try { owner.send(channels[type], payload); } catch { } } } } request(sessionId, type, values = {}) { const requestId = ++this.sequence; return new Promise((resolve, reject) => { const timer = setTimeout(() => { this.requests.delete(requestId); reject(new Error(`Network ${type} timed out`)); }, this.requestMs); timer.unref?.(); this.requests.set(requestId, { sessionId, result: `${type}-result`, resolve, reject, timer }); try { this.launch().postMessage({ type, sessionId, requestId, ...values }); } catch (error) { this.requests.delete(requestId); clearTimeout(timer); reject(error); } }); } async connect(owner, config) { const security = config?.security ?? "raw"; if (typeof config?.host !== "string" || !config.host || !Number.isSafeInteger(config.port) || config.port < 1 || config.port > 65535 || !["raw", "noise"].includes(security)) throw new Error("Invalid network endpoint"); this.disconnect(owner); const sessionId = ++this.session; this.owners.set(owner.id, sessionId); this.leases.set(sessionId, owner); if (!this.observed.has(owner)) { this.observed.add(owner); const cleanup = () => this.disconnect(owner); owner.once("destroyed", cleanup); owner.once("render-process-gone", cleanup); } const pending = this.request(sessionId, "connect", { host: config.host, port: config.port, security }); let ports; try { ports = new this.electron.MessageChannelMain(); this.launch().postMessage({ type: "attach-data-port", sessionId }, [ports.port1]); owner.postMessage("desktop:network-port", { sessionId }, [ports.port2]); } catch (error) { ports?.port1.close(); ports?.port2.close(); this.logger.warn?.("Network data port unavailable; using relay", error); } try { return await pending; } catch (error) { if (this.owners.get(owner.id) === sessionId) this.disconnect(owner); throw error; } } send(owner, data) { const sessionId = this.owners.get(owner.id); if (sessionId === void 0 || !isUint8Array(data)) throw new Error("Network send requires a live session and bytes"); return this.request(sessionId, "send", { data }); } disconnect(owner) { const sessionId = this.owners.get(owner.id); if (sessionId === void 0) return; this.owners.delete(owner.id); this.leases.delete(sessionId); for (const [id, request] of this.requests) if (request.sessionId === sessionId) { clearTimeout(request.timer); this.requests.delete(id); request.reject(new Error("Network session disconnected")); } try { this.worker?.postMessage({ type: "disconnect", sessionId }); } catch { } } failed(error) { const worker = this.worker; this.worker = null; for (const [sessionId, owner] of this.leases) if (!owner.isDestroyed()) { try { owner.send("desktop:network-status", { sessionId, connected: false, error: error.message }); } catch { } } for (const request of this.requests.values()) { clearTimeout(request.timer); request.reject(error); } this.requests.clear(); this.owners.clear(); this.leases.clear(); worker?.kill(); } close() { this.failed(new Error("Network host stopped")); } }; // src/electron/khaos/gameDataServiceHost.js var OUTPUT_TAIL_CHARS = 8192; var LOGGED_LINE_CHARS = 2e3; var LOGGED_LINES_PER_LEASE = 200; var LOGGED_ERRORS_PER_LEASE = 20; var SERVICE_NAME = "Khaos Game Data Service"; var CRASH_LOOP_EXITS = 6; var CRASH_WINDOW_MS = 15e3; var ERROR_LINE = /(?:^|\s)(?:[A-Z]\w*)?(?:Error|Exception)\b[^:]{0,40}:|FATAL ERROR/u; function describeServiceExit({ code, error = null, output = "" }) { if (error) return error; const lines = String(output).split(/\r?\n/u).map((line2) => line2.trim()).filter((line2) => line2 && !/^Node\.js v\d/u.test(line2)); const line = lines.findLast((text3) => ERROR_LINE.test(text3)) ?? lines.findLast((text3) => !text3.startsWith("at ")) ?? lines.at(-1); const status = code === null || code === void 0 ? "" : ` (code ${code})`; return line ? `Game data service exited unexpectedly${status}: ${line.slice(0, 300)}` : `Game data service exited unexpectedly${status}`; } var GameDataServiceHost = class { constructor(electron2, { filename, readAsset, heartbeatMs = 5e3, timeoutMs = 3e4, logger = console, record: record7 = null, now = () => performance.now() }) { Object.assign(this, { electron: electron2, filename, readAsset, heartbeatMs, timeoutMs, logger, record: record7, now }); this.current = null; this.generation = 0; this.failures = []; } crashLoop() { const now = this.now(); this.failures = this.failures.filter((at) => now - at < CRASH_WINDOW_MS); return this.failures.length >= CRASH_LOOP_EXITS; } launch() { if (this.current) return this.current; if (this.crashLoop()) throw new Error(`${SERVICE_NAME} exited ${this.failures.length} times in ${CRASH_WINDOW_MS / 1e3} s; waiting before starting it again`); const process2 = this.electron.utilityProcess.fork(this.filename, [], { serviceName: SERVICE_NAME, stdio: "pipe" }); const lease = { process: process2, generation: ++this.generation, clients: /* @__PURE__ */ new Map(), pending: [], nonce: 0, watchdog: null, failed: false, startedAt: this.now(), output: "", loggedLines: 0, partial: "" }; this.current = lease; for (const stream2 of [process2.stdout, process2.stderr]) { stream2?.setEncoding?.("utf8"); stream2?.on?.("data", (chunk) => this.keepOutput(lease, String(chunk))); stream2?.on?.("error", () => { }); } process2.on("message", (packet) => { const value = packet?.data ?? packet; if (this.current !== lease || !value || typeof value !== "object") return; if (value.type === "heartbeat-pong") { if (lease.pending.some((ping) => ping.nonce === value.nonce)) lease.pending = []; } else if (value.type === "service-error" && typeof value.error === "string") this.serviceError(lease, value); else if (value.type === "asset-read" && Number.isSafeInteger(value.requestId) && value.requestId > 0 && typeof value.url === "string") { void Promise.resolve().then(() => this.readAsset(value.url)).then((asset2) => this.reply(lease, { requestId: value.requestId, ok: true, ...asset2 }), (error) => this.reply(lease, { requestId: value.requestId, ok: false, error: error?.message ?? String(error) })); } }); process2.once("spawn", () => { lease.pid = process2.pid; lease.watchdog = setInterval(() => this.check(lease), this.heartbeatMs); lease.watchdog.unref?.(); this.check(lease); }); process2.on("error", (type, location) => { lease.error = `${SERVICE_NAME} failed: ${String(type)}${location ? ` at ${location}` : ""}`; }); process2.once("exit", (code) => this.end(lease, code)); this.logger.info?.("Game data service started", { generation: lease.generation }); return lease; } /** Keeps the last OUTPUT_TAIL_CHARS of the service's output and logs its lines (bounded per lease). */ keepOutput(lease, text3) { lease.output = (lease.output + text3).slice(-OUTPUT_TAIL_CHARS); const lines = (lease.partial + text3).split(/\r?\n/u); lease.partial = lines.pop().slice(-LOGGED_LINE_CHARS); for (const line of lines) this.logLine(lease, line); } logLine(lease, line) { if (!line.trim() || lease.loggedLines >= LOGGED_LINES_PER_LEASE) return; if (++lease.loggedLines === LOGGED_LINES_PER_LEASE) { this.logger.warn?.("Game data service output truncated", { generation: lease.generation }); return; } this.logger.warn?.(`Game data service: ${line.slice(0, LOGGED_LINE_CHARS)}`, { generation: lease.generation }); } /** An error the service caught as a last resort (it keeps running): main log, F11 reports and the stability log. */ serviceError(lease, { kind, error }) { lease.reportedErrors = (lease.reportedErrors ?? 0) + 1; if (lease.reportedErrors > LOGGED_ERRORS_PER_LEASE) return; const first = (error.split(String.fromCharCode(10))[0] ?? "").trim().slice(0, 400), label = typeof kind === "string" ? kind.slice(0, 80) : "error"; this.logger.error?.(`Game data service ${label}: ${first}`, { generation: lease.generation, error: error.slice(0, 4e3) }); try { this.record?.(`GAME DATA SERVICE ERROR generation=${lease.generation} ${label}: ${first}`); } catch { } } check(lease) { if (lease !== this.current || lease.failed) return; const now = performance.now(), latest = lease.pending.at(-1); if (latest && now - latest.at < this.timeoutMs) return; if (lease.pending.length === 2) { lease.failed = true; lease.error = "Game data service missed two heartbeat replies"; lease.process.kill(); return; } const ping = { nonce: ++lease.nonce, at: now }; lease.pending.push(ping); try { lease.process.postMessage({ type: "heartbeat-ping", nonce: ping.nonce }); } catch (error) { lease.error = String(error); lease.process.kill(); } } reply(lease, result) { if (this.current !== lease || lease.failed) return; try { lease.process.postMessage({ type: "asset-read-result", ...result }); } catch (error) { this.logger.warn?.("Game data reply failed", error); } } open(owner, frame, connectionId) { if (typeof connectionId !== "string" || !/^[\w-]{16,128}$/u.test(connectionId) || owner.isDestroyed() || frame.isDestroyed() || frame.detached) throw new Error("Invalid game-data channel target"); const lease = this.launch(); let cleanup; if (!lease.clients.has(owner.id)) { cleanup = () => { lease.clients.delete(owner.id); owner.off("destroyed", cleanup); owner.off("render-process-gone", cleanup); }; lease.clients.set(owner.id, { owner, cleanup }); owner.once("destroyed", cleanup); owner.once("render-process-gone", cleanup); } const { port1, port2 } = new this.electron.MessageChannelMain(); try { lease.process.postMessage({ type: "attach-client", connectionId }, [port1]); frame.postMessage("desktop:game-data-port", { type: "khaos:game-data-port", connectionId, generation: lease.generation }, [port2]); } catch (error) { port1.close(); port2.close(); cleanup?.(); throw error; } return { generation: lease.generation }; } end(lease, code) { clearInterval(lease.watchdog); if (lease.partial) { this.logLine(lease, lease.partial); lease.partial = ""; } const expected = lease !== this.current, lifetimeMs = Math.round(this.now() - lease.startedAt); const reason = describeServiceExit({ code, error: lease.error ?? null, output: lease.output }); if (expected) this.logger.info?.("Game data service stopped", { generation: lease.generation, code, lifetimeMs }); else { this.current = null; this.failures.push(this.now()); this.logger.error?.(`Game data service exited: ${reason}`, { generation: lease.generation, code, lifetimeMs, pid: lease.pid ?? null, output: lease.output.slice(-2e3) }); try { this.record?.(`GAME DATA SERVICE EXIT generation=${lease.generation} code=${code} after ${lifetimeMs} ms: ${reason.replace(/\s+/gu, " ").slice(0, 600)}`); } catch { } for (const { owner } of lease.clients.values()) if (!owner.isDestroyed()) owner.send("desktop:game-data-service-exit", { generation: lease.generation, code, error: reason }); } for (const { cleanup } of Array.from(lease.clients.values())) cleanup(); } /** * Stops the current service (if any) so the next channel starts a fresh one: the loading screen's Retry and its * automatic retries. An explicit restart also forgets the recent failures, so it is never refused as a crash loop. */ restart() { this.failures = []; const restarted = Boolean(this.current); if (restarted) this.logger.info?.("Game data service restart requested", { generation: this.current.generation }); this.close(); return { restarted }; } close() { const lease = this.current; if (!lease) return; this.current = null; clearInterval(lease.watchdog); for (const { cleanup } of Array.from(lease.clients.values())) cleanup(); try { lease.process.postMessage({ type: "shutdown" }); } catch { } const timer = setTimeout(() => lease.process.kill(), 500); timer.unref?.(); } }; // src/electron/khaos/dedicatedAudioHost.js var DedicatedAudioHost = class { constructor(electron2, { preferences, load, selectSource, logger = console }) { Object.assign(this, { electron: electron2, preferences, load, selectSource, logger }); this.owners = /* @__PURE__ */ new Map(); this.generation = 0; } async open(owner, frame, request) { if (!request || typeof request.connectionId !== "string" || !/^[\w-]{16,128}$/u.test(request.connectionId) || !/^[a-f0-9]{16}$/u.test(request.sourceKey) || request.assetBaseUrl !== `dofus-assets://game/${request.sourceKey}` || Object.keys(request).length !== 3 || owner.isDestroyed() || frame.isDestroyed() || frame.detached) throw new Error("Invalid dedicated audio channel"); this.release(this.owners.get(owner.id)); const window = new this.electron.BrowserWindow({ show: false, width: 1, height: 1, title: "Khaos Audio Runtime", focusable: false, skipTaskbar: true, paintWhenInitiallyHidden: true, webPreferences: { ...this.preferences(), autoplayPolicy: "no-user-gesture-required" } }); const lease = { owner, window, connectionId: request.connectionId, generation: ++this.generation, cleanups: [] }; this.owners.set(owner.id, lease); window.webContents.setBackgroundThrottling(false); const observe = (target, event, callback) => { target.on(event, callback); lease.cleanups.push(() => target.off(event, callback)); }; const stop = () => this.release(lease); observe(owner, "destroyed", stop); observe(owner, "render-process-gone", stop); observe(owner, "did-start-navigation", (event, _url, sameDocument, mainFrame) => { if ((event?.isMainFrame ?? mainFrame) && !(event?.isSameDocument ?? sameDocument)) stop(); }); observe(window, "closed", stop); observe(window.webContents, "render-process-gone", stop); try { await this.selectSource(window.webContents.id, request.sourceKey); await this.load(window, "audio"); if (this.owners.get(owner.id) !== lease || owner.isDestroyed() || frame.isDestroyed() || frame.detached) throw new Error("Audio owner changed during startup"); const { port1, port2 } = new this.electron.MessageChannelMain(); const envelope = { type: "khaos:dedicated-audio-port", connectionId: lease.connectionId, generation: lease.generation, assetBaseUrl: request.assetBaseUrl }; try { frame.postMessage("desktop:dedicated-audio-port", { ...envelope, role: "controller" }, [port1]); window.webContents.mainFrame.postMessage("desktop:dedicated-audio-port", { ...envelope, role: "runtime" }, [port2]); } catch (error) { port1.close(); port2.close(); throw error; } return { generation: lease.generation }; } catch (error) { this.release(lease); throw error; } } release(lease) { if (!lease || lease.disposed) return; lease.disposed = true; if (this.owners.get(lease.owner.id) === lease) this.owners.delete(lease.owner.id); for (const cleanup of lease.cleanups.splice(0)) { try { cleanup(); } catch { } } if (!lease.window.isDestroyed()) lease.window.close(); } close(owner, connectionId) { const lease = this.owners.get(owner.id); if (lease && lease.connectionId !== connectionId) throw new Error("Audio connection does not belong to this owner"); this.release(lease); } dispose() { for (const lease of Array.from(this.owners.values())) this.release(lease); } }; // src/electron/khaos/fmodBankHost.js var import_node_fs6 = __toESM(require("node:fs"), 1); var SPLIT_FORMAT = "khaos-split-asset"; var SHA2 = /^[0-9a-f]{64}$/u; var MAX_DESCRIPTOR_BYTES = 65536; var isAbsent = (error) => error?.name === "AssetHttpError" && error.status === 404; var SingleSource = class { constructor(descriptor) { this.descriptor = descriptor; this.size = descriptor.size; this.hash = descriptor.hash; } check() { const actual = import_node_fs6.default.fstatSync(this.descriptor.file.fd); if (!actual.isFile() || actual.size !== this.descriptor.size) throw new Error("FMOD bank changed while opening"); } readSync(buffer, at, length, position) { return import_node_fs6.default.readSync(this.descriptor.file.fd, buffer, at, length, position); } read(position, length) { return this.descriptor.file.read(position, length); } close() { return this.descriptor.file.close(); } }; var SplitSource = class { constructor(parts, size, hash) { let start = 0; this.parts = parts.map((descriptor) => { const part = { descriptor, start, size: descriptor.size }; start += descriptor.size; return part; }); if (start !== size) throw new Error("FMOD bank parts do not add up to the bank"); this.size = size; this.hash = hash; } check() { for (const part of this.parts) { const actual = import_node_fs6.default.fstatSync(part.descriptor.file.fd); if (!actual.isFile() || actual.size !== part.size) throw new Error("FMOD bank part changed while opening"); } } #part(position) { let low = 0, high = this.parts.length - 1; while (low < high) { const middle = low + high + 1 >> 1; if (this.parts[middle].start <= position) low = middle; else high = middle - 1; } return this.parts[low]; } readSync(buffer, at, length, position) { const part = this.#part(position); const within = position - part.start, count2 = Math.min(length, part.size - within); return import_node_fs6.default.readSync(part.descriptor.file.fd, buffer, at, count2, within); } async read(position, length) { const pieces = []; for (let done = 0; done < length; ) { const part = this.#part(position + done); const within = position + done - part.start, count2 = Math.min(length - done, part.size - within); pieces.push(await part.descriptor.file.read(within, count2)); done += count2; } return pieces.length === 1 ? pieces[0] : Buffer.concat(pieces, length); } async close() { const results = await Promise.allSettled(this.parts.map((part) => part.descriptor.file.close())); const failed = results.find((result) => result.status === "rejected"); if (failed) throw failed.reason; } }; function parseSplitDescriptor(bytes, name) { const value = JSON.parse(Buffer.from(bytes).toString("utf8")); const whole = `audio/banks/${name}`; if (value?.format !== SPLIT_FORMAT || value.schemaVersion !== 1 || value.path !== whole) throw new Error(`Invalid split descriptor for ${whole}`); if (!Number.isSafeInteger(value.size) || value.size < 1 || !SHA2.test(value.sha256 ?? "")) throw new Error(`Invalid split descriptor size or digest for ${whole}`); if (!Array.isArray(value.parts) || value.parts.length < 2) throw new Error(`Invalid split descriptor parts for ${whole}`); let total = 0; for (const part of value.parts) { if (typeof part?.path !== "string" || !part.path.startsWith("audio/banks/parts/") || !Number.isSafeInteger(part.size) || part.size < 1 || !SHA2.test(part.sha256 ?? "")) throw new Error(`Invalid split descriptor part for ${whole}`); total += part.size; } if (total !== value.size) throw new Error(`Split descriptor parts do not add up for ${whole}`); return value; } var FmodBankHost = class { constructor(cacheForRenderer) { this.cacheForRenderer = cacheForRenderer; this.handles = /* @__PURE__ */ new Map(); this.epochs = /* @__PURE__ */ new Map(); this.sequence = 0; } async open(renderer, name, mode) { if (typeof name !== "string" || !/^[\w.-]+\.bank$/u.test(name) || !["local", "ensure"].includes(mode)) throw new Error("Invalid FMOD bank request"); const cache2 = this.cacheForRenderer(renderer), epoch = this.epochs.get(renderer) ?? 0; this.epochs.set(renderer, epoch); const source = await this.#source(cache2, name, mode); if (!source) return null; const id = ++this.sequence; try { if ((this.epochs.get(renderer) ?? 0) !== epoch) { await source.close(); return null; } source.check(); if (!Number.isSafeInteger(id)) throw new Error("FMOD bank changed while opening"); this.handles.set(id, { renderer, name, source, size: source.size }); return { id, name, size: source.size, sha256: source.hash }; } catch (error) { await source.close(); throw error; } } /** The bank as one file, or its parts when the corpus ships it split; null when it is not on disk ("local"). */ async #source(cache2, name, mode) { const open5 = (logicalPath) => mode === "local" ? cache2.openLocalManifestAssetFile(logicalPath) : cache2.ensureManifestAssetFile(logicalPath); try { const descriptor = await open5(`audio/banks/${name}`); return descriptor ? new SingleSource(descriptor) : null; } catch (error) { if (!isAbsent(error)) throw error; } const index = await open5(`audio/banks/parts/${name}.parts.json`); if (!index) return null; let split; try { if (!(index.size > 0 && index.size <= MAX_DESCRIPTOR_BYTES)) throw new Error(`Invalid split descriptor size for audio/banks/${name}`); split = parseSplitDescriptor(await index.file.read(0, index.size), name); } finally { await index.file.close(); } const parts = []; try { for (const part of split.parts) { const descriptor = await open5(part.path); if (!descriptor) { await Promise.allSettled(parts.map((entry) => entry.file.close())); return null; } parts.push(descriptor); if (descriptor.size !== part.size || descriptor.hash !== part.sha256) throw new Error(`FMOD bank part ${part.path} differs from its descriptor`); } return new SplitSource(parts, split.size, split.sha256); } catch (error) { await Promise.allSettled(parts.map((entry) => entry.file.close())); throw error; } } lease(renderer, id, offset, length) { const entry = this.handles.get(id); if (!entry || entry.renderer !== renderer) throw new Error("FMOD bank does not belong to this renderer"); if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 1 || length > 524288 || !Number.isSafeInteger(offset + length) || offset + length > entry.size) throw new Error("Invalid FMOD bank read range"); return entry; } read(renderer, id, offset, length) { const entry = this.lease(renderer, id, offset, length), bytes = Buffer.allocUnsafe(length); let completed = 0; while (completed < length) { const count2 = entry.source.readSync(bytes, completed, length - completed, offset + completed); if (!count2) throw new Error("FMOD bank ended before requested range"); completed += count2; } return bytes; } async readAsync(renderer, id, offset, length) { const entry = this.lease(renderer, id, offset, length); return entry.source.read(offset, length); } async close(renderer, id) { const entry = this.handles.get(id); if (!entry || entry.renderer !== renderer) return; this.handles.delete(id); await entry.source.close(); } async closeRenderer(renderer) { this.epochs.set(renderer, (this.epochs.get(renderer) ?? 0) + 1); const ids = Array.from(this.handles).filter(([, entry]) => entry.renderer === renderer).map(([id]) => id); const results = await Promise.allSettled(ids.map((id) => this.close(renderer, id))); const failed = results.find((result) => result.status === "rejected"); if (failed) throw failed.reason; } async closeAll() { const renderers = /* @__PURE__ */ new Set([...this.epochs.keys(), ...Array.from(this.handles.values(), (entry) => entry.renderer)]); await Promise.all(Array.from(renderers, (id) => this.closeRenderer(id))); } }; // src/electron/khaos/desktopIpc.js var import_promises12 = __toESM(require("node:fs/promises"), 1); var import_node_path18 = __toESM(require("node:path"), 1); // src/electron/khaos/deviceIdentity.js var import_crypto = __toESM(require("crypto"), 1); var import_fs = __toESM(require("fs"), 1); var import_path = __toESM(require("path"), 1); var IDENTITY_FILE = "khaos-device-identity.json"; var CLIENT_KEY_PREFIX = "KHAOS_HWID_"; var PROOF_PREFIX = "KHAOS_DEVICE_PROOF_V1"; var ANCHOR = /^[0-9a-f]{64}$/; var B64URL = /^[A-Za-z0-9_-]+$/; var b64url = (buf) => Buffer.from(buf).toString("base64url"); function proofMessage(payload, deviceAnchor) { return `${PROOF_PREFIX} ${payload} ${deviceAnchor}`; } function valid(rec) { return rec !== null && typeof rec === "object" && rec.version === 1 && typeof rec.deviceAnchor === "string" && ANCHOR.test(rec.deviceAnchor) && typeof rec.publicKeySpki === "string" && B64URL.test(rec.publicKeySpki) && typeof rec.privateKeyPkcs8 === "string" && B64URL.test(rec.privateKeyPkcs8); } function create() { const { publicKey, privateKey } = import_crypto.default.generateKeyPairSync("ec", { namedCurve: "P-256" }); return { version: 1, deviceAnchor: import_crypto.default.randomBytes(32).toString("hex"), publicKeySpki: b64url(publicKey.export({ type: "spki", format: "der" })), privateKeyPkcs8: b64url(privateKey.export({ type: "pkcs8", format: "der" })) }; } var cache = /* @__PURE__ */ new Map(); function loadIdentity(userData) { const file2 = import_path.default.join(userData, IDENTITY_FILE); const hit = cache.get(file2); if (hit) return hit; let rec = null; try { rec = JSON.parse(import_fs.default.readFileSync(file2, "utf8")); } catch { } if (!valid(rec)) { rec = create(); import_fs.default.mkdirSync(userData, { recursive: true }); const tmp = `${file2}.${process.pid}.tmp`; import_fs.default.writeFileSync(tmp, `${JSON.stringify(rec)} `, { mode: 384 }); import_fs.default.renameSync(tmp, file2); } cache.set(file2, rec); return rec; } function deviceClientKey(userData) { return `${CLIENT_KEY_PREFIX}${loadIdentity(userData).deviceAnchor}`; } function signDeviceChallenge(userData, challengeId, payload) { if (typeof challengeId !== "string" || typeof payload !== "string") { throw new Error("Device challenge id and payload must be strings"); } const rec = loadIdentity(userData); const key = import_crypto.default.createPrivateKey({ key: Buffer.from(rec.privateKeyPkcs8, "base64url"), format: "der", type: "pkcs8" }); const signature = import_crypto.default.sign("sha256", Buffer.from(proofMessage(payload, rec.deviceAnchor), "utf8"), { key, dsaEncoding: "ieee-p1363" }); return { version: 1, challengeId, deviceAnchor: rec.deviceAnchor, publicKeySpki: rec.publicKeySpki, signature: b64url(signature) }; } // src/electron/khaos/accountSite.js var ACCOUNT_SITE_PAGES = Object.freeze({ __proto__: null, register: "/register", forgot: "/forgot-password" }); var LANGS = /* @__PURE__ */ new Set(["fr", "en", "es"]); function accountSiteUrl(page2, lang, apiBase) { const path22 = typeof page2 === "string" ? ACCOUNT_SITE_PAGES[page2] : void 0; if (typeof path22 !== "string") throw new Error("Account page refused"); return `${apiBase}${path22}?lang=${LANGS.has(lang) ? lang : "fr"}`; } // src/electron/khaos/desktopIpc.js var errorText = (failure3) => failure3 instanceof Error ? failure3.message : String(failure3); var bankId = (id) => Number.isSafeInteger(id) && id > 0; function bankRange(id, offset, length) { if (!bankId(id) || typeof offset !== "number" || typeof length !== "number") throw new Error("FMOD bank read requires numeric id, offset and length"); } var DesktopIpc = class { constructor(electron2, services) { this.electron = electron2; this.services = services; this.handlers = []; this.listeners = []; this.observed = /* @__PURE__ */ new Map(); this.installed = false; } mainFrame(event) { const sender = event?.sender, frame = event?.senderFrame; if (!sender || !frame || frame !== sender.mainFrame || sender.isDestroyed?.() || frame.isDestroyed?.() || frame.detached === true) throw new Error("This operation requires the main application frame"); } observe(sender) { if (this.observed.has(sender)) return; const cleanup = () => { if (this.observed.get(sender) !== cleanup) return; this.observed.delete(sender); sender.off("destroyed", cleanup); sender.off("render-process-gone", cleanup); try { this.services.assets.forgetRenderer(sender.id); } catch { } try { void Promise.resolve(this.services.banks.closeRenderer(sender.id)).catch(() => { }); } catch { } }; this.observed.set(sender, cleanup); sender.once("destroyed", cleanup); sender.once("render-process-gone", cleanup); } install() { if (this.installed) return; const { app, ipcMain: ipc, shell, dialog } = this.electron, { windows, assets, banks, network, gameData, audio, settings } = this.services; const identity = this.services.identity ?? { getClientKey: deviceClientKey, signChallenge: signDeviceChallenge }, storage = this.services.files ?? import_promises12.default; const routes = { "identity:get-client-key": () => identity.getClientKey(app.getPath("userData")), "identity:sign-challenge": (event, challenge) => { this.mainFrame(event); if (!challenge || Array.isArray(challenge) || typeof challenge.id !== "string" || typeof challenge.payload !== "string") throw new Error("Invalid device challenge"); return identity.signChallenge(app.getPath("userData"), challenge.id, challenge.payload); }, "network:connect": (event, options) => network.connect(event.sender, options), "network:send": (event, bytes) => network.send(event.sender, bytes), "network:disconnect": (event) => network.disconnect(event.sender), "game-data:open-channel": (event, id) => { this.mainFrame(event); if (typeof id !== "string") throw new Error("Game data connection id must be a string"); return gameData.open(event.sender, event.senderFrame, id); }, "game-data:restart-service": (event) => { this.mainFrame(event); return gameData.restart(); }, "audio:open-channel": (event, options) => { this.mainFrame(event); if (!windows.surfaces.windowFor(event.sender)) throw new Error("Audio requires a game surface"); return audio.open(event.sender, event.senderFrame, options); }, "audio:close-channel": (event, id) => { if (typeof id !== "string") throw new Error("Audio connection requires an ID"); return audio.close(event.sender, id); }, "fmod-bank:open": (event, name, mode) => { this.mainFrame(event); if (typeof name !== "string" || !["local", "ensure"].includes(mode)) throw new Error("Invalid FMOD bank open request"); this.observe(event.sender); return banks.open(event.sender.id, name, mode); }, "fmod-bank:read-async": async (event, ...range) => { try { this.mainFrame(event); bankRange(...range); return { ok: true, data: await banks.readAsync(event.sender.id, ...range) }; } catch (error) { return { ok: false, error: errorText(error) }; } }, "dialogs:error": async (event, title, detail) => { if (typeof title !== "string" || detail !== void 0 && typeof detail !== "string") throw new Error("Invalid error dialog"); const options = { type: "error", message: title, title, detail }, window = windows.forSender(event.sender); if (window && !window.isDestroyed()) await dialog.showMessageBox(window, options); else await dialog.showMessageBox(options); }, "app:exit": (_event, code = 0) => { if (!Number.isSafeInteger(code) || code < 0 || code > 255) throw new Error("Invalid application exit code"); app.exit(code); }, // WebGL2 could not start (renderer GameBootstrap): the launcher may restart Khaos on another graphics rung // (launcher/gpuMode.cjs, globalThis.__khaosGpuFallback); otherwise its answer carries the details for the dialog. "app:gpu-fallback": async (event, reason) => { this.mainFrame(event); if (typeof reason !== "string") throw new Error("Invalid graphics fallback reason"); const fallback = globalThis.__khaosGpuFallback; if (typeof fallback !== "function") return { retrying: false, details: "" }; const answer = await fallback(reason.slice(0, 2e3)); return { retrying: answer?.retrying === true, details: typeof answer?.details === "string" ? answer.details : "" }; }, // WebGL2 is up (`renderer`: its GL renderer name): the launcher keeps the graphics rung as working and answers // which one it is (the renderer's software-mode notice); "app:gpu-reset" asks for the normal mode next start. "app:gpu-ready": async (event, renderer) => { this.mainFrame(event); if (typeof renderer !== "string") throw new Error("Invalid graphics renderer name"); const ready = globalThis.__khaosGpuReady; const answer = typeof ready === "function" ? await ready(renderer.slice(0, 300)) : null; return { rung: typeof answer?.rung === "string" ? answer.rung : "", software: answer?.software === true, first: answer?.first === true, driverChanged: answer?.driverChanged === true }; }, "app:gpu-reset": async (event) => { this.mainFrame(event); const reset = globalThis.__khaosGpuReset; return typeof reset === "function" ? await reset() === true : false; }, "app:open-directory": async (_event, name) => { const directories = { options: () => import_node_path18.default.dirname(settings.path()), game: () => app.isPackaged ? import_node_path18.default.dirname(process.execPath) : app.getAppPath(), data: () => assets.root, logs: () => app.getPath("logs") }; if (!Object.hasOwn(directories, name)) throw new Error("Unknown desktop directory"); const directory = directories[name](); if (!directory) throw new Error("Game data is not initialized"); await storage.mkdir(directory, { recursive: true }); const error = await shell.openPath(directory); if (error) throw new Error(error); }, "app:open-support": () => shell.openExternal("https://api.khaos.invalid/support"), "app:open-account-site": (_event, page2, language) => shell.openExternal(accountSiteUrl(page2, language, "https://api.khaos.invalid")), "app:open-vote": (_event, server) => { if (typeof server !== "string" || !/^[a-z0-9][a-z0-9-]{1,30}$/u.test(server)) throw new Error("Invalid vote server"); return shell.openExternal(`https://api.khaos.invalid/voter?serveur=${server}`); } }; const syncBankRead = (event, ...range) => { try { this.mainFrame(event); bankRange(...range); event.returnValue = { ok: true, data: banks.read(event.sender.id, ...range) }; } catch (error) { event.returnValue = { ok: false, error: errorText(error) }; } }; const closeBank = (event, id) => { try { this.mainFrame(event); if (!bankId(id)) return; void Promise.resolve(banks.close(event.sender.id, id)).catch(() => { }); } catch { } }; try { for (const [name, action] of Object.entries(routes)) { const channel2 = `desktop:${name}`; ipc.handle(channel2, action); this.handlers.push(channel2); } for (const [channel2, callback] of [["desktop:fmod-bank:read", syncBankRead], ["desktop:fmod-bank:close", closeBank]]) { ipc.on(channel2, callback); this.listeners.push([channel2, callback]); } this.installed = true; } catch (error) { this.dispose(); throw error; } } dispose() { const ipc = this.electron.ipcMain; this.installed = false; for (const channel2 of this.handlers.splice(0)) ipc.removeHandler(channel2); for (const [channel2, callback] of this.listeners.splice(0)) ipc.off(channel2, callback); for (const cleanup of [...this.observed.values()]) cleanup(); } }; // src/electron/khaos/desktopApplication.js function desktopConfiguration(env = process.env, overrides = {}) { const base = String(overrides.baseUrl ?? env.KHAOS_ASSET_BASE_URL ?? env.DOFUS_ASSET_REMOTE_BASE_URL ?? env.VITE_ASSET_BASE_URL ?? "https://download.khaosdofus.com/khaos/assets").trim().replace(/\/+$/u, ""); const config = { ...overrides, baseUrl: base, manifestUrl: String(overrides.manifestUrl ?? env.KHAOS_ASSET_MANIFEST_URL ?? env.DOFUS_ASSET_MANIFEST_URL ?? env.VITE_ASSET_MANIFEST_URL ?? `${base}/asset-manifest.json`).trim(), rendererUrl: String(overrides.rendererUrl ?? env.ELECTRON_RENDERER_URL ?? "http://localhost:4321").trim().replace(/\/+$/u, "") }; for (const field of ["baseUrl", "manifestUrl", "rendererUrl"]) { let url; try { url = new URL(config[field]); } catch { throw new Error("Invalid desktop URL configuration"); } if (!(/* @__PURE__ */ new Set(["https:", "http:"])).has(url.protocol) || url.username || url.password || url.hash || field === "baseUrl" && url.search) throw new Error("Invalid desktop URL configuration"); } return config; } function coreAssetDirectory(directory, packaged, exists = import_node_fs7.default.existsSync) { const built = import_node_path19.default.join(directory, "dist/core"), source = import_node_path19.default.join(directory, "public/core"); if (!packaged) return source; return exists(built) || !exists(source) ? built : source; } function releaseDesktopMemory() { try { (0, import_node_v8.setFlagsFromString)("--expose-gc"); const collect = (0, import_node_vm.runInNewContext)("gc"); if (typeof collect === "function") collect(); } catch { } } var DesktopApplication = class { constructor(electron2, options) { this.electron = electron2; this.options = options; this.directory = import_node_path19.default.resolve(options.rootDirectory); const dependencies = options.dependencies ?? {}; const compiled = options.electronDirectory ?? import_node_path19.default.join(this.directory, "dist-electron"), config = desktopConfiguration(options.env, options.config); this.config = config; this.log = new DesktopLog(); this.logger = this.log.logger("KhaosDesktop"); this.settings = options.dependencies?.settings ?? new DesktopSettings({ filename: () => import_node_path19.default.join(electron2.app.getPath("userData"), "settings.json") }); this.windows = options.dependencies?.windows ?? new DesktopWindows(electron2, { settings: this.settings, appDirectory: this.directory, rendererUrl: config.rendererUrl, rendererFile: options.rendererFile, preload: import_node_path19.default.join(compiled, "preload.cjs"), logger: this.logger }); this.updater = dependencies.updater ?? createUpdateService(); const core = coreAssetDirectory(this.directory, electron2.app.isPackaged), setupRequest = options.gameDataSetup ?? globalThis.__khaosGameDataSetup ?? null; this.location = options.dependencies?.location ?? new GameDataLocation({ app: electron2.app, dialog: electron2.dialog, BrowserWindow: electron2.BrowserWindow, logger: this.logger, bytes: 12.5 * 1073741824, defaultRoot: setupRequest?.defaultRoot ?? null, setup: gameDataSetupStep({ electron: electron2, request: setupRequest, coreDirectory: core, logger: this.logger }), programDirectory: import_node_path19.default.dirname(process.execPath) }); this.assets = options.dependencies?.assets ?? new DesktopAssets({ electron: electron2, paths: { core, metadataWorker: import_node_path19.default.join(compiled, "asset-metadata-service.cjs"), legacyCache: import_node_path19.default.join(electron2.app.getPath("userData"), "asset-cache") }, config: { ...config, version: electron2.app.getVersion(), installProfile: "desktop-bc7" }, location: this.location, logger: this.log.logger("DesktopAssets"), broadcast: (channel2, state) => this.windows.broadcast(channel2, state), option: (name) => this.settings.current?.options?.[name], recentLogs: () => this.log.recent(), releaseMemory: releaseDesktopMemory, beforeClear: () => this.banks.closeAll(), onUpdateRequired: () => this.updater.checkForUpdates(), onSourceSelected: async (id) => { await this.banks.closeRenderer(id); const sender = electron2.webContents.fromId(id); if (sender) this.ipc.observe(sender); }, onProgress: (state) => { const transfer = state.transfer; const fraction = state.phase !== "downloading" || !transfer ? -1 : transfer.bytesTotal > 0 ? Math.max(0, Math.min(1, transfer.bytesDone / transfer.bytesTotal)) : 0; for (const window of this.windows.carriers) if (!window.isDestroyed()) window.setProgressBar(fraction); } }); this.banks = dependencies.banks ?? new FmodBankHost((id) => { const cache2 = this.assets.cacheForKey(this.assets.rendererSources.get(id) ?? this.assets.activeKey); if (!cache2) throw new Error("Unknown FMOD asset source"); return cache2; }); this.network = dependencies.network ?? new NetworkHost(electron2, { filename: import_node_path19.default.join(compiled, "network-service.cjs"), logger: this.logger }); this.gameData = dependencies.gameData ?? new GameDataServiceHost(electron2, { filename: import_node_path19.default.join(compiled, "game-data-service.cjs"), logger: this.logger, readAsset: (url) => this.readGameData(url), record: (line) => globalThis.__khaosStabilityLine?.(line) }); this.audio = dependencies.audio ?? new DedicatedAudioHost(electron2, { preferences: () => this.windows.preferences(), load: (window) => options.audioFile ? window.loadFile(options.audioFile) : this.windows.loadAudio(window), logger: this.logger, selectSource: async (id, key) => { if (!this.assets.cacheForKey(key)) throw new Error("Unknown audio source"); await this.banks.closeRenderer(id); this.assets.rendererSources.set(id, key); const sender = electron2.webContents.fromId(id); if (sender) this.ipc.observe(sender); } }); this.auth = dependencies.auth ?? new AuthSession({ app: electron2.app, safeStorage: electron2.safeStorage, webContents: electron2.webContents, logger: this.log.logger("AuthSession") }); this.diagnostics = dependencies.diagnostics ?? new DesktopDiagnostics(electron2, { surfaces: this.windows.surfaces, profileDirectory: () => electron2.app.getPath("userData"), logger: this.logger }); this.notifications = dependencies.notifications ?? new ExternalNotifications(electron2, { surfaces: this.windows.surfaces, createWindow: (spec) => new electron2.BrowserWindow({ ...spec, webPreferences: this.windows.preferences() }), load: (window, route) => this.windows.load(window, route), logger: this.logger }); this.ipc = dependencies.ipc ?? new DesktopIpc(electron2, { windows: this.windows, assets: this.assets, banks: this.banks, network: this.network, gameData: this.gameData, audio: this.audio, settings: this.settings, rootDirectory: this.directory }); this.listeners = []; this.starting = null; this.stopping = null; this.closed = false; this.registeredChannels = /* @__PURE__ */ new Set(); this.reads = new AbortController(); } listen(name, callback) { this.electron.app.on(name, callback); this.listeners.push([name, callback]); } async readGameData(url) { this.assertRunning(); if (typeof url !== "string" || /[\s\\%?#]/u.test(url) || url.split("/").some((part) => part === "." || part === "..")) throw new Error("Rejected game-data asset URL"); const parsed = new URL(url), segments = parsed.pathname.split("/"); if (parsed.protocol !== "dofus-assets:" || parsed.host !== "game" || parsed.username || parsed.password || !/^[a-f0-9]{16}$/u.test(segments[1]) || segments[2] !== "data" || segments.slice(1).some((part) => !part)) throw new Error("Rejected game-data source"); const response = await this.assets.handleProtocol(new Request(url, { signal: this.reads.signal })); if (!response.ok) { await response.body?.cancel().catch(() => { }); throw new Error(`Game data request failed (${response.status})`); } const bytes = await responseBytes(response, url, 64 * 1048576, this.reads.signal); return { bytes: new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength), contentType: response.headers.get("content-type"), hash: response.headers.get("x-dofus-asset-hash"), version: response.headers.get("x-dofus-asset-version") }; } assertRunning() { if (this.closed) throw new Error("Desktop application is stopped"); } async collectChannels(operation) { const ipc = this.electron.ipcMain; const original = ipc.handle; const record7 = (channel2, handler) => { const result = original.call(ipc, channel2, handler); this.registeredChannels.add(channel2); return result; }; ipc.handle = record7; try { return await operation(); } finally { if (ipc.handle === record7) ipc.handle = original; if (this.closed) { this.removeChannels(); this.restoreGuards(); } } } start() { if (this.closed) return Promise.reject(new Error("Desktop application is stopped")); if (!this.starting) this.starting = this.boot().catch(async (error) => { await this.stop(); throw error; }); return this.starting; } async boot() { const { app, protocol, Menu } = this.electron; if (app.isReady()) throw new Error("Desktop application must start before Electron readiness"); const privileges = Object.fromEntries("standard secure supportFetchAPI corsEnabled stream".split(" ").map((name) => [name, true])); protocol.registerSchemesAsPrivileged([{ scheme: "dofus-assets", privileges }]); const existingGuards = new Set(app.listeners("web-contents-created")); this.originalIpc = { handle: this.electron.ipcMain.handle, on: this.electron.ipcMain.on }; installKhaosElectronGuards(this.electron, { appDir: this.options.rendererFile ? import_node_path19.default.dirname(this.options.rendererFile) : import_node_path19.default.join(this.directory, "dist"), rendererUrl: this.config.rendererUrl }); this.guardIpc = { handle: this.electron.ipcMain.handle, on: this.electron.ipcMain.on }; for (const callback of app.listeners("web-contents-created")) if (!existingGuards.has(callback)) this.listeners.push(["web-contents-created", callback]); app.commandLine.appendSwitch("force-color-profile", "srgb"); app.setAppUserModelId("net.khaosdofus.khaos"); if (this.options.singleInstance !== false && !app.requestSingleInstanceLock({ variant: "game" })) { await this.stop(); app.quit(); return; } this.listen("will-quit", () => { void this.stop(); }); this.listen("second-instance", (_event, _argv, _cwd, payload) => { try { if (!payload || typeof payload !== "object" || Array.isArray(payload) || Reflect.ownKeys(payload).length !== 1 || Object.getOwnPropertyDescriptor(payload, "variant")?.value !== "game") return; void this.start().then(() => { this.assertRunning(); return this.windows.open(null); }).catch((error) => this.logger.error("Second instance failed", error)); } catch (error) { this.logger.warn("Rejected second instance payload", error); } }); await app.whenReady(); this.assertRunning(); const gpuCheck = this.options.gpuStartCheck ?? globalThis.__khaosGpuStartCheck; const gpuReady = typeof gpuCheck === "function" ? Promise.resolve().then(() => gpuCheck()).then((proceed) => proceed !== false, (error) => { this.logger.warn("Graphics start check failed", error); return true; }) : Promise.resolve(true); if (process.platform !== "darwin") { Menu.setApplicationMenu(null); this.listen("browser-window-created", (_event, window) => window.removeMenu()); } if (app.isPackaged && app.isDefaultProtocolClient("khaos")) app.removeAsDefaultProtocolClient("khaos"); await this.collectChannels(async () => { await this.windows.start(); this.assertRunning(); this.auth.installIpc(this.electron.ipcMain); this.updater.installIpc(this.electron.ipcMain); this.diagnostics.start(); this.notifications.start(); this.ipc.install(); }); this.listen("window-all-closed", () => { }); if (!await gpuReady) { this.logger.info?.("No WebGL2 on this graphics mode: no window opened"); await this.stop(); return this; } this.assertRunning(); const storage = this.options.storageRoot ?? await this.location.initialize({ promptOnFirstRun: true }); this.assertRunning(); if (!storage) { this.logger.info?.("Game data folder step closed: quitting"); await this.stop(); app.quit(); return this; } try { await this.assets.initialize(storage); } finally { if (this.closed) { try { this.electron.protocol.unhandle?.("dofus-assets"); } catch { } } } this.assertRunning(); this.assetChannels = await this.collectChannels(() => this.assets.registerIpc()); this.listen("activate", () => { if (!this.windows.carriers.size) void this.windows.open(null).catch((error) => this.logger.error("Window activation failed", error)); }); this.listen("window-all-closed", () => { if (process.platform !== "darwin" && this.options.quitOnLastWindow !== false) app.quit(); }); await this.windows.open(null); return this; } stop() { this.closed = true; this.reads.abort(new Error("Desktop application stopped")); if (!this.stopping) this.stopping = (async () => { for (const [name, callback] of this.listeners.splice(0)) this.electron.app.off(name, callback); const tasks = /* @__PURE__ */ new Map([["IPC", () => this.ipc.dispose()], ["notifications", () => this.notifications.dispose()], ["diagnostics", () => this.diagnostics.dispose()], ["windows", () => this.windows.close()], ["audio", () => this.audio.dispose()], ["network", () => this.network.close()], ["game data", () => this.gameData.close()], ["FMOD banks", () => this.banks.closeAll()], ["assets", () => this.assets.close()]]); const results = await Promise.allSettled([...tasks.values()].map((operation) => Promise.resolve().then(operation))); this.removeChannels(); this.restoreGuards(); try { if (this.electron.protocol.isProtocolHandled?.("dofus-assets") !== false) this.electron.protocol.unhandle?.("dofus-assets"); } catch (error) { this.logger.warn("Asset protocol cleanup failed", error); } let index = 0; for (const name of tasks.keys()) { if (results[index].status === "rejected") this.logger.warn(`Desktop ${name} cleanup failed`, results[index].reason); index++; } })(); return this.stopping; } removeChannels() { for (const channel2 of /* @__PURE__ */ new Set([...this.registeredChannels, ...this.assetChannels ?? []])) { try { this.electron.ipcMain.removeHandler(channel2); } catch (error) { this.logger.warn("IPC cleanup failed", error); } } this.registeredChannels.clear(); } restoreGuards() { if (!this.originalIpc || !this.guardIpc) return; for (const method of ["handle", "on"]) if (this.electron.ipcMain[method] === this.guardIpc[method]) this.electron.ipcMain[method] = this.originalIpc[method]; } }; // src/electron/main.js var desktop = new DesktopApplication(import_electron.default, { rootDirectory: import_node_path20.default.resolve(__dirname, ".."), electronDirectory: __dirname }); void desktop.start().catch((error) => { console.error("Khaos desktop startup failed", error); import_electron.default.app.exit(1); }); //# sourceMappingURL=main.cjs.map