@felfhenor/electron 0.0.0-stage → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/logging.js ADDED
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.gameLog = exports.coreLog = exports.formatLine = exports.redactHome = exports.logFilePath = exports.LOG_LEVELS = void 0;
7
+ exports.initLogging = initLogging;
8
+ exports.logSessionHeader = logSessionHeader;
9
+ const electron_1 = require("electron");
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const os_1 = __importDefault(require("os"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const util_1 = __importDefault(require("util"));
14
+ const paths_1 = require("./paths");
15
+ // The current session's file plus this many previous ones.
16
+ const KEPT_SESSIONS = 5;
17
+ // A renderer stuck throwing every frame would otherwise fill the disk in one session.
18
+ const MAX_LOG_BYTES = 50 * 1024 * 1024;
19
+ const MAX_ENTRY_LENGTH = 25000;
20
+ exports.LOG_LEVELS = ['debug', 'log', 'info', 'warn', 'error'];
21
+ const logFilePath = (name, index) => path_1.default.join((0, paths_1.logsDir)(), index === 0 ? `${name}.log` : `${name}.${index}.log`);
22
+ exports.logFilePath = logFilePath;
23
+ // name.log -> name.1.log -> ... dropping the oldest.
24
+ function rotateLogFiles(name) {
25
+ fs_1.default.rmSync((0, exports.logFilePath)(name, KEPT_SESSIONS - 1), { force: true });
26
+ for (let index = KEPT_SESSIONS - 2; index >= 0; index--) {
27
+ const from = (0, exports.logFilePath)(name, index);
28
+ if (fs_1.default.existsSync(from))
29
+ fs_1.default.renameSync(from, (0, exports.logFilePath)(name, index + 1));
30
+ }
31
+ }
32
+ function truncate(text) {
33
+ if (text.length <= MAX_ENTRY_LENGTH)
34
+ return text;
35
+ const cut = text.length - MAX_ENTRY_LENGTH;
36
+ return `${text.slice(0, MAX_ENTRY_LENGTH)}... [truncated ${cut} chars]`;
37
+ }
38
+ // Paths under the home folder carry the OS username, and these files get shared with the developer.
39
+ const homePatterns = [os_1.default.homedir(), os_1.default.homedir().replaceAll('\\', '/')];
40
+ const redactHome = (text) => homePatterns.reduce((result, home) => result.replaceAll(home, '~'), text);
41
+ exports.redactHome = redactHome;
42
+ const formatLine = (level, category, message) => `${new Date().toISOString()} [${level.toUpperCase().padEnd(5)}] {${category}} ${(0, exports.redactHome)(truncate(message))}\n`;
43
+ exports.formatLine = formatLine;
44
+ // A locked file can block rotation; appending still keeps this session's lines.
45
+ function openSessionFile(name) {
46
+ fs_1.default.mkdirSync((0, paths_1.logsDir)(), { recursive: true });
47
+ try {
48
+ rotateLogFiles(name);
49
+ return fs_1.default.openSync((0, exports.logFilePath)(name, 0), 'w');
50
+ }
51
+ catch (e) {
52
+ console.error(`Could not rotate ${name}.log`, e);
53
+ return fs_1.default.openSync((0, exports.logFilePath)(name, 0), 'a');
54
+ }
55
+ }
56
+ function withLevels(write, flush = () => undefined) {
57
+ const at = (level) => (category, ...data) => write(level, category, util_1.default.formatWithOptions({ depth: 5, breakLength: Infinity }, ...data));
58
+ return {
59
+ write,
60
+ flush,
61
+ info: at('info'),
62
+ warn: at('warn'),
63
+ error: at('error'),
64
+ };
65
+ }
66
+ // Sync writes so the last lines before a hard crash still reach the disk.
67
+ function createSessionLog(name) {
68
+ let fd;
69
+ let bytes = 0;
70
+ let lastEntry = '';
71
+ let repeats = 0;
72
+ try {
73
+ fd = openSessionFile(name);
74
+ }
75
+ catch (e) {
76
+ console.error(`Could not open ${name}.log`, e);
77
+ }
78
+ const writeLine = (line) => {
79
+ if (fd === undefined || bytes >= MAX_LOG_BYTES)
80
+ return;
81
+ try {
82
+ fs_1.default.writeSync(fd, line);
83
+ bytes += Buffer.byteLength(line);
84
+ }
85
+ catch {
86
+ // A failing log write must never take the game down with it.
87
+ }
88
+ };
89
+ const emit = (level, category, message) => {
90
+ const line = (0, exports.formatLine)(level, category, message);
91
+ if (!electron_1.app.isPackaged)
92
+ process.stdout.write(`[${name}] ${line}`);
93
+ writeLine(line);
94
+ };
95
+ const flush = () => {
96
+ if (repeats > 0)
97
+ emit('info', 'Log', `Previous message repeated ${repeats} more times.`);
98
+ repeats = 0;
99
+ };
100
+ // An error thrown every frame would otherwise hit the size cap and lose the crash that follows it.
101
+ const write = (level, category, message) => {
102
+ const entry = `${level}|${category}|${message}`;
103
+ if (entry === lastEntry) {
104
+ repeats++;
105
+ return;
106
+ }
107
+ flush();
108
+ lastEntry = entry;
109
+ emit(level, category, message);
110
+ };
111
+ return withLevels(write, flush);
112
+ }
113
+ const noopLog = withLevels(() => undefined);
114
+ // No-ops until initLogging, so a second instance or installer run can't rotate away the live session's logs.
115
+ const logs = { core: noopLog, game: noopLog };
116
+ function initLogging() {
117
+ logs.core = createSessionLog('core');
118
+ logs.game = createSessionLog('game');
119
+ electron_1.app.on('quit', () => {
120
+ logs.game.flush();
121
+ logs.core.flush();
122
+ });
123
+ }
124
+ const coreLog = () => logs.core;
125
+ exports.coreLog = coreLog;
126
+ const gameLog = () => logs.game;
127
+ exports.gameLog = gameLog;
128
+ function logSessionHeader() {
129
+ const log = (0, exports.coreLog)();
130
+ log.info('Session', `App ${electron_1.app.getName()} ${electron_1.app.getVersion()} (packaged: ${electron_1.app.isPackaged})`);
131
+ log.info('Session', `Electron ${process.versions.electron}, Chrome ${process.versions.chrome}`);
132
+ log.info('Session', `OS ${os_1.default.type()} ${os_1.default.release()} ${os_1.default.arch()}`);
133
+ log.info('Session', `userData ${electron_1.app.getPath('userData')}`);
134
+ }
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "@felfhenor/electron",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.6",
4
+ "description": "Desktop shell for felfhenor games: disk saves, backups, logs, window handling, Steam and Discord.",
5
+ "license": "UNLICENSED",
6
+ "main": "./index.js",
7
+ "types": "./index.d.ts",
8
+ "peerDependencies": {
9
+ "electron": ">=43.0.0"
10
+ },
11
+ "peerDependenciesMeta": {
12
+ "electron": {
13
+ "optional": true
14
+ }
15
+ },
16
+ "dependencies": {
17
+ "@zip.js/zip.js": "^2.25.1"
18
+ }
19
+ }
package/paths.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ export declare const savesDir: () => string;
2
+ export declare const backupsDir: () => string;
3
+ export declare const logsDir: () => string;
4
+ export declare const SAVE_KINDS: readonly ["save", "profile"];
5
+ export type SaveKind = (typeof SAVE_KINDS)[number];
6
+ export declare function isSaveKind(value: unknown): value is SaveKind;
7
+ export declare const saveFilePath: (kind: SaveKind, dir?: string) => string;
8
+ export declare function backupFilePath(id: string, dir?: string): string;
package/paths.js ADDED
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.saveFilePath = exports.SAVE_KINDS = exports.logsDir = exports.backupsDir = exports.savesDir = void 0;
7
+ exports.isSaveKind = isSaveKind;
8
+ exports.backupFilePath = backupFilePath;
9
+ const electron_1 = require("electron");
10
+ const path_1 = __importDefault(require("path"));
11
+ // Dev runs share userData with the installed game, so they get their own folders to keep its files.
12
+ function userFolder(name) {
13
+ return path_1.default.join(electron_1.app.getPath('userData'), electron_1.app.isPackaged ? name : `${name}-dev`);
14
+ }
15
+ const savesDir = () => userFolder('savefiles');
16
+ exports.savesDir = savesDir;
17
+ const backupsDir = () => userFolder('savefile-backups');
18
+ exports.backupsDir = backupsDir;
19
+ const logsDir = () => userFolder('logs');
20
+ exports.logsDir = logsDir;
21
+ exports.SAVE_KINDS = ['save', 'profile'];
22
+ function isSaveKind(value) {
23
+ return exports.SAVE_KINDS.includes(value);
24
+ }
25
+ const saveFilePath = (kind, dir = (0, exports.savesDir)()) => path_1.default.join(dir, kind === 'save' ? 'savefile.json' : 'profile.json');
26
+ exports.saveFilePath = saveFilePath;
27
+ // Ids come from the renderer, so anything that could escape the backup folder is rejected.
28
+ function backupFilePath(id, dir = (0, exports.backupsDir)()) {
29
+ if (!/^[a-z0-9-]+$/i.test(id))
30
+ throw new Error(`Invalid backup id: ${id}`);
31
+ return path_1.default.join(dir, `${id}.json`);
32
+ }
package/preload.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ declare const contextBridge: Electron.ContextBridge, ipcRenderer: Electron.IpcRenderer;
2
+ declare const felInvoke: (channel: string, ...args: unknown[]) => Promise<any>;
3
+ declare const felSend: (channel: string, ...args: unknown[]) => void;
4
+ declare function felOnSaveBeforeClose(callback: () => Promise<boolean>): () => void;
package/preload.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ /* eslint-disable @typescript-eslint/no-require-imports, @typescript-eslint/consistent-type-imports -- a sandboxed preload only has require */
3
+ // A sandboxed preload can't load local files, so this stays a self-contained script: no imports, channel names inline.
4
+ const { contextBridge, ipcRenderer } = require('electron');
5
+ const felInvoke = (channel, ...args) => ipcRenderer.invoke(channel, ...args);
6
+ const felSend = (channel, ...args) => ipcRenderer.send(channel, ...args);
7
+ // A throwing save still answers, so the main process doesn't sit out its timeout.
8
+ function felOnSaveBeforeClose(callback) {
9
+ const listener = () => Promise.resolve()
10
+ .then(callback)
11
+ .catch(() => false)
12
+ .then((saved) => felSend('fel:window:save-before-close:done', saved));
13
+ ipcRenderer.on('fel:window:save-before-close', listener);
14
+ felSend('fel:window:save-before-close:ready');
15
+ return () => ipcRenderer.removeListener('fel:window:save-before-close', listener);
16
+ }
17
+ contextBridge.exposeInMainWorld('felHost', {
18
+ platform: 'electron',
19
+ files: {
20
+ read: (kind) => felInvoke('fel:files:read', kind),
21
+ write: (kind, json) => felInvoke('fel:files:write', kind, json),
22
+ quarantine: (kind) => felInvoke('fel:files:quarantine', kind),
23
+ backupList: () => felInvoke('fel:backup:list'),
24
+ backupWrite: (id, json) => felInvoke('fel:backup:write', id, json),
25
+ backupDelete: (ids) => felInvoke('fel:backup:delete', ids),
26
+ },
27
+ log: {
28
+ write: (level, category, message) => felSend('fel:log:write', level, category, message),
29
+ },
30
+ window: {
31
+ flash: () => felSend('fel:window:flash'),
32
+ onSaveBeforeClose: felOnSaveBeforeClose,
33
+ },
34
+ notify: (title, body) => felSend('fel:window:notify', title, body),
35
+ openFolder: (kind) => felInvoke('fel:open-folder', kind),
36
+ exportWithLogs: (json) => felInvoke('fel:export-with-logs', json),
37
+ steam: {
38
+ achievementsActivate: (ids) => felInvoke('fel:steam:achievements', ids),
39
+ achievementClear: (id) => felInvoke('fel:steam:achievement-clear', id),
40
+ presence: (display, tokens) => felSend('fel:steam:presence', display, tokens),
41
+ inputType: () => felInvoke('fel:steam:input-type'),
42
+ showKeyboard: (rect) => felInvoke('fel:steam:keyboard', rect),
43
+ },
44
+ discord: {
45
+ presence: (presence) => felSend('fel:discord:presence', presence),
46
+ },
47
+ });
package/protocol.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export declare const APP_SCHEME = "app";
2
+ export declare const APP_HOST = "game";
3
+ export declare function protocolRegisterScheme(): void;
4
+ export declare function protocolResolve(root: string, url: string): string | undefined;
5
+ export declare function protocolServe(browserDir: string): void;
package/protocol.js ADDED
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.APP_HOST = exports.APP_SCHEME = void 0;
7
+ exports.protocolRegisterScheme = protocolRegisterScheme;
8
+ exports.protocolResolve = protocolResolve;
9
+ exports.protocolServe = protocolServe;
10
+ const electron_1 = require("electron");
11
+ const path_1 = __importDefault(require("path"));
12
+ const url_1 = require("url");
13
+ exports.APP_SCHEME = 'app';
14
+ exports.APP_HOST = 'game';
15
+ // Must run before app ready. Standard + secure gives the page a real origin (storage keys on it) and lets fetch() load content.
16
+ function protocolRegisterScheme() {
17
+ electron_1.protocol.registerSchemesAsPrivileged([
18
+ {
19
+ scheme: exports.APP_SCHEME,
20
+ // stream lets <audio>/<video> served from app:// seek and play progressively.
21
+ privileges: {
22
+ standard: true,
23
+ secure: true,
24
+ supportFetchAPI: true,
25
+ stream: true,
26
+ },
27
+ },
28
+ ]);
29
+ }
30
+ // Decoded first, so an encoded `..%2F` can't slip past the containment check.
31
+ function protocolResolve(root, url) {
32
+ const { host, pathname } = new URL(url);
33
+ if (host !== exports.APP_HOST)
34
+ return undefined;
35
+ let decoded;
36
+ try {
37
+ decoded = decodeURIComponent(pathname);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ // No asset path has one, and Windows would treat it as a separator: refused everywhere, not just on Windows.
43
+ if (decoded.includes('\\'))
44
+ return undefined;
45
+ const target = path_1.default.resolve(root, `.${path_1.default.posix.normalize(`/${decoded}`)}`);
46
+ const inside = target === root || target.startsWith(`${root}${path_1.default.sep}`);
47
+ return inside ? target : undefined;
48
+ }
49
+ // Anything without a file extension is an app route, so it gets index.html.
50
+ function protocolTarget(root, url) {
51
+ const target = protocolResolve(root, url);
52
+ if (!target)
53
+ return undefined;
54
+ return path_1.default.extname(target) ? target : path_1.default.join(root, 'index.html');
55
+ }
56
+ function protocolServe(browserDir) {
57
+ const root = path_1.default.resolve(browserDir);
58
+ electron_1.protocol.handle(exports.APP_SCHEME, async (request) => {
59
+ const target = protocolTarget(root, request.url);
60
+ if (!target)
61
+ return new Response('Not found', { status: 404 });
62
+ return electron_1.net.fetch((0, url_1.pathToFileURL)(target).toString());
63
+ });
64
+ }
@@ -0,0 +1,4 @@
1
+ import type { BrowserWindow } from 'electron';
2
+ export declare const SAVE_TIMEOUT_MS = 5000;
3
+ export declare const SKIP_SAVE_WINDOW_MS = 10000;
4
+ export declare function watchSaveBeforeClose(win: BrowserWindow): void;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SKIP_SAVE_WINDOW_MS = exports.SAVE_TIMEOUT_MS = void 0;
4
+ exports.watchSaveBeforeClose = watchSaveBeforeClose;
5
+ const electron_1 = require("electron");
6
+ const ipc_1 = require("./ipc");
7
+ const logging_1 = require("./logging");
8
+ // Long enough for a large IndexedDB write, short enough that a hung renderer can't keep the game open.
9
+ exports.SAVE_TIMEOUT_MS = 5000;
10
+ // How long "close again to quit without saving" stays armed after a failed save.
11
+ exports.SKIP_SAVE_WINDOW_MS = 10000;
12
+ function closeNow(win, state) {
13
+ state.canClose = true;
14
+ if (win.isDestroyed())
15
+ return;
16
+ if (state.isQuitting)
17
+ electron_1.app.quit();
18
+ else
19
+ win.close();
20
+ }
21
+ // The renderer answers true when saved (or when saving is blocked); false arms a second close to quit anyway.
22
+ function closeFinish(win, state, saved) {
23
+ state.isSaving = false;
24
+ (0, logging_1.coreLog)().info('SaveBeforeClose', `save finished, saved: ${saved}`);
25
+ if (saved)
26
+ return closeNow(win, state);
27
+ state.isQuitting = false;
28
+ state.canClose = true;
29
+ clearTimeout(state.skipTimer);
30
+ state.skipTimer = setTimeout(() => (state.canClose = false), exports.SKIP_SAVE_WINDOW_MS);
31
+ }
32
+ function closeAskRenderer(win, state) {
33
+ state.isSaving = true;
34
+ const onDone = (event, saved) => {
35
+ if (event.sender !== win.webContents)
36
+ return;
37
+ clearTimeout(timeout);
38
+ electron_1.ipcMain.removeListener(ipc_1.CHANNELS.saveBeforeCloseDone, onDone);
39
+ closeFinish(win, state, saved === true);
40
+ };
41
+ const timeout = setTimeout(() => {
42
+ (0, logging_1.coreLog)().warn('SaveBeforeClose', `no answer within ${exports.SAVE_TIMEOUT_MS}ms, closing anyway`);
43
+ electron_1.ipcMain.removeListener(ipc_1.CHANNELS.saveBeforeCloseDone, onDone);
44
+ closeFinish(win, state, true);
45
+ }, exports.SAVE_TIMEOUT_MS);
46
+ electron_1.ipcMain.on(ipc_1.CHANNELS.saveBeforeCloseDone, onDone);
47
+ win.webContents.send(ipc_1.CHANNELS.saveBeforeClose);
48
+ }
49
+ // Holds a close until the renderer confirms its save landed, so a long autosave interval loses nothing.
50
+ function watchSaveBeforeClose(win) {
51
+ const state = {
52
+ canClose: false,
53
+ isSaving: false,
54
+ isQuitting: false,
55
+ isListening: false,
56
+ };
57
+ // Cmd+Q closes windows as part of quitting; holding that close cancels the quit, so it's resumed after.
58
+ electron_1.app.on('before-quit', () => (state.isQuitting = true));
59
+ electron_1.ipcMain.on(ipc_1.CHANNELS.saveBeforeCloseReady, (event) => {
60
+ if (event.sender === win.webContents)
61
+ state.isListening = true;
62
+ });
63
+ win.webContents.on('did-navigate', () => (state.isListening = false));
64
+ win.webContents.on('render-process-gone', () => (state.isListening = false));
65
+ win.on('close', (event) => {
66
+ if (state.canClose || !state.isListening)
67
+ return;
68
+ event.preventDefault();
69
+ if (!state.isSaving)
70
+ closeAskRenderer(win, state);
71
+ });
72
+ }
package/steam.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function steamInit(appId?: number): void;
2
+ export declare function steamRegisterHandlers(): void;
package/steam.js ADDED
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.steamInit = steamInit;
4
+ exports.steamRegisterHandlers = steamRegisterHandlers;
5
+ const electron_1 = require("electron");
6
+ const ipc_1 = require("./ipc");
7
+ const logging_1 = require("./logging");
8
+ /* eslint-disable @typescript-eslint/no-explicit-any -- steamworks.js is optional and loaded untyped */
9
+ let client;
10
+ // The overlay only redraws when the page does, so an idle screen would freeze it mid-animation.
11
+ function repaintForOverlay(win) {
12
+ const timer = setInterval(() => {
13
+ if (win.isDestroyed())
14
+ return clearInterval(timer);
15
+ if (win.isVisible() && !win.isMinimized())
16
+ win.webContents.invalidate();
17
+ }, 1000 / 60);
18
+ }
19
+ // Must run before app ready: the overlay needs command-line switches that only apply at startup.
20
+ function steamInit(appId) {
21
+ try {
22
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
23
+ const steamworks = require('steamworks.js');
24
+ client = steamworks.init(Number(process.env['STEAM_APP_ID']) || appId);
25
+ steamworks.electronEnableSteamOverlay(true);
26
+ // Partial swaps only redraw what changed, leaving the closed overlay's bar burned into static screens.
27
+ electron_1.app.commandLine.appendSwitch('ui-disable-partial-swap');
28
+ electron_1.app.on('browser-window-created', (_event, win) => repaintForOverlay(win));
29
+ client.input.init();
30
+ (0, logging_1.coreLog)().info('Steam', `initialized app ${client.utils.getAppId()}`);
31
+ }
32
+ catch (e) {
33
+ // Expected whenever steamworks.js isn't installed or the Steam client isn't running.
34
+ client = undefined;
35
+ (0, logging_1.coreLog)().info('Steam', 'not connected', e.message);
36
+ }
37
+ }
38
+ const isAchievementId = (id) => typeof id === 'string' && /^\w+$/.test(id);
39
+ function steamActivate(ids) {
40
+ if (!client || !Array.isArray(ids))
41
+ return false;
42
+ const pending = ids
43
+ .filter(isAchievementId)
44
+ .filter((id) => !client.achievement.isActivated(id));
45
+ const failed = pending.filter((id) => !client.achievement.activate(id));
46
+ // Usually a name missing from the Steamworks partner site.
47
+ if (failed.length)
48
+ (0, logging_1.coreLog)().warn('Steam', 'achievements not activated', failed);
49
+ return failed.length === 0;
50
+ }
51
+ let presenceKeys = [];
52
+ // Every key from the last activity is cleared, so a leftover can't leak into the next token.
53
+ function steamPresence(display, tokens) {
54
+ if (!client)
55
+ return;
56
+ const next = typeof display === 'string' ? { steam_display: display } : {};
57
+ Object.entries((tokens ?? {})).forEach(([k, v]) => {
58
+ if (typeof v === 'string')
59
+ next[k] = v.slice(0, 255);
60
+ });
61
+ try {
62
+ presenceKeys
63
+ .filter((k) => !(k in next))
64
+ .forEach((k) => client.localplayer.setRichPresence(k, null));
65
+ Object.entries(next).forEach(([k, v]) => client.localplayer.setRichPresence(k, v));
66
+ presenceKeys = Object.keys(next);
67
+ }
68
+ catch (e) {
69
+ (0, logging_1.coreLog)().warn('Steam', 'rich presence not set', e.message);
70
+ }
71
+ }
72
+ // Steam Input's virtual pad hides the physical controller from the browser; the Deck's built-in pad can report Unknown.
73
+ function steamInputType() {
74
+ if (!client)
75
+ return undefined;
76
+ const type = client.input.getControllers()[0]?.getType();
77
+ if (type && type !== 'Unknown')
78
+ return type;
79
+ return client.utils.isSteamRunningOnSteamDeck()
80
+ ? 'SteamDeckController'
81
+ : undefined;
82
+ }
83
+ async function steamKeyboard(rect) {
84
+ const { x, y, width, height } = (rect ?? {});
85
+ const box = [x, y, width, height];
86
+ if (!client || !box.every((n) => Number.isFinite(n)))
87
+ return false;
88
+ // 0 = single line; the keyboard types into whichever field has focus.
89
+ return client.utils
90
+ .showFloatingGamepadTextInput(0, ...box.map((n) => Math.round(n)))
91
+ .catch(() => false);
92
+ }
93
+ function steamRegisterHandlers() {
94
+ (0, ipc_1.ipcHandle)(ipc_1.CHANNELS.steamAchievements, (ids) => steamActivate(ids));
95
+ (0, ipc_1.ipcHandle)(ipc_1.CHANNELS.steamAchievementClear, (id) => client && isAchievementId(id) ? client.achievement.clear(id) : false);
96
+ (0, ipc_1.ipcOn)(ipc_1.CHANNELS.steamPresence, (_event, display, tokens) => steamPresence(display, tokens));
97
+ (0, ipc_1.ipcHandle)(ipc_1.CHANNELS.steamInputType, () => {
98
+ try {
99
+ return steamInputType();
100
+ }
101
+ catch {
102
+ return undefined;
103
+ }
104
+ });
105
+ (0, ipc_1.ipcHandle)(ipc_1.CHANNELS.steamKeyboard, (rect) => steamKeyboard(rect));
106
+ }
package/window.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import type { Rectangle } from 'electron';
2
+ import { BrowserWindow } from 'electron';
3
+ import type { FelElectronOptions } from './config';
4
+ export declare function windowRestorableBounds(bounds?: Rectangle): Rectangle | undefined;
5
+ export declare function windowCreate(options: FelElectronOptions, preload: string, devOrigin?: string): BrowserWindow;
6
+ export declare function windowBringToFront(win: BrowserWindow): void;
7
+ export declare function windowRegisterHandlers(getWindow: () => BrowserWindow | undefined, root: string): void;