Fix script deletion during execution on desktop
This commit fixes an issue seen on certain Windows environments (Windows 10 22H2 and 11 23H2 Pro Azure VMs) where scripts were being deleted during execution due to temporary directory usage. To resolve this, scripts are now stored in a persistent directory, enhancing reliability for long-running scripts and improving auditability along with troubleshooting. Key changes: - Move script execution logic to the `main` process from `preloader` to utilize Electron's `app.getPath`. - Improve runtime environment detection for non-browser environments to allow its usage in Electron main process. - Introduce a secure module to expose IPC channels from the main process to the renderer via the preloader process. Supporting refactorings include: - Simplify `CodeRunner` interface by removing the `tempScriptFolderName` parameter. - Rename `NodeSystemOperations` to `NodeElectronSystemOperations` as it now wraps electron APIs too, and convert it to class for simplicity. - Rename `TemporaryFileCodeRunner` to `ScriptFileCodeRunner` to reflect its new functinoality. - Rename `SystemOperations` folder to `System` for simplicity. - Rename `HostRuntimeEnvironment` to `BrowserRuntimeEnvironment` for clarity. - Refactor main Electron process configuration to align with latest Electron documentation/recommendations. - Refactor unit tests `BrowserRuntimeEnvironment` to simplify singleton workaround. - Use alias imports like `electron/main` and `electron/common` for better clarity.
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
export interface CodeRunner {
|
||||
runCode(
|
||||
code: string,
|
||||
tempScriptFolderName: string,
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { IApplication } from '@/domain/IApplication';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { IApplicationFactory } from '../IApplicationFactory';
|
||||
import { ApplicationFactory } from '../ApplicationFactory';
|
||||
import { ApplicationContext } from './ApplicationContext';
|
||||
|
||||
export async function buildContext(
|
||||
factory: IApplicationFactory = ApplicationFactory.Current,
|
||||
environment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
environment = CurrentEnvironment,
|
||||
): Promise<IApplicationContext> {
|
||||
const app = await factory.getApp();
|
||||
const os = getInitialOs(app, environment.os);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { SystemOperations } from '../../System/SystemOperations';
|
||||
import { NodeElectronSystemOperations } from '../../System/NodeElectronSystemOperations';
|
||||
import { ScriptDirectoryProvider } from './ScriptDirectoryProvider';
|
||||
|
||||
export const ExecutionSubdirectory = 'runs';
|
||||
|
||||
export class PersistentDirectoryProvider implements ScriptDirectoryProvider {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
async provideScriptDirectory(): Promise<string> {
|
||||
const scriptsDirectory = this.system.location.combinePaths(
|
||||
/*
|
||||
Switched from temporary to persistent directory for script storage for improved reliability.
|
||||
|
||||
Temporary directories in some environments, such certain Windows Pro Azure VMs, showed
|
||||
issues where scripts were interrupted due to directory cleanup during script execution.
|
||||
This was observed with system temp directories (e.g., `%LOCALAPPDATA%\Temp`).
|
||||
|
||||
Persistent directories offer better stability during long executions and aid in auditability
|
||||
and troubleshooting.
|
||||
*/
|
||||
this.system.operatingSystem.getUserDataDirectory(),
|
||||
ExecutionSubdirectory,
|
||||
);
|
||||
this.logger.info(`Attempting to create script directory at path: ${scriptsDirectory}`);
|
||||
try {
|
||||
await this.system.fileSystem.createDirectory(scriptsDirectory, true);
|
||||
this.logger.info(`Script directory successfully created at: ${scriptsDirectory}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error creating script directory at ${scriptsDirectory}: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
return scriptsDirectory;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface ScriptDirectoryProvider {
|
||||
provideScriptDirectory(): Promise<string>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { FilenameGenerator } from './FilenameGenerator';
|
||||
|
||||
/**
|
||||
@@ -14,7 +14,7 @@ export class OsTimestampedFilenameGenerator implements FilenameGenerator {
|
||||
private readonly currentOs?: OperatingSystem;
|
||||
|
||||
constructor(
|
||||
environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) {
|
||||
this.currentOs = environment.os;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { SystemOperations } from '../System/SystemOperations';
|
||||
import { NodeElectronSystemOperations } from '../System/NodeElectronSystemOperations';
|
||||
import { FilenameGenerator } from './Filename/FilenameGenerator';
|
||||
import { ScriptFileCreator } from './ScriptFileCreator';
|
||||
import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator';
|
||||
import { ScriptDirectoryProvider } from './Directory/ScriptDirectoryProvider';
|
||||
import { PersistentDirectoryProvider } from './Directory/PersistentDirectoryProvider';
|
||||
|
||||
export class ScriptFileCreationOrchestrator implements ScriptFileCreator {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(),
|
||||
private readonly directoryProvider: ScriptDirectoryProvider = new PersistentDirectoryProvider(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
public async createScriptFile(contents: string): Promise<string> {
|
||||
const filePath = await this.provideFilePath();
|
||||
await this.createFile(filePath, contents);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async provideFilePath(): Promise<string> {
|
||||
const filename = this.filenameGenerator.generateFilename();
|
||||
const directoryPath = await this.directoryProvider.provideScriptDirectory();
|
||||
const filePath = this.system.location.combinePaths(directoryPath, filename);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async createFile(filePath: string, contents: string): Promise<void> {
|
||||
this.logger.info(`Creating file at ${filePath}, size: ${contents.length} characters`);
|
||||
await this.system.fileSystem.writeToFile(filePath, contents);
|
||||
this.logger.info(`File created successfully at ${filePath}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export interface ScriptFileCreator {
|
||||
createScriptFile(contents: string): Promise<string>;
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { CommandOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { CommandOps, SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { createNodeSystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/NodeSystemOperations';
|
||||
import { NodeElectronSystemOperations } from '@/infrastructure/CodeRunner/System/NodeElectronSystemOperations';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { ScriptFileExecutor } from './ScriptFileExecutor';
|
||||
|
||||
export class VisibleTerminalScriptExecutor implements ScriptFileExecutor {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = createNodeSystemOperations(),
|
||||
private readonly system: SystemOperations = new NodeElectronSystemOperations(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
private readonly environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
private readonly environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) { }
|
||||
|
||||
public async executeScriptFile(filePath: string): Promise<void> {
|
||||
|
||||
29
src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts
Normal file
29
src/infrastructure/CodeRunner/ScriptFileCodeRunner.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '../Log/ElectronLogger';
|
||||
import { ScriptFileExecutor } from './Execution/ScriptFileExecutor';
|
||||
import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor';
|
||||
import { ScriptFileCreator } from './Creation/ScriptFileCreator';
|
||||
import { ScriptFileCreationOrchestrator } from './Creation/ScriptFileCreationOrchestrator';
|
||||
|
||||
export class ScriptFileCodeRunner implements CodeRunner {
|
||||
constructor(
|
||||
private readonly scriptFileExecutor: ScriptFileExecutor = new VisibleTerminalScriptExecutor(),
|
||||
private readonly scriptFileCreator: ScriptFileCreator = new ScriptFileCreationOrchestrator(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
) { }
|
||||
|
||||
public async runCode(
|
||||
code: string,
|
||||
): Promise<void> {
|
||||
this.logger.info('Initiating script running process.');
|
||||
try {
|
||||
const scriptFilePath = await this.scriptFileCreator.createScriptFile(code);
|
||||
await this.scriptFileExecutor.executeScriptFile(scriptFilePath);
|
||||
this.logger.info(`Successfully ran script at ${scriptFilePath}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error running script: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { join } from 'node:path';
|
||||
import { chmod, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { exec } from 'node:child_process';
|
||||
import { app } from 'electron/main';
|
||||
import {
|
||||
CommandOps, FileSystemOps, LocationOps, OperatingSystemOps, SystemOperations,
|
||||
} from './SystemOperations';
|
||||
|
||||
export class NodeElectronSystemOperations implements SystemOperations {
|
||||
public readonly operatingSystem: OperatingSystemOps = {
|
||||
/*
|
||||
This method returns the directory for storing app's configuration files.
|
||||
It appends your app's name to the default appData directory.
|
||||
Conventionally, you should store user data files in this directory.
|
||||
However, avoid writing large files here as some environments might back up this directory
|
||||
to cloud storage, potentially causing issues with file size.
|
||||
|
||||
Based on tests it returns:
|
||||
|
||||
- Windows: `%APPDATA%\privacy.sexy`
|
||||
- Linux: `$HOME/.config/privacy.sexy/runs`
|
||||
- macOS: `$HOME/Library/Application Support/privacy.sexy/runs`
|
||||
|
||||
For more details, refer to the Electron documentation: https://web.archive.org/web/20240104154857/https://www.electronjs.org/docs/latest/api/app#appgetpathname
|
||||
*/
|
||||
getUserDataDirectory: () => {
|
||||
return app.getPath('userData');
|
||||
},
|
||||
};
|
||||
|
||||
public readonly location: LocationOps = {
|
||||
combinePaths: (...pathSegments) => join(...pathSegments),
|
||||
};
|
||||
|
||||
public readonly fileSystem: FileSystemOps = {
|
||||
setFilePermissions: (
|
||||
filePath: string,
|
||||
mode: string | number,
|
||||
) => chmod(filePath, mode),
|
||||
createDirectory: async (
|
||||
directoryPath: string,
|
||||
isRecursive?: boolean,
|
||||
) => {
|
||||
await mkdir(directoryPath, { recursive: isRecursive });
|
||||
// Ignoring the return value from `mkdir`, which is the first directory created
|
||||
// when `recursive` is true, or empty return value.
|
||||
// See https://github.com/nodejs/node/pull/31530
|
||||
},
|
||||
writeToFile: (
|
||||
filePath: string,
|
||||
data: string,
|
||||
) => writeFile(filePath, data),
|
||||
};
|
||||
|
||||
public readonly command: CommandOps = {
|
||||
exec: (command) => new Promise((resolve, reject) => {
|
||||
exec(command, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,7 @@ export interface SystemOperations {
|
||||
}
|
||||
|
||||
export interface OperatingSystemOps {
|
||||
getTempDirectory(): string;
|
||||
getUserDataDirectory(): string;
|
||||
}
|
||||
|
||||
export interface LocationOps {
|
||||
@@ -1,46 +0,0 @@
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { chmod, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { exec } from 'node:child_process';
|
||||
import { SystemOperations } from './SystemOperations';
|
||||
|
||||
export function createNodeSystemOperations(): SystemOperations {
|
||||
return {
|
||||
operatingSystem: {
|
||||
getTempDirectory: () => tmpdir(),
|
||||
},
|
||||
location: {
|
||||
combinePaths: (...pathSegments) => join(...pathSegments),
|
||||
},
|
||||
fileSystem: {
|
||||
setFilePermissions: (
|
||||
filePath: string,
|
||||
mode: string | number,
|
||||
) => chmod(filePath, mode),
|
||||
createDirectory: async (
|
||||
directoryPath: string,
|
||||
isRecursive?: boolean,
|
||||
) => {
|
||||
await mkdir(directoryPath, { recursive: isRecursive });
|
||||
// Ignoring the return value from `mkdir`, which is the first directory created
|
||||
// when `recursive` is true. The function contract is to not return any value,
|
||||
// and we avoid handling this inconsistent behavior.
|
||||
// See https://github.com/nodejs/node/pull/31530
|
||||
},
|
||||
writeToFile: (
|
||||
filePath: string,
|
||||
data: string,
|
||||
) => writeFile(filePath, data),
|
||||
},
|
||||
command: {
|
||||
exec: (command) => new Promise((resolve, reject) => {
|
||||
exec(command, (error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ElectronLogger } from '../Log/ElectronLogger';
|
||||
import { SystemOperations } from './SystemOperations/SystemOperations';
|
||||
import { createNodeSystemOperations } from './SystemOperations/NodeSystemOperations';
|
||||
import { FilenameGenerator } from './Filename/FilenameGenerator';
|
||||
import { ScriptFileExecutor } from './Execution/ScriptFileExecutor';
|
||||
import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor';
|
||||
import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator';
|
||||
|
||||
export class TemporaryFileCodeRunner implements CodeRunner {
|
||||
constructor(
|
||||
private readonly system: SystemOperations = createNodeSystemOperations(),
|
||||
private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(),
|
||||
private readonly logger: Logger = ElectronLogger,
|
||||
private readonly scriptFileExecutor: ScriptFileExecutor = new VisibleTerminalScriptExecutor(),
|
||||
) { }
|
||||
|
||||
public async runCode(
|
||||
code: string,
|
||||
tempScriptFolderName: string,
|
||||
): Promise<void> {
|
||||
this.logger.info('Starting running code.');
|
||||
try {
|
||||
const filename = this.filenameGenerator.generateFilename();
|
||||
const filePath = await this.createTemporaryFile(filename, tempScriptFolderName, code);
|
||||
await this.scriptFileExecutor.executeScriptFile(filePath);
|
||||
this.logger.info(`Successfully executed script at ${filePath}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error executing script: ${error.message}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async createTemporaryFile(
|
||||
filename: string,
|
||||
tempScriptFolderName: string,
|
||||
contents: string,
|
||||
): Promise<string> {
|
||||
const directoryPath = this.system.location.combinePaths(
|
||||
this.system.operatingSystem.getTempDirectory(),
|
||||
tempScriptFolderName,
|
||||
);
|
||||
await this.createDirectoryIfNotExists(directoryPath);
|
||||
const filePath = this.system.location.combinePaths(directoryPath, filename);
|
||||
await this.createFile(filePath, contents);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
private async createFile(filePath: string, contents: string): Promise<void> {
|
||||
this.logger.info(`Creating file at ${filePath}, size: ${contents.length} characters`);
|
||||
await this.system.fileSystem.writeToFile(filePath, contents);
|
||||
this.logger.info(`File created successfully at ${filePath}`);
|
||||
}
|
||||
|
||||
private async createDirectoryIfNotExists(directoryPath: string): Promise<void> {
|
||||
this.logger.info(`Checking and ensuring directory exists: ${directoryPath}`);
|
||||
await this.system.fileSystem.createDirectory(directoryPath, true);
|
||||
this.logger.info(`Directory confirmed at: ${directoryPath}`);
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,19 @@ import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
||||
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
||||
import { EnvironmentVariablesFactory } from '@/infrastructure/EnvironmentVariables/EnvironmentVariablesFactory';
|
||||
import { RuntimeEnvironment } from '../RuntimeEnvironment';
|
||||
import { ConditionBasedOsDetector } from './BrowserOs/ConditionBasedOsDetector';
|
||||
import { BrowserEnvironment, BrowserOsDetector } from './BrowserOs/BrowserOsDetector';
|
||||
import { RuntimeEnvironment } from './RuntimeEnvironment';
|
||||
import { isTouchEnabledDevice } from './TouchSupportDetection';
|
||||
|
||||
export class HostRuntimeEnvironment implements RuntimeEnvironment {
|
||||
public static readonly CurrentEnvironment
|
||||
: RuntimeEnvironment = new HostRuntimeEnvironment(window);
|
||||
|
||||
export class BrowserRuntimeEnvironment implements RuntimeEnvironment {
|
||||
public readonly isDesktop: boolean;
|
||||
|
||||
public readonly os: OperatingSystem | undefined;
|
||||
|
||||
public readonly isNonProduction: boolean;
|
||||
|
||||
protected constructor(
|
||||
public constructor(
|
||||
window: Partial<Window>,
|
||||
environmentVariables: IEnvironmentVariables = EnvironmentVariablesFactory.Current.instance,
|
||||
browserOsDetector: BrowserOsDetector = new ConditionBasedOsDetector(),
|
||||
@@ -1,6 +1,8 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
|
||||
export function convertPlatformToOs(platform: NodeJS.Platform): OperatingSystem | undefined {
|
||||
export function convertPlatformToOs(
|
||||
platform: NodeJS.Platform,
|
||||
): OperatingSystem | undefined {
|
||||
switch (platform) {
|
||||
case 'darwin':
|
||||
return OperatingSystem.macOS;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '../RuntimeEnvironment';
|
||||
import { convertPlatformToOs } from './NodeOsMapper';
|
||||
|
||||
export class NodeRuntimeEnvironment implements RuntimeEnvironment {
|
||||
public readonly isDesktop: boolean;
|
||||
|
||||
public readonly os: OperatingSystem | undefined;
|
||||
|
||||
public readonly isNonProduction: boolean;
|
||||
|
||||
constructor(
|
||||
nodeProcess: NodeJSProcessAccessor = globalThis.process,
|
||||
convertToOs: PlatformToOperatingSystemConverter = convertPlatformToOs,
|
||||
) {
|
||||
if (!nodeProcess) { throw new Error('missing process'); } // do not trust strictNullChecks for global objects
|
||||
this.isDesktop = true;
|
||||
this.os = convertToOs(nodeProcess.platform);
|
||||
this.isNonProduction = nodeProcess.env.NODE_ENV !== 'production'; // populated by Vite
|
||||
}
|
||||
}
|
||||
|
||||
export interface NodeJSProcessAccessor {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
export type PlatformToOperatingSystemConverter = typeof convertPlatformToOs;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { BrowserRuntimeEnvironment } from './Browser/BrowserRuntimeEnvironment';
|
||||
import { NodeRuntimeEnvironment } from './Node/NodeRuntimeEnvironment';
|
||||
import { RuntimeEnvironment } from './RuntimeEnvironment';
|
||||
|
||||
export const CurrentEnvironment = determineAndCreateRuntimeEnvironment(
|
||||
() => globalThis.window,
|
||||
);
|
||||
|
||||
export function determineAndCreateRuntimeEnvironment(
|
||||
windowAccessor: WindowAccessor,
|
||||
browserEnvironmentFactory: BrowserRuntimeEnvironmentFactory = (
|
||||
window,
|
||||
) => new BrowserRuntimeEnvironment(window),
|
||||
nodeEnvironmentFactory: NodeRuntimeEnvironmentFactory = () => new NodeRuntimeEnvironment(),
|
||||
): RuntimeEnvironment {
|
||||
const window = windowAccessor();
|
||||
if (window) {
|
||||
return browserEnvironmentFactory(window);
|
||||
}
|
||||
return nodeEnvironmentFactory();
|
||||
}
|
||||
|
||||
export type BrowserRuntimeEnvironmentFactory = (window: Window) => RuntimeEnvironment;
|
||||
|
||||
export type NodeRuntimeEnvironmentFactory = () => NodeRuntimeEnvironment;
|
||||
|
||||
export type WindowAccessor = () => Window | undefined;
|
||||
@@ -1,10 +1,10 @@
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { ConsoleLogger } from '@/infrastructure/Log/ConsoleLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { LoggerFactory } from '@/application/Common/Log/LoggerFactory';
|
||||
import { NoopLogger } from '@/infrastructure/Log/NoopLogger';
|
||||
import { WindowInjectedLogger } from '@/infrastructure/Log/WindowInjectedLogger';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
|
||||
export class ClientLoggerFactory implements LoggerFactory {
|
||||
public static readonly Current: LoggerFactory = new ClientLoggerFactory();
|
||||
@@ -12,7 +12,7 @@ export class ClientLoggerFactory implements LoggerFactory {
|
||||
public readonly logger: Logger;
|
||||
|
||||
protected constructor(
|
||||
environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
environment: RuntimeEnvironment = CurrentEnvironment,
|
||||
) {
|
||||
if (environment.isDesktop) {
|
||||
this.logger = new WindowInjectedLogger();
|
||||
|
||||
@@ -13,7 +13,7 @@ import { PropertyKeys } from '@/TypeHelpers';
|
||||
import { useUserSelectionState } from '@/presentation/components/Shared/Hooks/UseUserSelectionState';
|
||||
import { useLogger } from '@/presentation/components/Shared/Hooks/UseLogger';
|
||||
import { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRunner';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
|
||||
export function provideDependencies(
|
||||
context: IApplicationContext,
|
||||
@@ -33,7 +33,7 @@ export function provideDependencies(
|
||||
),
|
||||
useRuntimeEnvironment: (di) => di.provide(
|
||||
InjectionKeys.useRuntimeEnvironment,
|
||||
HostRuntimeEnvironment.CurrentEnvironment,
|
||||
CurrentEnvironment,
|
||||
),
|
||||
useAutoUnsubscribedEvents: (di) => di.provide(
|
||||
InjectionKeys.useAutoUnsubscribedEvents,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { CurrentEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironmentFactory';
|
||||
import { Bootstrapper } from '../Bootstrapper';
|
||||
|
||||
export class MobileSafariActivePseudoClassEnabler implements Bootstrapper {
|
||||
constructor(
|
||||
private readonly currentEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||
private readonly currentEnvironment = CurrentEnvironment,
|
||||
private readonly browser: BrowserAccessor = GlobalBrowserAccessor,
|
||||
) {
|
||||
|
||||
|
||||
@@ -26,10 +26,7 @@ export default defineComponent({
|
||||
|
||||
async function executeCode() {
|
||||
if (!codeRunner) { throw new Error('missing code runner'); }
|
||||
await codeRunner.runCode(
|
||||
currentContext.state.code.current,
|
||||
currentContext.app.info.name,
|
||||
);
|
||||
await codeRunner.runCode(currentContext.state.code.current);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
24
src/presentation/electron/main/IpcRegistration.ts
Normal file
24
src/presentation/electron/main/IpcRegistration.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { registerIpcChannel } from '../shared/IpcBridging/IpcProxy';
|
||||
import { IpcChannelDefinitions } from '../shared/IpcBridging/IpcChannelDefinitions';
|
||||
|
||||
export function registerAllIpcChannels(
|
||||
createCodeRunner: CodeRunnerFactory = () => new ScriptFileCodeRunner(),
|
||||
registrar: IpcRegistrar = registerIpcChannel,
|
||||
) {
|
||||
const registrars: Record<keyof typeof IpcChannelDefinitions, () => void> = {
|
||||
CodeRunner: () => registrar(IpcChannelDefinitions.CodeRunner, createCodeRunner()),
|
||||
};
|
||||
Object.entries(registrars).forEach(([name, register]) => {
|
||||
try {
|
||||
register();
|
||||
} catch (err) {
|
||||
throw new AggregateError(`main: Failed to register IPC channel "${name}"`, err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export type CodeRunnerFactory = () => CodeRunner;
|
||||
|
||||
export type IpcRegistrar = typeof registerIpcChannel;
|
||||
@@ -1,4 +1,4 @@
|
||||
import { app, dialog } from 'electron';
|
||||
import { app, dialog } from 'electron/main';
|
||||
import { autoUpdater, UpdateInfo } from 'electron-updater';
|
||||
import { ProgressInfo } from 'electron-builder';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { dialog } from 'electron';
|
||||
import { dialog } from 'electron/main';
|
||||
|
||||
export enum ManualUpdateChoice {
|
||||
NoAction = 0,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { existsSync, createWriteStream, type WriteStream } from 'node:fs';
|
||||
import { unlink, mkdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { app } from 'electron';
|
||||
import { app } from 'electron/main';
|
||||
import { UpdateInfo } from 'electron-updater';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { UpdateProgressBar } from '../UpdateProgressBar';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { app, shell } from 'electron';
|
||||
import { app } from 'electron/main';
|
||||
import { shell } from 'electron/common';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { retryFileSystemAccess } from './RetryFileSystemAccess';
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import ProgressBar from 'electron-progressbar';
|
||||
import { ProgressInfo } from 'electron-builder';
|
||||
import { app, BrowserWindow } from 'electron';
|
||||
import { app, BrowserWindow } from 'electron/main';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
|
||||
export class UpdateProgressBar {
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
// Initializes Electron's main process, always runs in the background, and manages the main window.
|
||||
|
||||
import {
|
||||
app, protocol, BrowserWindow, shell, screen,
|
||||
} from 'electron';
|
||||
app, protocol, BrowserWindow, screen,
|
||||
} from 'electron/main';
|
||||
import { shell } from 'electron/common';
|
||||
import log from 'electron-log/main';
|
||||
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer';
|
||||
import { validateRuntimeSanity } from '@/infrastructure/RuntimeSanity/SanityChecks';
|
||||
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { name } from '@/../package.json' assert { type: 'json' };
|
||||
import { setupAutoUpdater } from './Update/UpdateInitializer';
|
||||
import {
|
||||
APP_ICON_PATH, PRELOADER_SCRIPT_PATH, RENDERER_HTML_PATH, RENDERER_URL,
|
||||
} from './ElectronConfig';
|
||||
import { registerAllIpcChannels } from './IpcRegistration';
|
||||
|
||||
const isDevelopment = !app.isPackaged;
|
||||
|
||||
@@ -57,36 +60,11 @@ function createWindow() {
|
||||
});
|
||||
}
|
||||
|
||||
let macOsQuit = false;
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform === 'darwin'
|
||||
&& !macOsQuit) {
|
||||
// On macOS it is common for applications and their menu bar
|
||||
// to stay active until the user quits explicitly with Cmd + Q
|
||||
return;
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
configureAppQuitBehavior();
|
||||
registerAllIpcChannels();
|
||||
setAppName();
|
||||
|
||||
if (process.platform === 'darwin') {
|
||||
// On macOS we application quit is stopped if user does not Cmd + Q
|
||||
// But we still want to be able to use app.quit() and quit the application
|
||||
// on menu bar, after updates etc.
|
||||
app.on('before-quit', () => {
|
||||
macOsQuit = true;
|
||||
});
|
||||
}
|
||||
|
||||
app.on('activate', () => {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
if (win === null) {
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('ready', async () => {
|
||||
app.whenReady().then(async () => {
|
||||
if (isDevelopment) {
|
||||
try {
|
||||
await installExtension(VUEJS_DEVTOOLS);
|
||||
@@ -95,6 +73,13 @@ app.on('ready', async () => {
|
||||
}
|
||||
}
|
||||
createWindow();
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
// On macOS it's common to re-create a window in the app when the
|
||||
// dock icon is clicked and there are no other windows open.
|
||||
createWindow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Exit cleanly on request from parent process in development mode.
|
||||
@@ -156,3 +141,39 @@ function setupLogger(): void {
|
||||
log.transports.file.level = 'silly';
|
||||
log.eventLogger.startLogging();
|
||||
}
|
||||
|
||||
function configureAppQuitBehavior() {
|
||||
let macOsQuit = false;
|
||||
// Quit when all windows are closed.
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform === 'darwin'
|
||||
&& !macOsQuit) {
|
||||
/*
|
||||
On macOS it is common for applications and their menu bar
|
||||
to stay active until the user quits explicitly with Cmd + Q
|
||||
*/
|
||||
return;
|
||||
}
|
||||
app.quit();
|
||||
});
|
||||
if (process.platform === 'darwin') {
|
||||
/*
|
||||
On macOS we application quit is stopped if user does not Cmd + Q
|
||||
But we still want to be able to use app.quit() and quit the application
|
||||
on menu bar, after updates etc.
|
||||
*/
|
||||
app.on('before-quit', () => {
|
||||
macOsQuit = true;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function setAppName() {
|
||||
/*
|
||||
Set the app name in development mode to ensure correct userData path.
|
||||
Without this, `app.getPath('userData')` defaults to 'Electron'.
|
||||
*/
|
||||
if (isDevelopment) {
|
||||
app.setName(name); // Works only for Windows, unsolved for macOS.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { contextBridge } from 'electron';
|
||||
import { contextBridge } from 'electron/renderer';
|
||||
import { bindObjectMethods } from './MethodContextBinder';
|
||||
import { provideWindowVariables } from './RendererApiProvider';
|
||||
|
||||
|
||||
14
src/presentation/electron/preload/ContextBridging/README.md
Normal file
14
src/presentation/electron/preload/ContextBridging/README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Context Bridging Module
|
||||
|
||||
This module establishes secure, maintainable, and efficient inter-process communication between the preloader
|
||||
and renderer processes.
|
||||
|
||||
## Benefits
|
||||
|
||||
- **Security**: Exposes intended parts of an object to the renderer process, safeguarding the application's
|
||||
integrity and security.
|
||||
- **Type Safety and Maintainability**: Offers type-checked contracts for robust and easy-to-maintain code.
|
||||
- **Simplicity**: Streamlines the process of exposing APIs to the renderer process, minimizing the complexity
|
||||
of context bindings.
|
||||
- **Scalability**: Enhances the scalability of API exposure and simplifies managing more complex API structures,
|
||||
overcoming the limitations of ad-hoc approaches.
|
||||
@@ -1,27 +1,27 @@
|
||||
import { createElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
||||
import { TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { convertPlatformToOs } from './NodeOsMapper';
|
||||
import { convertPlatformToOs } from '@/infrastructure/RuntimeEnvironment/Node/NodeOsMapper';
|
||||
import { createIpcConsumerProxy } from '../../shared/IpcBridging/IpcProxy';
|
||||
import { IpcChannelDefinitions } from '../../shared/IpcBridging/IpcChannelDefinitions';
|
||||
import { createSecureFacade } from './SecureFacadeCreator';
|
||||
|
||||
export function provideWindowVariables(
|
||||
createCodeRunner: CodeRunnerFactory = () => new TemporaryFileCodeRunner(),
|
||||
createLogger: LoggerFactory = () => createElectronLogger(),
|
||||
convertToOs = convertPlatformToOs,
|
||||
createApiFacade: ApiFacadeFactory = createSecureFacade,
|
||||
ipcConsumerCreator: IpcConsumerProxyCreator = createIpcConsumerProxy,
|
||||
): WindowVariables {
|
||||
return {
|
||||
isDesktop: true,
|
||||
log: createApiFacade(createLogger(), ['info', 'debug', 'warn', 'error']),
|
||||
os: convertToOs(process.platform),
|
||||
codeRunner: createApiFacade(createCodeRunner(), ['runCode']),
|
||||
codeRunner: ipcConsumerCreator(IpcChannelDefinitions.CodeRunner),
|
||||
};
|
||||
}
|
||||
|
||||
export type LoggerFactory = () => Logger;
|
||||
|
||||
export type CodeRunnerFactory = () => CodeRunner;
|
||||
|
||||
export type ApiFacadeFactory = typeof createSecureFacade;
|
||||
|
||||
export type IpcConsumerProxyCreator = typeof createIpcConsumerProxy;
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { FunctionKeys } from '@/TypeHelpers';
|
||||
|
||||
export interface IpcChannel<T> {
|
||||
readonly namespace: string;
|
||||
readonly accessibleMembers: readonly FunctionKeys<T>[]; // Property keys are not yet supported
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { FunctionKeys } from '@/TypeHelpers';
|
||||
import { CodeRunner } from '@/application/CodeRunner';
|
||||
import { IpcChannel } from './IpcChannel';
|
||||
|
||||
export const IpcChannelDefinitions = {
|
||||
CodeRunner: defineElectronIpcChannel<CodeRunner>('code-run', ['runCode']),
|
||||
} as const;
|
||||
|
||||
function defineElectronIpcChannel<T>(
|
||||
name: string,
|
||||
functionNames: readonly FunctionKeys<T>[],
|
||||
): IpcChannel<T> {
|
||||
return {
|
||||
namespace: name,
|
||||
accessibleMembers: functionNames,
|
||||
};
|
||||
}
|
||||
48
src/presentation/electron/shared/IpcBridging/IpcProxy.ts
Normal file
48
src/presentation/electron/shared/IpcBridging/IpcProxy.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { ipcMain } from 'electron/main';
|
||||
import { ipcRenderer } from 'electron/renderer';
|
||||
import { isFunction } from '@/TypeHelpers';
|
||||
import { IpcChannel } from './IpcChannel';
|
||||
|
||||
export function createIpcConsumerProxy<T>(
|
||||
channel: IpcChannel<T>,
|
||||
electronIpcRenderer: Electron.IpcRenderer = ipcRenderer,
|
||||
): AsyncMethods<T> {
|
||||
const facade: Partial<T> = {};
|
||||
channel.accessibleMembers.forEach((member) => {
|
||||
const functionKey = member as string;
|
||||
const ipcChannel = getIpcChannelIdentifier(channel.namespace, functionKey);
|
||||
facade[functionKey] = ((...args: unknown[]) => {
|
||||
return electronIpcRenderer.invoke(ipcChannel, ...args);
|
||||
}) as AsyncMethods<T>[keyof T];
|
||||
});
|
||||
return facade as AsyncMethods<T>;
|
||||
}
|
||||
|
||||
export function registerIpcChannel<T>(
|
||||
channel: IpcChannel<T>,
|
||||
originalObject: T,
|
||||
electronIpcMain: Electron.IpcMain = ipcMain,
|
||||
) {
|
||||
channel.accessibleMembers.forEach((functionKey) => {
|
||||
const originalFunction = originalObject[functionKey];
|
||||
if (!isFunction(originalFunction)) {
|
||||
throw new Error('Non-function members are not yet supported');
|
||||
}
|
||||
const ipcChannel = getIpcChannelIdentifier(channel.namespace, functionKey as string);
|
||||
electronIpcMain.handle(ipcChannel, (_event, ...args: unknown[]) => {
|
||||
return originalFunction.apply(originalObject, args);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getIpcChannelIdentifier(namespace: string, key: string) {
|
||||
return `proxy:${namespace}:${key}`;
|
||||
}
|
||||
|
||||
type AsyncMethods<T> = {
|
||||
[P in keyof T]: T[P] extends (...args: infer Args) => infer R
|
||||
? R extends Promise<unknown>
|
||||
? (...args: Args) => R
|
||||
: (...args: Args) => Promise<R>
|
||||
: never;
|
||||
};
|
||||
17
src/presentation/electron/shared/IpcBridging/README.md
Normal file
17
src/presentation/electron/shared/IpcBridging/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# IPC bridging
|
||||
|
||||
This module introduces structured and type-safe inter-process communication (IPC) to Electron applications,
|
||||
enhancing the development and maintenance of complex features.
|
||||
|
||||
## Benefits
|
||||
|
||||
- **Type safety**: Ensures reliable data exchange between processes and prevents runtime errors through enforced
|
||||
type checks in IPC communication.
|
||||
- **Maintainability**: Facilitates easy tracking and management of inter-process contracts using defined and clear
|
||||
interfaces.
|
||||
- **Security**: Implements the least-privilege principle by defining which members are accessible in proxy objects,
|
||||
enhancing the security of IPC interactions.
|
||||
- **Simplicity**: Simplifies IPC calls by abstracting the underlying complexity, providing a more straightforward
|
||||
interface for developers.
|
||||
- **Scalability**: Structured IPC management supports effective scaling and reduces the challenges of ad-hoc
|
||||
IPC implementations.
|
||||
Reference in New Issue
Block a user