### Electron Main Process Setup (packages/desktop/main.js) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Initializes the Electron application's main process, including BrowserWindow creation, IPC handlers, service initialization, auto-updater, and loading the web app. ```javascript // Example snippet for main process setup import { app, BrowserWindow, ipcMain, autoUpdater } from 'electron'; import path from 'path'; // ... other imports and setup function createWindow() { const mainWindow = new BrowserWindow({ // ... BrowserWindow options }); // Load web application mainWindow.loadURL('file://' + path.join(__dirname, '../web-dist/index.html')); // Set up IPC handlers ipcMain.handle('some-channel', async (event, ...args) => { // handle IPC message return 'response'; }); // Initialize auto-updater // autoUpdater.setFeedURL({ url: 'YOUR_UPDATE_URL' }); } app.whenReady().then(() => { createWindow(); // ... other app setup }); ``` -------------------------------- ### Start MCP Server Commands (Shell) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Commands to start the MCP server for development and production. Development mode utilizes nodemon for hot reloading, while production mode runs the built server directly. ```shell # Development pnpm mcp:dev # Runs with nodemon hot reload # Production pnpm mcp:start # Runs built server ``` -------------------------------- ### Auto-Update Process Steps Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 The auto-update process, orchestrated by electron-updater, involves querying GitHub Releases, downloading platform-specific manifest files, comparing versions, downloading the appropriate installer, verifying checksums, and finally initiating the installation of the new version. ```javascript // Inside packages/desktop/main.js // ... autoUpdater.checkForUpdates(); // ... autoUpdater.quitAndInstall(); // ... ``` -------------------------------- ### Claude Desktop Services Configuration (JSON) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Example JSON configuration for integrating the MCP server with Claude Desktop. This involves adding a service entry with a name and the URL of the MCP server. The configuration file location varies by operating system. ```json { "services": [ { "name": "Prompt Optimizer", "url": "http://localhost:8081/mcp" } ] } ``` -------------------------------- ### Desktop-Specific Build Process Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Details the build process defined in packages/desktop/package.json. The 'build' script first executes 'build:web' which prepares the web assets for Electron, and then 'package' which uses electron-builder to bundle the application and generate platform-specific installers. ```json { "build": "pnpm run build:web && pnpm run package", "build:web": "cd ../web && cross-env ELECTRON_BUILD=true vite build --base=./ && node -e \"...\"", "package": "electron-builder" } ``` -------------------------------- ### Windows Platform-Specific Packaging Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Defines the packaging configuration for Windows builds, supporting both NSIS installer and portable zip artifact types. It specifies the target artifact types and the naming convention for generated files, along with an icon for the installer. The NSIS configuration further details installer options like one-click installation and directory selection. ```json { "win": { "target": ["nsis", "zip"], "artifactName": "${productName}-${version}-${os}-${arch}.${ext}", "icon": "icons/app-icon.ico" }, "nsis": { "oneClick": false, "allowToChangeInstallationDirectory": true } } ``` -------------------------------- ### Electron IPC Handler Examples Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 Demonstrates typical IPC handlers in the Electron main process for various operations like model import/update and preference import. It utilizes `safeSerialize` to prepare data and returns standardized success or error responses. ```javascript // Model import handleripcMain.handle('model-importData', async (event, data) => { try { const safeData = safeSerialize(data); await modelManager.importData(safeData); return createSuccessResponse(null); } catch (error) { return createErrorResponse(error); } }); // Model update handleripcMain.handle('model-updateModel', async (event, id, updates) => { try { const safeUpdates = safeSerialize(updates); await modelManager.updateModel(id, safeUpdates); return createSuccessResponse(null); } catch (error) { return createErrorResponse(error); } }); // Preference import handleripcMain.handle('preference-importData', async (event, data) => { try { const safeData = safeSerialize(data); await preferenceService.importData(safeData); return createSuccessResponse(null); } catch (error) { return createErrorResponse(error); } }); ``` -------------------------------- ### Auto-Update Configuration (JSON) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Configuration for the auto-update mechanism of the desktop application. It specifies GitHub Releases as the update server, requiring the provider to be 'github' and specifying the owner and repository of the project. Applications packaged with installers will automatically check for updates on startup. ```json { "publish": { "provider": "github", "owner": "linshenkx", "repo": "prompt-optimizer" } } ``` -------------------------------- ### macOS Platform-Specific Packaging Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Configures macOS builds to support both Intel (x64) and Apple Silicon (arm64) architectures. It specifies DMG and zip targets for each architecture, a standardized artifact name, and an icon file. The DMG format provides a standard macOS installation experience, though code signing and notarization are not performed by default. ```json { "mac": { "target": [ { "target": "dmg", "arch": ["x64", "arm64"] }, { "target": "zip", "arch": ["x64", "arm64"] } ], "artifactName": "${productName}-${version}-${os}-${arch}.${ext}", "icon": "icons/app-icon.icns" } } ``` -------------------------------- ### Extended Service Mapping for Future Extensions - TypeScript Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 This example illustrates how the service map can be extended to include additional services like ImageModelManager and FavoriteManager for bulk export/import operations. This demonstrates the extensibility of the data management system. ```typescript const serviceMap = [ // ... existing services ... { service: this.imageModelManager, dataKey: 'imageModels' }, { service: this.favoriteManager, dataKey: 'favorites' } ]; ``` -------------------------------- ### GitHub Releases API Query for Updates Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 The auto-update process queries the GitHub Releases API to fetch information about the latest release. This is typically done using a GET request to the 'latest' release endpoint for the repository. ```http GET https://api.github.com/repos/linshenkx/prompt-optimizer/releases/latest ``` -------------------------------- ### Manage Quick Templates Based on Optimization Mode Source: https://deepwiki.com/linshenkx/prompt-optimizer/3 Computes a list of quick templates based on the current `optimizationMode` prop. It filters predefined templates ('system' or 'user') to provide relevant starting points for conversations. The `applyQuickTemplate` function updates the message list with a selected template. ```vue const quickTemplates = computed(() => { const mode = props.optimizationMode || 'system' // Filter templates by optimization mode const templates = { system: [ { key: 'systemDefault', messages: [...] }, { key: 'systemRoleTest', messages: [...] }, { key: 'systemMultiTurnTest', messages: [...] } ], user: [ { key: 'userSimpleTest', messages: [...] }, { key: 'userWithContext', messages: [...] }, { key: 'userDialogue', messages: [...] } ] } return templates[mode] }) const applyQuickTemplate = (template: QuickTemplate) => { localState.value.messages = template.messages.map(m => ({ id: uuidv4(), role: m.role, content: m.content })) } ``` -------------------------------- ### Build Desktop Application (Shell) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Builds the desktop application by first compiling the web application with ELECTRON_BUILD set to true, copying the web distribution to the desktop package, and then using electron-builder to package the application. This process supports multiple build targets including Windows, macOS, and Linux. ```shell pnpm build:desktop # 1. Builds web application with ELECTRON_BUILD=true # 2. Copies web dist to packages/desktop/web-dist/ # 3. Runs electron-builder to package ``` -------------------------------- ### Initialize FileStorageProvider in Desktop Application Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 Demonstrates the initialization of the FileStorageProvider in the Electron main process for the desktop application. It uses the app.getPath('userData') to determine the storage location. Atomic write operations and backup mechanisms are employed for data integrity. Sources: packages/desktop/main.js. ```javascript // Desktop initialization sequence const userDataPath = app.getPath('userData'); // Platform-specific paths: // - Windows: C:\Users\{user}\AppData\Roaming\Prompt Optimizer // - macOS: ~/Library/Application Support/Prompt Optimizer // - Linux: ~/.config/prompt-optimizer storageProvider = new FileStorageProvider(userDataPath); ``` -------------------------------- ### Vercel Deployment Pipeline Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5-deployment-and-configuration Customizes the Vercel deployment pipeline for a monorepo. It specifies build and install commands, output directories, rewrites for SPA routing, and environment variables for conditional behavior. ```yaml "Vercel-Specific Configuration: * **Build Command** : Handles both root and extension directory contexts * **Install Command** : Adds `@vercel/analytics` workspace dependency * **Output Directory** : Always `packages/web/dist` * **Rewrites** : SPA routing with API passthrough * **Environment** : `VITE_VERCEL_DEPLOYMENT=true` flag for conditional behavior" ``` -------------------------------- ### Electron Builder Configuration (JSON) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4 Configures the Electron Builder settings for packaging the desktop application. Specifies application ID, product name, output directories, files to include, and platform-specific build targets for Windows, macOS, and Linux. ```json { "appId": "com.promptoptimizer.desktop", "productName": "PromptOptimizer", "directories": { "output": "dist" }, "files": [ "main.js", "preload.js", "config/**/*", "web-dist/**/*", "node_modules/**/*" ], "win": { "target": ["nsis", "zip"], "artifactName": "${productName}-${version}-${os}-${arch}.${ext}", "icon": "icons/app-icon.ico" }, "mac": { "target": [ { "target": "dmg", "arch": ["x64", "arm64"] }, { "target": "zip", "arch": ["x64", "arm64"] } ], "icon": "icons/app-icon.icns" }, "linux": { "target": ["AppImage", "zip"], "icon": "icons/" } } ``` -------------------------------- ### Build Packaging Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/4 Specifies the build and packaging configuration for the desktop application using `electron-builder`, as defined in the `package.json` file. ```json // Source: packages/desktop/package.json10-99 // Configuration for electron-builder is typically found here. ``` -------------------------------- ### Vue: Get Message Variables Source: https://deepwiki.com/linshenkx/prompt-optimizer/3 A utility function to extract detected and missing variables from a given message content using the provided scanVariables function and availableVariables map. Returns an object containing arrays of detected and missing variable names. ```javascript const getMessageVariables = (content: string) => { if (!scanVariables) return { detected: [], missing: [] } const detected = scanVariables(content) const missing = detected.filter(v => !availableVariables[v]) return { detected, missing } } ``` -------------------------------- ### Define IStorageProvider Interface for Data Persistence Source: https://deepwiki.com/linshenkx/prompt-optimizer/2-core-services-layer Defines the interface for storage providers, enabling platform-specific data persistence. It includes basic operations like getting, setting, and removing items, as well as an advanced operation for atomic read-modify-write using a StorageAdapter. ```typescript interface IStorageProvider { getItem(key: string): Promise setItem(key: string, value: string): Promise removeItem(key: string): Promise // Advanced operations (via StorageAdapter) updateData(key: string, updater: (current: T | null) => T): Promise } ``` -------------------------------- ### Build and Development Scripts (npm/pnpm) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4 Defines scripts for building the web application, packaging the desktop app, and running in development mode. Uses pnpm for package management and cross-env for setting environment variables. ```json { "build": "pnpm run build:web && pnpm run package", "build:web": "cd ../web && cross-env ELECTRON_BUILD=true vite build --base=./ && ...", "package": "electron-builder", "dev": "cross-env NODE_ENV=development electron ." } ``` -------------------------------- ### Nginx Configuration for MCP Server (Nginx Config) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Nginx configuration to route requests starting with `/mcp` to the MCP server running on `http://localhost:3000`. This enables path-based routing for both the web UI and the MCP server through a single entry point, essential for Docker deployments. ```nginx location /mcp { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; } ``` -------------------------------- ### Root package.json Build Script Definitions Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Defines the core build scripts in the root package.json. 'build:desktop-only' specifically targets the desktop build using pnpm, while 'build:desktop' orchestrates a complete build sequence including core, UI, web, and desktop-only components using npm-run-all. ```json { "build:desktop-only": "pnpm -F @prompt-optimizer/desktop build", "build:desktop": "npm-run-all build:core build:ui build:web build:desktop-only" } ``` -------------------------------- ### GitHub Release Publishing Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Configures the application to publish updates through GitHub Releases. Specifies the provider, owner, repository, and whether the repository is private. This enables automatic updates from the designated GitHub repository. ```json { "publish": { "provider": "github", "owner": "linshenkx", "repo": "prompt-optimizer", "private": false } } ``` -------------------------------- ### Create DataManager Instance Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 Illustrates the instantiation of the DataManager using a factory function during application initialization. It shows the dependencies required for creating a DataManager instance. ```javascript // From useAppInitializer or equivalent const dataManager = createDataManager( modelManager, templateManager, historyManager, preferenceService, contextRepo ); ``` -------------------------------- ### Download Build Artifacts (YAML) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 A GitHub Actions step to download all build artifacts generated by previous jobs. The artifacts are downloaded into the './artifacts' directory, making them available for subsequent release creation steps. ```yaml - name: Download all build artifacts uses: actions/download-artifact@v4 with: path: ./artifacts ``` -------------------------------- ### Define IImportExportable Interface for Data Serialization (TypeScript) Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 The `IImportExportable` interface defines the contract for services participating in bulk import and export operations. It standardizes methods for exporting, importing, getting data types, and validating data, enabling the `DataManager` to orchestrate these processes. ```typescript /** * Interface for services that can be exported and imported. */ interface IImportExportable { /** * Exports the service's data in a serializable format. * @returns A promise that resolves with the exported data. */ exportData(): Promise; /** * Imports data into the service. * @param data The data to import, expected to be in a serializable format. * @returns A promise that resolves when the data has been imported. */ importData(data: any): Promise; /** * Returns a string identifier for the type of data this service handles. * Useful for error reporting and identification during import/export. * @returns A promise that resolves with the data type string. */ getDataType(): Promise; /** * Validates the provided data before it is imported. * @param data The data to validate. * @returns A promise that resolves with a boolean indicating whether the data is valid. */ validateData(data: any): Promise; } // Example of how a service might implement this interface: // class MyService implements IImportExportable { // async exportData(): Promise { /* ... */ return {}; } // async importData(data: any): Promise { /* ... */ } // async getDataType(): Promise { return "myDataType"; } // async validateData(data: any): Promise { return true; } // } ``` -------------------------------- ### Electron-Builder Dependency Bundling Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 This configuration snippet for electron-builder specifies which files and directories, including all node_modules, are included in the Electron application's distribution. This ensures the application is self-contained but increases package size. Native modules are automatically rebuilt for the target Electron version. ```json { "files": [ "main.js", "preload.js", "config/**/*", "web-dist/**/*", "node_modules/**/*" ] } ``` -------------------------------- ### Initialize DataManager Services - JavaScript Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 This JavaScript function demonstrates the initialization sequence for DataManager services within a desktop application's main process. It includes setting up storage, individual services, and finally creating the DataManager instance with all its dependencies. ```javascript // From desktop/main.js:initializeServices() async function initializeServices() { // Initialize storage provider storageProvider = new FileStorageProvider(userDataPath); // Initialize individual services await initializePreferenceService(storageProvider); modelManager = createModelManager(storageProvider); templateLanguageService = createTemplateLanguageService(preferenceService); await templateLanguageService.initialize(); templateManager = createTemplateManager(storageProvider, templateLanguageService); historyManager = createHistoryManager(storageProvider, modelManager); contextRepo = createContextRepo(storageProvider); // Create DataManager with all dependencies dataManager = createDataManager( modelManager, templateManager, historyManager, preferenceService, contextRepo ); console.log('[Main Process] Core services initialized successfully.'); } ``` -------------------------------- ### Define IPC Event Constants for Updates (JavaScript) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Defines a comprehensive set of Inter-Process Communication (IPC) event constants used between the main and renderer processes for managing application updates. These constants facilitate communication for checking updates, downloading, installing, and handling update-related information. ```javascript const IPC_EVENTS = { UPDATE_CHECK: 'updater-check-update', UPDATE_START_DOWNLOAD: 'updater-start-download', UPDATE_INSTALL: 'updater-install-update', UPDATE_IGNORE_VERSION: 'updater-ignore-version', UPDATE_UNIGNORE_VERSION: 'updater-unignore-version', UPDATE_GET_IGNORED_VERSIONS: 'updater-get-ignored-versions', UPDATE_DOWNLOAD_SPECIFIC_VERSION: 'updater-download-specific-version', UPDATE_CHECK_ALL_VERSIONS: 'updater-check-all-versions', // Main → Renderer events UPDATE_AVAILABLE_INFO: 'update-available-info', UPDATE_NOT_AVAILABLE: 'update-not-available', UPDATE_DOWNLOAD_PROGRESS: 'update-download-progress', UPDATE_DOWNLOADED: 'update-downloaded', UPDATE_ERROR: 'update-error', UPDATE_DOWNLOAD_STARTED: 'updater-download-started' }; ``` -------------------------------- ### Window Lifecycle and Data Persistence Mechanisms in Electron Source: https://deepwiki.com/linshenkx/prompt-optimizer/4 To prevent data loss, the application implements several safety mechanisms before closing. These include an emergency exit timer, a force quit timer for slow saves, a promise race for timeouts during data saving, and bypassing saves during auto-update installations to ensure data integrity and a smooth user experience. ```javascript const { app, BrowserWindow } = require('electron'); let mainWindow; app.on('before-quit', async (event) => { event.preventDefault(); // Prevent immediate quit // Safety mechanisms before saving data const emergencyExitTimer = setTimeout(() => { console.error('Emergency exit: Save operation timed out.'); app.exit(1); }, 10000); // 10 seconds const forceQuitTimer = setTimeout(() => { console.error('Force quit: Save operation took too long.'); // Destroy window if save is taking too long if (mainWindow) { mainWindow.destroy(); } app.exit(1); }, 5000); // 5 seconds try { // Simulate data saving operation with timeout protection await Promise.race([ saveAllData(), // Assume this returns a promise new Promise((_, reject) => setTimeout(() => reject(new Error('Save timeout')), 7000)) ]); clearTimeout(emergencyExitTimer); clearTimeout(forceQuitTimer); app.quit(); // Proceed with quit only if save is successful } catch (error) { console.error('Error during save:', error.message); clearTimeout(emergencyExitTimer); clearTimeout(forceQuitTimer); // Optionally attempt to save critical data or exit forcefully app.exit(1); } }); async function saveAllData() { // Placeholder for actual data saving logic console.log('Saving application data...'); await new Promise(resolve => setTimeout(resolve, 3000)); // Simulate async save console.log('Data saved.'); } // Logic to bypass save during update installation let isUpdating = false; // ... updater logic ... app.on('before-quit', async (event) => { if (isUpdating) { console.log('Skipping save during update installation.'); return; } // ... rest of the save logic ... }); ``` -------------------------------- ### Create GitHub Release (YAML) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 A GitHub Actions step that utilizes the 'softprops/action-gh-release' action to create a new release on GitHub. It uses outputs from previous steps for the release name, tag, body, and includes all artifacts from the './artifacts' directory. ```yaml - name: Create GitHub Release uses: softprops/action-gh-release@v2 with: name: ${{ steps.version.outputs.release_name_prefix }}${{ steps.version.outputs.version }} tag_name: ${{ steps.version.outputs.version }} body: ${{ steps.release_notes.outputs.notes }} files: ./artifacts/**/* prerelease: ${{ steps.version.outputs.is_prerelease }} draft: false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ``` -------------------------------- ### Service Level Error Collection in TypeScript Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 This example illustrates error collection at the service level, specifically within TemplateManager's importData function. It collects failed template imports in a 'failedTemplates' array. This approach allows for partial success, as the process continues even if some templates fail to import, and only a warning is logged. ```typescript // From TemplateManager.importData() const failedTemplates: { template: Template; error: Error }[] = []; for (const template of templates) { try { await this.saveTemplate(userTemplate); } catch (error) { failedTemplates.push({ template, error: error as Error }); } } if (failedTemplates.length > 0) { console.warn(`Failed to import ${failedTemplates.length} templates`); // Continues without throwing - partial success allowed } ``` -------------------------------- ### Development vs. Production Window Loading (JavaScript) Source: https://deepwiki.com/linshenkx/prompt-optimizer/4 Handles how the main window loads content based on the environment. In development, it loads from a local Vite server and opens DevTools. In production, it loads the built HTML file from the 'web-dist' directory. ```javascript // Window loading logic (main.js:352-366) if (process.env.NODE_ENV === 'development') { mainWindow.loadURL('http://localhost:18181'); mainWindow.webContents.openDevTools(); } else { const webDistPath = path.join(__dirname, 'web-dist/index.html'); mainWindow.loadFile(webDistPath); } ``` -------------------------------- ### Build and Distribution Source: https://deepwiki.com/linshenkx/prompt-optimizer/4-platform-implementations Details on how the desktop application is built and distributed, including build targets and the auto-update configuration. ```APIDOC ## Build and Distribution ### Build Configuration - Uses `electron-builder` for packaging. ### Build Targets - **Windows**: NSIS installer + ZIP archive - **macOS**: DMG + ZIP archive (x64 and arm64) - **Linux**: AppImage + ZIP archive ### Build Process 1. Run `pnpm build:desktop`. 2. Builds the web application with `ELECTRON_BUILD=true`. 3. Copies the web distribution to `packages/desktop/web-dist/`. 4. Executes `electron-builder` to package the application. ### Auto-Update Configuration - **Provider**: GitHub - **Repository**: `linshenkx/prompt-optimizer` - Auto-update uses GitHub Releases. Desktop apps with installers (not ZIP) automatically check for updates on startup. ``` -------------------------------- ### Package.json Version Scripts (JSON) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Scripts defined in package.json for managing version synchronization and tagging. These scripts automate the process of updating versions, staging changes, and preparing for releases. ```json "version:sync": "node scripts/sync-versions.js", "version": "pnpm run version:sync && git add -A", "version:prepare": "pnpm version --no-git-tag-version", "version:tag": "git tag v$(node -p \"require('./package.json').version\")", "version:publish": "git push origin v$(node -p \"require('./package.json').version\")" ``` -------------------------------- ### File Storage Provider Structure Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 The FileStorageProvider organizes user data in a standardized directory structure across different operating systems. This ensures data persistence, multi-user support, and ease of backup/restore. The structure includes configurations for text and image models, user templates, history, preferences, contexts, and favorites. ```text {userData}/ ├── models.json ├── imageModels.json ├── templates.json ├── history.json ├── preferences.json ├── contexts.json └── favorites.json ``` -------------------------------- ### Auto-Detect Repository Info (PowerShell) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Automatically detects GitHub repository information, including the full URL, owner, and name. This is used to dynamically configure package details during the release process. It relies on GitHub Actions context variables. ```powershell $repoUrl = "https://github.com/${{ github.repository }}.git" $repoInfo = "${{ github.repository }}".split("/") $repoOwner = $repoInfo[0] $repoName = $repoInfo[1] ``` -------------------------------- ### Update Publish Configuration (PowerShell) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Updates the publish configuration for the package, setting the provider to 'github' and including the detected repository owner and name. This enables forks to automatically configure the correct repository for distribution. ```powershell $publishConfig = @{ provider = "github" owner = $repoOwner repo = $repoName private = $False } $pkgJson.build.publish = $publishConfig ``` -------------------------------- ### Linux Platform-Specific Packaging Configuration Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Specifies the packaging configuration for Linux builds, generating both AppImage (universal self-contained format) and zip archive types. It defines the target formats, artifact naming convention, and an icon directory. AppImage offers a portable, distribution-agnostic execution method. ```json { "linux": { "target": ["AppImage", "zip"], "artifactName": "${productName}-${version}-${os}-${arch}.${ext}", "icon": "icons/" } } ``` -------------------------------- ### Renderer Process Electron API Wrapper Source: https://deepwiki.com/linshenkx/prompt-optimizer/2 Shows how the preload script exposes IPC functionalities to the renderer process via `window.electronAPI`. This wrapper provides a clean interface for calling main process IPC handlers and handling their results or errors. ```javascript // Preload.js exposure contextBridge.exposeInMainWorld('electronAPI', { model: { importData: async (data) => { const result = await ipcRenderer.invoke('model-importData', data); if (!result.success) { throw new Error(result.error); } }, exportData: async () => { const result = await ipcRenderer.invoke('model-exportData'); if (!result.success) { throw new Error(result.error); } return result.data; } } }); ``` -------------------------------- ### Desktop Package Dependencies (JSON) Source: https://deepwiki.com/linshenkx/prompt-optimizer/5 Lists the runtime and development dependencies for the desktop application package. Runtime dependencies include core libraries and utilities like dotenv, electron-log, and electron-updater. Development dependencies include tools for building and packaging, such as electron and electron-builder. ```json "dependencies": { "@prompt-optimizer/core": "workspace:*", "dotenv": "^16.0.0", "electron-log": "^5.4.1", "electron-updater": "6.3.9", "node-fetch": "^2.7.0", "undici": "^6.19.8" } ``` ```json "devDependencies": { "cross-env": "^7.0.3", "electron": "^37.1.0", "electron-builder": "^24.0.0" } ``` -------------------------------- ### Set Pro Sub Mode with Persistence (TypeScript) Source: https://deepwiki.com/linshenkx/prompt-optimizer/1 This function handles the logic for switching and persisting the pro sub-mode. It ensures initialization, updates the singleton mode value, saves the preference using PreferenceService, logs the change, and triggers reactivity. This is crucial for maintaining user state across sessions. ```typescript const setProSubMode = async (mode: ProSubMode) => { await ensureInitialized() singleton!.mode.value = mode await setPreference(UI_SETTINGS_KEYS.PRO_SUB_MODE, mode) console.log(`[useProSubMode] 子模式已切换并持久化: ${mode}`) } ```