repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
LynxHub
github_2023
KindaBrazy
typescript
GitManager.getLastPulledDate
public static async getLastPulledDate(repoDir: string): Promise<string> { try { const status = await simpleGit(repoDir).log(['-1', '--format=%cd', '--date=format:%Y-%m-%d %H:%M:%S']); return status.latest?.hash ?? ''; } catch (error) { console.error('Error getting last pulled date:', error); return ''; } }
/** * Gets the date of the last pull for a repository. * @param repoDir - The directory of the local repository. * @returns A promise that resolves to the date string or an empty string if not found. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L81-L89
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.getCurrentReleaseTag
public static async getCurrentReleaseTag(repoDir: string): Promise<string> { try { const describeOutput = await simpleGit(repoDir).raw(['describe', '--tags', '--abbrev=0']); return describeOutput.trim() || 'No tag found'; } catch (error) { console.error('Error getting current release tag:', error); return 'No tag found'; } }
/** * Gets the current release tag of a repository. * @param repoDir - The directory of the local repository. * @returns A promise that resolves to the tag or 'No tag found' if not available. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L96-L104
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.isUpdateAvailable
public static async isUpdateAvailable(repoDir: string | undefined): Promise<boolean> { if (!repoDir) return false; try { const status: StatusResult = await simpleGit(path.resolve(repoDir)).remote(['update']).status(); return status.behind > 0; } catch (error) { console.error('Error checking for updates:', error, repoDir); return false; } }
/** * Checks if updates are available for a repository. * @param repoDir - The directory of the local repository. * @returns A promise that resolves to true if updates are available, false otherwise. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L111-L120
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.isDirRepo
public static async isDirRepo(dir: string): Promise<boolean> { if (!(await checkPathExists(dir))) return false; try { return await simpleGit(dir).checkIsRepo(CheckRepoActions.IS_REPO_ROOT); } catch (error) { console.error('Error checking if directory is a repo:', error); return false; } }
/** * Checks if a directory is a Git repository. * @param dir - The directory to check. * @returns A promise that resolves to true if the directory is a Git repository, false otherwise. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L127-L135
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.formatGitUrl
public static formatGitUrl(url: string): string | undefined { const githubRegex = /^https:\/\/github\.com\/.+$/; if (!githubRegex.test(url)) { console.log(`This url: ${url} isn't a GitHub Repository`); return undefined; } return url.endsWith('.git') ? url.slice(0, -4) : url; }
/** * Formats a GitHub URL by removing the '.git' suffix if present. * @param url - The URL to format. * @returns The formatted URL or undefined if not a valid GitHub URL. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L142-L149
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.remoteUrlFromDir
public static async remoteUrlFromDir(dir: string): Promise<string | undefined> { const result: RemoteWithRefs[] = await simpleGit(dir).getRemotes(true); return GitManager.formatGitUrl(result[0]?.refs.fetch); }
/** * Gets the remote URL for a local repository directory. * @param dir - The directory of the local repository. * @returns A promise that resolves to the formatted remote URL or undefined. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L156-L159
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.clone
public async clone(url: string, directory: string): Promise<void> { const targetDirectory = path.resolve(directory); return new Promise((resolve, reject) => { this.git .clone(url, targetDirectory) .then(() => { this.handleProgressComplete(); resolve(); }) .catch(error => { this.handleError(error); reject(error); }); }); }
/** * Clones a repository to the specified directory. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L198-L213
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.pull
public async pull(dir: string): Promise<void> { try { const result = await simpleGit(dir, {progress: this.handleProgressUpdate}).pull(); this.handleProgressComplete(result); } catch (error) { this.handleError(error); } }
/** * Pulls the latest changes from the remote repository. * @param dir - The directory of the local repository. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L507-L514
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.pullAsync
public async pullAsync(dir: string): Promise<boolean> { try { const result = await simpleGit(dir, {progress: this.handleProgressUpdate}).pull(); const {changes, insertions, deletions} = result.summary; return changes > 0 || insertions > 0 || deletions > 0; } catch { return false; } }
/** * Pulls the latest changes and returns whether updates were received. * @param dir - The directory of the local repository. * @returns A promise that resolves to true if updates were received false otherwise. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L521-L529
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
GitManager.abort
public abort(): void { this.abortController.abort(); }
/** Aborts the current Git operation. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/GitManager.ts#L532-L534
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
PtyManager.constructor
constructor() { this.isRunning = false; this.shell = determineShell(); }
//#region Constructor
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/PtyManager.ts#L27-L30
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
PtyManager.isAvailable
private isAvailable(): boolean { return this.isRunning && !!this.process?.pid; }
/** * Checks if the PTY process is available. * @returns True if the process is running and has a valid PID, false otherwise. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/PtyManager.ts#L40-L42
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
PtyManager.start
public start(dir?: string, sendDataToRenderer = false): void { const {useConpty} = storageManager.getData('terminal'); this.process = pty.spawn(this.shell, [], { cwd: dir ? path.resolve(dir) : undefined, cols: 150, rows: 150, env: process.env, useConpty: useConpty === 'auto' ? undefined : useConpty === 'yes', }); this.isRunning = true; this.process.onData(data => { if (this.onData) { this.onData(data); } else if (sendDataToRenderer) { appManager.getWebContent()?.send(ptyChannels.onData, data); } }); }
/** * Starts a new PTY process. * @param dir - The working directory for the PTY process. * @param sendDataToRenderer - Whether to send data to the renderer process. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/PtyManager.ts#L53-L72
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
PtyManager.stop
public stop(): void { if (this.isAvailable() && this.process?.pid) { treeKill(this.process.pid); if (platform() === 'darwin') this.process.kill(); this.isRunning = false; this.process = undefined; } }
/** * Stops the current PTY process. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/PtyManager.ts#L77-L84
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
PtyManager.resize
public resize(cols: number, rows: number): void { if (this.isAvailable()) { this.process?.resize(cols, rows); } }
/** * Resizes the PTY process window. * @param cols - Number of columns. * @param rows - Number of rows. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/PtyManager.ts#L91-L95
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
PtyManager.write
public write(data: string | string[]): void { if (!this.isAvailable()) return; if (Array.isArray(data)) { data.forEach(text => this.process?.write(text)); } else { this.process?.write(data); } }
/** * Writes data to the PTY process. * @param data - The data to write, either a string or an array of strings. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/PtyManager.ts#L101-L109
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
TrayManager.constructor
constructor(trayIcon: string, trayIconMenu: string) { this.trayIcon = trayIcon; this.trayIconMenu = trayIconMenu; }
/** * Creates a new TrayManager instance. * @param trayIcon - Path to the tray icon image. * @param trayIconMenu - Path to the icon used in the context menu. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/TrayManager.ts#L25-L28
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
TrayManager.closeMainWindow
private closeMainWindow = (): void => { appManager.getMainWindow()?.close(); }
/** Closes the main application window. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/TrayManager.ts
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
TrayManager.createTrayIcon
public createTrayIcon(): void { if (this.tray) return; const icon = os.platform() === 'win32' ? this.trayIcon : this.trayIconMenu; this.tray = new Tray(icon); this.tray.setToolTip(APP_NAME); const staticItems: EMenuItem[] = [ {enabled: false, icon: this.trayIconMenu, label: APP_NAME_VERSION}, {type: 'separator'}, {label: 'Show', type: 'normal', click: this.showMainWindow}, {label: 'Quit', type: 'normal', click: this.closeMainWindow}, ]; const resultItems = extensionManager.getTrayItems(staticItems); const contextMenu = Menu.buildFromTemplate(resultItems); this.tray.setContextMenu(contextMenu); this.tray.on('double-click', this.showMainWindow); }
/** Creates and sets up the tray icon with its context menu. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/TrayManager.ts#L48-L68
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
TrayManager.destroyTrayIcon
public destroyTrayIcon(): void { if (!this.tray) return; this.tray.destroy(); this.tray = undefined; }
/** Destroys the tray icon, removing it from the system tray. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/TrayManager.ts#L71-L76
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
getRepoFolders
async function getRepoFolders(dir: string): Promise<string[]> { try { const files = await fs.promises.readdir(dir, {withFileTypes: true}); const folders = files.filter(file => file.isDirectory()).map(file => file.name); if (folders.length === 0) return []; const repoFolders = await Promise.all( folders.map(async folder => { const isRepo = await GitManager.isDirRepo(path.join(dir, folder)); return isRepo ? folder : null; }), ); return repoFolders.filter(Boolean) as string[]; } catch (error) { console.error(`Error retrieving repository folders from ${dir}:`, error); return []; } }
/** * Retrieves repository folders from a given directory. * @param dir - The directory to search for repositories. * @returns A promise that resolves to an array of repository folder names. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Ipc/Methods/IpcMethods-CardExtensions.ts#L21-L40
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
parseWindowsBuildNumber
function parseWindowsBuildNumber(releaseString: string): number { const buildNumber = releaseString.split('.')[2]; return parseInt(buildNumber, 10); }
/** * Parses the Windows build number from the release string. * @param releaseString - The Windows release string. * @returns The parsed build number. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Ipc/Methods/IpcMethods-Platform.ts#L10-L13
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
runMultiCommand
function runMultiCommand(commands: string[]): void { if (!lodash.isEmpty(commands) && ptyManager) { commands.forEach(command => ptyManager?.write(`${command}${LINE_ENDING}`)); } }
/** * Runs multiple commands in the PTY. * @param commands - An array of commands to run. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Ipc/Methods/IpcMethods-Pty.ts#L19-L23
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
runPreOpen
function runPreOpen(cardId: string): void { const preOpens = storageManager.getPreOpenById(cardId); if (preOpens) { preOpens.data.forEach(toOpen => shell.openPath(toOpen.path)); } }
/** * Open pre-open array in desktop's default manner for a given card. * @param cardId - The ID of the card. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Ipc/Methods/IpcMethods-Pty.ts#L29-L34
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
setupGitManagerListeners
function setupGitManagerListeners(manager: GitManager, id?: string): void { manager.onProgress = (progress: SimpleGitProgressEvent) => { appManager.getWebContent()?.send(gitChannels.onProgress, id, 'Progress', progress); }; manager.onComplete = (result?: any) => { appManager.getWebContent()?.send(gitChannels.onProgress, id, 'Completed', result); }; manager.onError = (reason: string) => { appManager.getWebContent()?.send(gitChannels.onProgress, id, 'Failed', reason); }; }
/** * Sets up listeners for GitManager instance. * @param manager - The GitManager instance. * @param id - Optional identifier for pull operations. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Ipc/Methods/IpcMethods-Repository.ts#L79-L91
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
ExtensionManager.setStorageManager
public setStorageManager(manager: StorageManager) { this.extensionUtils.setStorageManager(manager); }
//#region Utils
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Plugin/Extensions/ExtensionManager.ts#L67-L69
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
ExtensionManager.listenForChannels
public listenForChannels() { this.extensionApi.listenForChannels(); }
//#region Api
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Plugin/Extensions/ExtensionManager.ts#L86-L88
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
BaseStorage.constructor
constructor() { // @ts-ignore this.storage = JSONFileSyncPreset<StorageTypes>(this.STORAGE_PATH, this.DEFAULT_DATA); this.storage.read(); this.migration(); }
//#region Constructor
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/BaseStorage.ts#L93-L98
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
BaseStorage.migration
private migration() { const storeVersion = this.getData('storage').version; const version4to5 = () => { this.storage.data.terminal = this.DEFAULT_DATA.terminal; this.storage.write(); }; const version5to6 = () => { this.storage.data.cards.duplicated = []; this.storage.write(); }; const updateVersion = () => { this.updateData('storage', {version: this.CURRENT_VERSION}); }; if (storeVersion < this.CURRENT_VERSION) { switch (storeVersion) { case 0.4: { version4to5(); version5to6(); break; } case 0.5: { version5to6(); break; } default: break; } updateVersion(); } }
//#region Private Methods
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/BaseStorage.ts#L104-L138
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
BaseStorage.getData
public getData<K extends keyof StorageTypes>(key: K): StorageTypes[K] { return this.storage.data[key]; }
//#region Public Methods
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/BaseStorage.ts#L144-L146
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.constructor
constructor() { super(); }
//#region Constructor
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L23-L25
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.getPreCommands
private getPreCommands(id: string): string[] { return this.getData('cardsConfig').preCommands.find(preCommand => preCommand.cardId === id)?.data || []; }
//#region Private Methods
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L31-L33
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.getPreOpenById
public getPreOpenById(cardId: string) { return this.getData('cardsConfig').preOpen.find(preOpen => preOpen.cardId === cardId); }
//#region Getter
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L64-L66
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.updateZoomFactor
public updateZoomFactor(data: {id: string; zoom: number}) { const zoomFactor = this.getData('cards').zoomFactor; const existZoom = zoomFactor.findIndex(zoom => zoom.id === data.id); if (existZoom !== -1) { zoomFactor[existZoom].zoom = data.zoom; } else { zoomFactor.push(data); } this.updateData('cards', {zoomFactor}); }
//#region Public Methods
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L113-L125
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addInstalledCard
public addInstalledCard(card: InstalledCard) { const storedCards = this.getData('cards').installedCards; const cardExists = storedCards.some(c => c.id === card.id); if (!cardExists) { const result: InstalledCards = [...storedCards, card]; this.updateData('cards', {installedCards: result}); appManager.getWebContent()?.send(storageUtilsChannels.onInstalledCards, result); } cardsValidator.changedCards(); }
//#region Installed Cards
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L129-L142
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addAutoUpdateCard
public addAutoUpdateCard(cardId: string) { const storedAutoUpdateCards = this.getData('cards').autoUpdateCards; const cardExists = lodash.includes(storedAutoUpdateCards, cardId); if (!cardExists) { const result: string[] = [...storedAutoUpdateCards, cardId]; this.updateData('cards', {autoUpdateCards: [...storedAutoUpdateCards, cardId]}); appManager.getWebContent()?.send(storageUtilsChannels.onAutoUpdateCards, result); } }
//#region Auto Update Cards
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L164-L176
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addAutoUpdateExtensions
public addAutoUpdateExtensions(cardId: string) { const storedAutoUpdateExtensions = this.getData('cards').autoUpdateExtensions; const extensionsExists = lodash.includes(storedAutoUpdateExtensions, cardId); if (!extensionsExists) { const result: string[] = [...storedAutoUpdateExtensions, cardId]; this.updateData('cards', {autoUpdateExtensions: [...storedAutoUpdateExtensions, cardId]}); appManager.getWebContent()?.send(storageUtilsChannels.onAutoUpdateExtensions, result); } }
//#region Auto Update Extensions
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L192-L204
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addPinnedCard
public addPinnedCard(cardId: string) { const storedPinnedCards = this.getData('cards').pinnedCards; const cardExists = lodash.includes(storedPinnedCards, cardId); if (!cardExists) { const result: string[] = [...storedPinnedCards, cardId]; this.updateData('cards', {pinnedCards: [...storedPinnedCards, cardId]}); appManager.getWebContent()?.send(storageUtilsChannels.onPinnedCardsChange, result); } }
//#region Pinned Cards
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L220-L232
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.updateRecentlyUsedCards
public updateRecentlyUsedCards(id: string) { const newArray = _.without(this.getData('cards').recentlyUsedCards, id); // Add the id to the beginning of the array newArray.unshift(id); // Keep only the last 5 elements const result = _.take(newArray, 5); this.updateData('cards', {recentlyUsedCards: result}); appManager.getWebContent()?.send(storageUtilsChannels.onRecentlyUsedCardsChange, result); }
//#region Recently Used Cards
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L273-L283
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.setHomeCategory
public setHomeCategory(data: string[]) { this.updateData('app', {homeCategory: data}); appManager.getWebContent()?.send(storageUtilsChannels.onHomeCategory, data); }
//#region Home Category
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L305-L308
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addPreCommand
public addPreCommand(cardId: string, command: string): void { const preCommands = this.getData('cardsConfig').preCommands; const existCommand = preCommands.findIndex(command => command.cardId === cardId); let commands: string[]; if (existCommand !== -1) { preCommands[existCommand].data.push(command); commands = preCommands[existCommand].data; } else { commands = [command]; preCommands.push({cardId, data: [command]}); } appManager.getWebContent()?.send(storageUtilsChannels.onPreCommands, {commands, id: cardId}); this.updateData('cardsConfig', {preCommands}); }
//#region Pre Commands
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L330-L347
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addCustomRun
public addCustomRun(cardId: string, command: string): void { const customRun = this.getData('cardsConfig').customRun; const existCustomRun = customRun.findIndex(custom => custom.cardId === cardId); let custom: string[]; if (existCustomRun !== -1) { customRun[existCustomRun].data.push(command); custom = customRun[existCustomRun].data; } else { custom = [command]; customRun.push({cardId, data: [command]}); } appManager.getWebContent()?.send(storageUtilsChannels.onCustomRun, {commands: custom, id: cardId}); this.updateData('cardsConfig', {customRun}); }
//#region Custom Run
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L404-L420
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
StorageManager.addPreOpen
public addPreOpen(cardId: string, open: {type: 'folder' | 'file'; path: string}): void { const preOpen = this.getData('cardsConfig').preOpen; const existCustomRun = preOpen.findIndex(custom => custom.cardId === cardId); if (existCustomRun !== -1) { preOpen[existCustomRun].data.push(open); } else { preOpen.push({cardId, data: [open]}); } this.updateData('cardsConfig', {preOpen}); }
//#region Pre Open
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Managements/Storage/StorageManager.ts#L477-L487
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
processDuOutput
function processDuOutput(stdout: string): number { if (platform() === 'win32') { const stats = stdout.trim().split('\n')[1]?.split(',') ?? []; return Number(stats.at(-2)) || 0; } const match = /^(\d+)/.exec(stdout); if (!match) return 0; const bytes = Number(match[1]); return platform() === 'darwin' ? bytes * 1024 : bytes; }
/** * Processes the output of the du command across different platforms. * @param stdout - The standard output from the du command execution. * @returns The folder size in bytes. * @throws {Error} If the operating system is not supported. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Utilities/CalculateFolderSize/CalculateFolderSize.ts#L17-L28
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
downloadAndExtractDuZip
async function downloadAndExtractDuZip(savePath: string): Promise<void> { const tempFilePath = path.join(os.tmpdir(), 'du.zip'); try { await new Promise<void>((resolve, reject) => { https .get(DU_ZIP_URL, async res => { if (res.statusCode !== 200) { reject(new Error(`Failed to download DU.zip: ${res.statusCode} ${res.statusMessage}`)); return; } const fileStream = createWriteStream(tempFilePath); await pipeline(res, fileStream); resolve(); }) .on('error', reject); }); await decompress(tempFilePath, savePath); } finally { await fs.promises.unlink(tempFilePath).catch(() => {}); // Clean up temp file } }
/** * Downloads and extracts the DU.zip file. * @param savePath - The path where the extracted files should be saved. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/main/Utilities/CalculateFolderSize/DownloadDU.ts#L19-L42
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
CardsDataManager.constructor
constructor(data: CardData, isInstalled: boolean) { this.title = data.title; this.id = data.id; this.description = data.description; this.repoUrl = validateGitRepoUrl(data.repoUrl); this.bgUrl = data.bgUrl; this.extensionsDir = data.extensionsDir; this.type = data.type; this.haveArguments = !!data.arguments; this.installed = isInstalled; makeAutoObservable(this); }
/* ----------------------------- Constructor ----------------------------- */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Cards/CardsDataManager.tsx#L29-L42
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
CardsDataManager.setMenuIsOpen
setMenuIsOpen = (menuIsOpen: boolean) => { this.menuIsOpen = menuIsOpen; }
/* ----------------------------- States ----------------------------- */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Cards/CardsDataManager.tsx
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
CardExtensions
const CardExtensions = () => { const [installedExtensions, setInstalledExtensions] = useState<string[]>([]); const {isOpen, title, id} = useModalsState('cardExtensions'); const [currentTab, setCurrentTab] = useState<any>('installed'); const [updatesAvailable, setUpdatesAvailable] = useState<string[]>([]); const [isUpdatingAll, setIsUpdatingAll] = useState<boolean>(false); const dispatch = useDispatch<AppDispatch>(); const installedRef = useRef<{updateAll: () => void; getExtensions: () => void}>(null); const autoUpdate = useIsAutoUpdateExtensions(id); const onClose = useCallback(() => { dispatch(modalActions.closeModal('cardExtensions')); }, [dispatch]); const updateAll = useCallback(() => { installedRef.current?.updateAll(); }, [installedRef.current]); const updateTable = useCallback(() => { installedRef.current?.getExtensions(); }, [installedRef.current]); useEffect(() => { setUpdatesAvailable([]); setCurrentTab('installed'); }, [isOpen]); const onPress = useCallback( () => autoUpdate ? rendererIpc.storageUtils.removeAutoUpdateExtensions(id) : rendererIpc.storageUtils.addAutoUpdateExtensions(id), [autoUpdate, id], ); const isUpdateAvailable = useMemo(() => { return !isEmpty(updatesAvailable); }, [updatesAvailable, id]); const isExtensionAvailable = useMemo(() => { return !isEmpty(installedExtensions); }, [installedExtensions, id]); return ( <Modal isOpen={isOpen} onClose={onClose} isDismissable={false} scrollBehavior="inside" motionProps={modalMotionProps} classNames={{backdrop: '!top-10', wrapper: '!top-10 scrollbar-hide'}} className="max-w-[80%] border-2 border-foreground/10 dark:border-foreground/5 overflow-hidden" hideCloseButton> <ModalContent> <ModalHeader className="flex-col gap-y-2 text-center"> {title || 'Extensions'} <Tabs variant="solid" className="mt-3" color="secondary" selectedKey={currentTab} onSelectionChange={setCurrentTab} fullWidth disableAnimation> <Tab key="installed" title="Installed" className="cursor-default" /> <Tab key="available" title="Available" className="cursor-default" /> <Tab key="clone" title="Clone" className="cursor-default" /> </Tabs> </ModalHeader> <ModalBody className="scrollbar-hide"> <div className="relative h-fit"> <Installed ref={installedRef} setIsUpdatingAll={setIsUpdatingAll} updatesAvailable={updatesAvailable} visible={currentTab === 'installed'} setUpdatesAvailable={setUpdatesAvailable} setInstalledExtensions={setInstalledExtensions} /> <Clone updateTable={updateTable} visible={currentTab === 'clone'} installedExtensions={installedExtensions} /> <Available updateTable={updateTable} visible={currentTab === 'available'} installedExtensions={installedExtensions} /> </div> </ModalBody> <ModalFooter> <div className="flex w-full flex-row justify-between"> <div> {currentTab === 'installed' && ( <Checkbox size="sm" isSelected={autoUpdate} onValueChange={onPress} className="cursor-default" isDisabled={!isExtensionAvailable}> Auto Update on Launch </Checkbox> )} </div> <div className="space-x-1.5"> {currentTab === 'installed' && ( <Button onPress={updateAll} variant={isUpdateAvailable ? 'flat' : 'light'} isDisabled={!isUpdateAvailable || isUpdatingAll} color={isUpdateAvailable ? 'success' : 'default'} className={`${!isUpdateAvailable && 'cursor-default'}`}> {!isUpdateAvailable ? 'No Updates Available' : isUpdatingAll ? 'Updating...' : 'Update All'} </Button> )} <Button color="warning" variant="light" onPress={onClose} className="cursor-default"> Close </Button> </div> </div> </ModalFooter> </ModalContent> </Modal> ); };
/** Managing card extension -> install, update, uninstall and etc */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Modals/CardExtensions/CardExtensions.tsx#L16-L143
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
filterItem
const filterItem = () => (argument: {name: string; description?: string}) => { const {description = '', name} = argument; return searchInStrings(searchValue, [description, name]); };
// -----------------------------------------------> By search
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Modals/LaunchConfig/Arguments/AddArguments/ArgumentCategory.tsx#L76-L79
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
WarningModal
const WarningModal = () => { const {contentId, isOpen} = useModalsState('warningModal'); const dispatch = useDispatch<AppDispatch>(); const handleClose = useCallback(() => { dispatch(modalActions.closeModal('warningModal')); Modal.destroyAll(); }, [dispatch]); useEffect(() => { if (isOpen) { Modal.warning({ afterClose: () => { dispatch(modalActions.closeModal('warningModal')); }, centered: true, content: warnContent[contentId], footer: ( <div className="mt-4 flex items-end justify-end"> <Space> <Button as={Link} variant="light" color="warning" href={ISSUE_PAGE} className="hover:text-warning" isExternal showAnchorIcon> Report </Button> <Button color="danger" variant="light" onPress={handleClose} className="cursor-default"> Close </Button> </Space> </div> ), maskClosable: true, okButtonProps: {className: 'cursor-default', color: 'danger'}, rootClassName: 'scrollbar-hide', styles: {mask: {top: '2.5rem'}}, title: warnTitle[contentId], wrapClassName: 'mt-10', }); } }, [isOpen, contentId, handleClose, dispatch]); return <Fragment />; };
/** Hook to display a warning */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Modals/Warning/WarningModal.tsx#L12-L59
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
DashboardPageContents
const DashboardPageContents = () => ( <ScrollShadow orientation="vertical" className="flex size-full flex-col space-y-8 pb-4 pl-1" hideScrollBar> <DashboardSections /> </ScrollShadow> );
/** Settings content */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Pages/SettingsPages/Dashboard/DashboardPage-Contents.tsx#L6-L10
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
SettingsPageContents
const SettingsPageContents = () => ( <ScrollShadow orientation="vertical" className="flex size-full flex-col space-y-8 pb-4 pl-1" hideScrollBar> <SettingsSections /> </ScrollShadow> );
/** Settings content */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/Pages/SettingsPages/Settings/SettingsPage-Contents.tsx#L6-L10
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
LynxTerminal
const LynxTerminal = () => { const allCards = useAllCards(); const terminalRef = useRef<HTMLDivElement | null>(null); const terminal = useRef<Terminal | null>(null); const fitAddon = useRef<FitAddon | null>(null); const unicode11Addon = useRef<Unicode11Addon | null>(null); const outputColor = useTerminalState('outputColor'); const useConpty = useTerminalState('useConpty'); const scrollback = useTerminalState('scrollBack'); const fontSize = useTerminalState('fontSize'); const cursorStyle = useTerminalState('cursorStyle'); const cursorInactiveStyle = useTerminalState('cursorInactiveStyle'); const cursorBlink = useTerminalState('blinkCursor'); const resizeDelay = useTerminalState('resizeDelay'); const [selectedText, setSelectedText] = useState<string>(''); const {address, id, currentView} = useCardsState('runningCard'); const darkMode = useAppState('darkMode'); const dispatch = useDispatch<AppDispatch>(); const [browserBehavior, setBrowserBehavior] = useState<'appBrowser' | 'defaultBrowser' | 'doNothing' | string>( 'appBrowser', ); const getTheme = useCallback( (): ITheme => ({ background: darkMode ? getColor('raisinBlack') : getColor('white'), foreground: darkMode ? getColor('white') : getColor('black'), cursor: darkMode ? getColor('white') : getColor('black'), cursorAccent: darkMode ? getColor('white') : getColor('black'), selectionForeground: darkMode ? getColor('black') : getColor('white'), selectionBackground: darkMode ? getColor('white', 0.7) : getColor('black', 0.7), }), [darkMode], ); const copyText = useCallback(() => { if (!isEmpty(selectedText)) { navigator.clipboard.writeText(selectedText); message.success(`Copied to clipboard`); terminal.current?.clearSelection(); } }, [selectedText, terminal]); useHotkeys('ctrl+c', copyText, { keyup: true, enableOnFormTags: true, enableOnContentEditable: true, }); useEffect(() => { rendererIpc.storage.get('cardsConfig').then(result => { const custom = result.customRunBehavior.find(customRun => customRun.cardID === id); if (custom) { setBrowserBehavior(custom.browser); } }); }, [id]); const setTheme = useCallback(() => { if (terminal.current) { terminal.current.options.theme = getTheme(); } }, [getTheme, terminal.current]); useEffect(() => { setTheme(); }, [darkMode]); const writeData = useCallback( (data: string) => { if (isEmpty(address) && browserBehavior !== 'doNothing') { const catchAddress = getCardMethod(allCards, id, 'catchAddress'); const url = catchAddress?.(data) || ''; if (!isEmpty(url)) { if (browserBehavior === 'appBrowser') { setTimeout(() => { dispatch(cardsActions.setRunningCardAddress(url)); dispatch(cardsActions.setRunningCardView('browser')); }, 1500); } else { window.open(url); } } } terminal.current?.write(outputColor ? parseTerminalColors(data) : data); }, [address, id, browserBehavior, outputColor, dispatch, allCards], ); const onRightClickRef = useRef<((e: MouseEvent) => void) | null>(null); useEffect(() => { onRightClickRef.current = () => { const isSelectedText = !isEmpty(terminal.current?.getSelection()); if (isSelectedText) { copyText(); } else { navigator.clipboard.readText().then(text => { rendererIpc.pty.write(text); }); } }; }, [copyText, terminal]); const stableEventHandler = useCallback(e => { onRightClickRef.current?.(e); }, []); useEffect(() => { terminalRef.current?.removeEventListener('contextmenu', stableEventHandler); terminalRef.current?.addEventListener('contextmenu', stableEventHandler); }, [terminalRef, stableEventHandler]); useEffect(() => { async function loadTerminal() { const JetBrainsMono = new FontFaceObserver(FONT_FAMILY); const sysInfo = await rendererIpc.win.getSystemInfo(); const windowsPty: IWindowsPty | undefined = sysInfo.os === 'win32' ? { backend: useConpty === 'auto' ? (sysInfo.buildNumber as number) >= 18309 ? 'conpty' : 'winpty' : useConpty === 'yes' ? 'conpty' : 'winpty', buildNumber: sysInfo.buildNumber as number, } : undefined; JetBrainsMono.load().then(() => { let renderMode: 'webgl' | 'canvas' = isWebgl2Supported() ? 'webgl' : 'canvas'; // Create and initialize the terminal object with a default background and cursor terminal.current = new Terminal({ allowProposedApi: true, rows: 150, cols: 150, scrollback, cursorBlink, fontFamily: 'JetBrainsMono', fontSize: fontSize, scrollOnUserInput: true, cursorStyle, cursorInactiveStyle, windowsPty, }); setTheme(); fitAddon.current = new FitAddon(); unicode11Addon.current = new Unicode11Addon(); terminal.current.loadAddon(fitAddon.current); terminal.current.loadAddon(unicode11Addon.current); terminal.current.unicode.activeVersion = '11'; terminal.current.loadAddon(new ClipboardAddon()); terminal.current.loadAddon( new WebLinksAddon((_event, uri) => { window.open(uri); }), ); // Load terminal ui on the element. if (terminalRef.current) terminal.current.open(terminalRef.current); if (renderMode === 'webgl') { const webglAddon: WebglAddon = new WebglAddon(); // If on webgl content losing switch to canvas webglAddon.onContextLoss(() => { webglAddon.dispose(); terminal.current?.loadAddon(new CanvasAddon()); renderMode = 'canvas'; }); terminal.current.loadAddon(webglAddon); renderMode = 'webgl'; } else { terminal.current.loadAddon(new CanvasAddon()); renderMode = 'canvas'; } terminal.current.onResize(size => { { rendererIpc.pty.resize(size.cols, size.rows); } }); // Fit terminal to element fitAddon.current.fit(); terminal.current.onSelectionChange(() => { setSelectedText(terminal.current?.getSelection() || ''); }); terminal.current.attachCustomKeyEventHandler(e => { const isSelectedText = !isEmpty(terminal.current?.getSelection()); return !(e.key === 'c' && e.ctrlKey && isSelectedText); }); terminal.current.onData(data => { if (!isEmpty(data)) rendererIpc.pty.write(data); }); }); } if (terminalRef.current && !terminal.current) { loadTerminal(); } window.addEventListener('resize', () => { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(() => { fitAddon.current?.fit(); }, resizeDelay); }); rendererIpc.pty.onData((_, data) => { writeData(data); }); return () => { window.removeEventListener('resize', () => {}); rendererIpc.pty.offData(); }; }, [terminalRef.current]); const animate = useMemo(() => { return currentView === 'terminal' ? 'animate' : 'exit'; }, [currentView]); return ( <motion.div variants={{ init: {scale: 0.95, opacity: 0}, animate: {scale: 1, opacity: 1}, exit: {scale: 0.95, opacity: 0}, }}
/** Xterm.js terminal */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Components/RunningCardView/LynxTerminal.tsx#L31-L280
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
useGetArgumentsByID
const useGetArgumentsByID = (id: string): ArgumentsData | undefined => useAllCards().find(card => card.id === id)?.arguments;
/** * Retrieves the arguments for a specific card. * @param id The ID of the card. * @returns The arguments data or undefined if not found. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Modules/ModuleLoader.ts#L38-L39
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
useGetCardsByPath
const useGetCardsByPath = (path: AvailablePages): CardData[] | undefined => useAllModules().find(module => module.routePath === path)?.cards;
/** * Retrieves all cards associated with a specific path. * @param path The path to filter cards by. * @returns An array of cards or undefined if no module matches the path. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Modules/ModuleLoader.ts#L46-L47
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
duplicateCard
const duplicateCard = (id: string, defaultID?: string, defaultTitle?: string) => { let newId: string = ''; let newTitle: string = ''; let routePath: string = ''; // Function to generate the next ID const generateNewId = (baseId: string): string => { let counter = 2; let newId = `${baseId}_${counter}`; while (allCards.some(card => card.id === newId)) { counter++; newId = `${baseId}_${counter}`; } return newId; }; const generateNewTitle = (ogTitle: string) => { let counter = 2; let newTitle = `${ogTitle} (${counter})`; while (allCards.some(card => card.title === newTitle)) { counter++; newTitle = `${ogTitle} (${counter})`; } return newTitle; }; // Use find and map together for efficiency let duplicatedCard: CardData | undefined; const updatedModules = allModules.map(page => { const cardIndex = page.cards.findIndex(card => card.id === id); if (cardIndex === -1) { return page; // Card not found in this page } // Card found, duplicate and add to the page const originalCard = page.cards[cardIndex]; newId = defaultID || generateNewId(originalCard.id); newTitle = defaultTitle || generateNewTitle(originalCard.title); duplicatedCard = {...originalCard, id: newId, title: newTitle}; // Add new title const updatedCards = [...page.cards]; updatedCards.splice(cardIndex + 1, 0, duplicatedCard); routePath = page.routePath; return {...page, cards: updatedCards}; }); if (!duplicatedCard) { return undefined; // Card not found at all } allModules = updatedModules; allCards = [...allCards, duplicatedCard]; emitChange(); return {id: newId, title: newTitle, routePath}; };
/** * Duplicate a card */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Modules/ModuleLoader.ts#L62-L123
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
generateNewId
const generateNewId = (baseId: string): string => { let counter = 2; let newId = `${baseId}_${counter}`; while (allCards.some(card => card.id === newId)) { counter++; newId = `${baseId}_${counter}`; } return newId; };
// Function to generate the next ID
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Modules/ModuleLoader.ts#L68-L78
16a4717552cc939cabefa69048c04a6d66380aa9
LynxHub
github_2023
KindaBrazy
typescript
loadModules
const loadModules = async () => { try { const moduleData = await rendererIpc.module.getModulesData(); // Use Promise.all for concurrent module imports const importedModules = await Promise.all( moduleData.map(async path => { const module = await import(/* @vite-ignore */ `${path}/scripts/renderer.mjs?${Date.now()}`); return {path, module}; }), ); const newAllModules: CardModules = []; const newAllCards: CardData[] = []; // Optimize module and card aggregation using reduce for better performance importedModules.reduce((acc, {module}) => { const importedModule = module as RendererModuleImportType; importedModule.setCurrentBuild?.(APP_BUILD_NUMBER); importedModule.default.forEach(mod => { const existingModuleIndex = newAllModules.findIndex(m => m.routePath === mod.routePath); if (existingModuleIndex !== -1) { // Add new cards to existing module, avoiding duplicates const existingModule = newAllModules[existingModuleIndex]; mod.cards.forEach(card => { if (!existingModule.cards.some(c => c.id === card.id)) { existingModule.cards.push(card); newAllCards.push(card); } }); } else { newAllModules.push(mod); newAllCards.push(...mod.cards); } }); return acc; }, {}); await emitLoaded(newAllModules, newAllCards); } catch (error) { console.error('Error importing modules:', error); throw error; // Re-throw to allow for handling at a higher level if needed } };
/** * Loads all modules and their associated cards. * This function fetches module data, imports the corresponding modules, * and sets the `allModules` and `allCards` variables. */
https://github.com/KindaBrazy/LynxHub/blob/16a4717552cc939cabefa69048c04a6d66380aa9/src/renderer/src/App/Modules/ModuleLoader.ts#L171-L218
16a4717552cc939cabefa69048c04a6d66380aa9
InPlayerEpisodePreview
github_2023
Namo2
typescript
attemptLoadVideoView
function attemptLoadVideoView(retryCount = 0): void { if (videoPaths.includes(currentRoutePath)) { if ((programDataStore.movies.length > 0 && programDataStore.boxSetName !== '') || (programDataStore.seasons.length > 0 && programDataStore.seasons[programDataStore.activeSeasonIndex].episodes.length > 1)) { // Check if the preview container is already loaded before loading if (!previewContainerLoaded && !isPreviewButtonCreated()) { loadVideoView(); previewContainerLoaded = true; // Set flag to true after loading } } else if (retryCount < 3) { // Retry up to 3 times setTimeout((): void => { logger.debug(`Retry #${retryCount + 1}`); attemptLoadVideoView(retryCount + 1); }, 10000); // Wait 10 seconds for each retry } } else if (videoPaths.includes(previousRoutePath)) { unloadVideoView(); } }
// This function attempts to load the video view, retrying up to 3 times if necessary.
https://github.com/Namo2/InPlayerEpisodePreview/blob/4eba9531f6b6fd9a61b36a66d1f8aa148060e582/Namo.Plugin.InPlayerEpisodePreview/Web/InPlayerPreview.ts#L65-L82
4eba9531f6b6fd9a61b36a66d1f8aa148060e582
InPlayerEpisodePreview
github_2023
Namo2
typescript
ListElementTemplate.update
public update(): void { let newData: BaseItem; // get current episode data if (ItemType[this.item.Type] === ItemType.Series) { const season: Season = this.programDataStore.seasons.find((s: Season): boolean => s.episodes.some((e: BaseItem): boolean => e.Id === this.item.Id)); newData = season.episodes.find((e: BaseItem): boolean => e.Id === this.item.Id); } else if (ItemType[this.item.Type] === ItemType.Movie) { newData = this.programDataStore.movies.find((m: BaseItem): boolean => m.Id === this.item.Id); } // update playtime percentage const playtime: Element = this.getElement().querySelector('.itemProgressBarForeground'); playtime.setAttribute("style", `width:${newData.UserData.PlayedPercentage}%`); // update quick actions state this.playStateIcon.update(); this.favoriteIcon.update(); }
/** * Unused - Will maybe be used in further updates on this */
https://github.com/Namo2/InPlayerEpisodePreview/blob/4eba9531f6b6fd9a61b36a66d1f8aa148060e582/Namo.Plugin.InPlayerEpisodePreview/Web/Components/ListElementTemplate.ts#L112-L129
4eba9531f6b6fd9a61b36a66d1f8aa148060e582
InPlayerEpisodePreview
github_2023
Namo2
typescript
FavoriteIconTemplate.update
public update(): void { // get current episode data const season = this.programDataStore.seasons.find(s => s.episodes.some(e => e.Id === this.episode.Id)); const newData = season.episodes.find(e => e.Id === this.episode.Id); const favoriteIcon = this.getElement(); favoriteIcon.setAttribute("data-isfavorite", newData.UserData.IsFavorite.toString()); }
/** * Unused - Will maybe be used in further updates on this */
https://github.com/Namo2/InPlayerEpisodePreview/blob/4eba9531f6b6fd9a61b36a66d1f8aa148060e582/Namo.Plugin.InPlayerEpisodePreview/Web/Components/QuickActions/FavoriteIconTemplate.ts#L39-L46
4eba9531f6b6fd9a61b36a66d1f8aa148060e582
InPlayerEpisodePreview
github_2023
Namo2
typescript
PlayStateIconTemplate.update
public update(): void { // get current episode data const season = this.programDataStore.seasons.find(s => s.episodes.some(e => e.Id === this.episode.Id)); const newData = season.episodes.find(e => e.Id === this.episode.Id); const playStateIcon = this.getElement(); playStateIcon.setAttribute("data-played", newData.UserData.Played.toString()); }
/** * Unused - Will maybe be used in further updates on this */
https://github.com/Namo2/InPlayerEpisodePreview/blob/4eba9531f6b6fd9a61b36a66d1f8aa148060e582/Namo.Plugin.InPlayerEpisodePreview/Web/Components/QuickActions/PlayStateIconTemplate.ts#L37-L44
4eba9531f6b6fd9a61b36a66d1f8aa148060e582
llm-rag-vectordb-python
github_2023
build-on-aws
typescript
onResize
const onResize = () => { if (isMobile) { return; } // 狭い画面のDrawerが表示されていて、画面サイズが大きくなったら状態を更新 if (!smallDrawer.current?.checkVisibility() && opened) { switchOpen(); } };
// リサイズイベントを拾って状態を更新する
https://github.com/build-on-aws/llm-rag-vectordb-python/blob/090f7ac758c441530f71aaf997adeec9b86a2317/pi-day-2024/01.Bedrock_Claude_Chat/frontend/src/components/ChatListDrawer.tsx#L266-L275
090f7ac758c441530f71aaf997adeec9b86a2317
llm-rag-vectordb-python
github_2023
build-on-aws
typescript
handleClickOutside
const handleClickOutside = (event: any) => { // メニューボタンとメニュー以外をクリックしていたらメニューを閉じる if ( menuRef.current && !menuRef.current.contains(event.target) && !buttonRef.current?.contains(event.target) ) { setIsOpen(false); } };
// メニューの外側をクリックした際のハンドリング
https://github.com/build-on-aws/llm-rag-vectordb-python/blob/090f7ac758c441530f71aaf997adeec9b86a2317/pi-day-2024/01.Bedrock_Claude_Chat/frontend/src/components/Menu.tsx#L32-L41
090f7ac758c441530f71aaf997adeec9b86a2317
llm-rag-vectordb-python
github_2023
build-on-aws
typescript
pushNewMessage
const pushNewMessage = ( parentMessageId: string | null, messageContent: MessageContent ) => { pushMessage( conversationId ?? '', parentMessageId, NEW_MESSAGE_ID.USER, messageContent ); pushMessage( conversationId ?? '', NEW_MESSAGE_ID.USER, NEW_MESSAGE_ID.ASSISTANT, { role: 'assistant', content: [ { contentType: 'text', body: '', }, ], model: messageContent.model, } ); };
// 画面に即時反映させるために、Stateを更新する処理
https://github.com/build-on-aws/llm-rag-vectordb-python/blob/090f7ac758c441530f71aaf997adeec9b86a2317/pi-day-2024/01.Bedrock_Claude_Chat/frontend/src/hooks/useChat.ts#L261-L286
090f7ac758c441530f71aaf997adeec9b86a2317
llm-rag-vectordb-python
github_2023
build-on-aws
typescript
regenerate
const regenerate = (props?: { content?: string; messageId?: string; bot?: BotInputType; }) => { let index: number = -1; // messageIdが指定されている場合は、指定されたメッセージをベースにする if (props?.messageId) { index = messages.findIndex((m) => m.id === props.messageId); } // 最新のメッセージがUSERの場合は、エラーとして処理する const isRetryError = messages[messages.length - 1].role === 'user'; // messageIdが指定されていない場合は、最新のメッセージを再生成する if (index === -1) { index = isRetryError ? messages.length - 1 : messages.length - 2; } const parentMessage = produce(messages[index], (draft) => { if (props?.content) { draft.content[0].body = props.content; } }); // Stateを書き換え後の内容に更新 if (props?.content) { editMessage(conversationId, parentMessage.id, props.content); } const input: PostMessageRequest = { conversationId: conversationId, message: { ...parentMessage, parentMessageId: parentMessage.parent, }, stream: true, botId: props?.bot?.botId, }; if (input.message.parentMessageId === null) { input.message.parentMessageId = 'system'; } setPostingMessage(true); // 画面に即時反映するために、Stateを更新する if (isRetryError) { pushMessage( conversationId ?? '', parentMessage.id, NEW_MESSAGE_ID.ASSISTANT, { role: 'assistant', content: [ { contentType: 'text', body: '', }, ], model: messages[index].model, } ); } else { pushNewMessage(parentMessage.parent, parentMessage); } setCurrentMessageId(NEW_MESSAGE_ID.ASSISTANT); postStreaming({ input, dispatch: (c: string) => { editMessage(conversationId, NEW_MESSAGE_ID.ASSISTANT, c); }, }) .then(() => { mutate(); }) .catch((e) => { console.error(e); setCurrentMessageId(NEW_MESSAGE_ID.USER); removeMessage(conversationId, NEW_MESSAGE_ID.ASSISTANT); }) .finally(() => { setPostingMessage(false); }); };
/** * 再生成 * @param props content: 内容を上書きしたい場合に設定 messageId: 再生成対象のmessageId botId: ボットの場合は設定する */
https://github.com/build-on-aws/llm-rag-vectordb-python/blob/090f7ac758c441530f71aaf997adeec9b86a2317/pi-day-2024/01.Bedrock_Claude_Chat/frontend/src/hooks/useChat.ts#L418-L503
090f7ac758c441530f71aaf997adeec9b86a2317
llm-rag-vectordb-python
github_2023
build-on-aws
typescript
fetcfWithParams
const fetcfWithParams = ([url, params]: [string, Record<string, any>]) => { return api .get(url, { params, }) .then((res) => res.data); };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/build-on-aws/llm-rag-vectordb-python/blob/090f7ac758c441530f71aaf997adeec9b86a2317/pi-day-2024/01.Bedrock_Claude_Chat/frontend/src/hooks/useHttp.ts#L29-L35
090f7ac758c441530f71aaf997adeec9b86a2317
llm-rag-vectordb-python
github_2023
build-on-aws
typescript
useHttp
const useHttp = () => { // const alert = useAlertSnackbar(); return { /** * GET Request * Implemented with SWR * @param url * @returns */ // eslint-disable-next-line @typescript-eslint/no-explicit-any get: <Data = any, Error = any>( url: string | [string, ...unknown[]] | null, config?: SWRConfiguration ) => { // eslint-disable-next-line react-hooks/rules-of-hooks return useSWR<Data, AxiosError<Error>>( url, typeof url === 'string' ? fetcher : fetcfWithParams, { ...config, } ); }, // eslint-disable-next-line @typescript-eslint/no-explicit-any getOnce: <RES = any, DATA = any>( url: string, params?: DATA, // eslint-disable-next-line @typescript-eslint/no-explicit-any errorProcess?: (err: any) => void ) => { return new Promise<AxiosResponse<RES>>((resolve, reject) => { api .get<RES, AxiosResponse<RES>, DATA>(url, { params, }) .then((data) => { resolve(data); }) .catch((err) => { if (errorProcess) { errorProcess(err); } else { // alert.openError(getErrorMessage(err)); } reject(err); }); }); }, /** * POST Request * @param url * @param data * @returns */ // eslint-disable-next-line @typescript-eslint/no-explicit-any post: <RES = any, DATA = any>( url: string, data: DATA, // eslint-disable-next-line @typescript-eslint/no-explicit-any errorProcess?: (err: any) => void ) => { return new Promise<AxiosResponse<RES>>((resolve, reject) => { api .post<RES, AxiosResponse<RES>, DATA>(url, data) .then((data) => { resolve(data); }) .catch((err) => { if (errorProcess) { errorProcess(err); } else { // alert.openError(getErrorMessage(err)); } reject(err); }); }); }, /** * PUT Request * @param url * @param data * @returns */ // eslint-disable-next-line @typescript-eslint/no-explicit-any put: <RES = any, DATA = any>( url: string, data: DATA, // eslint-disable-next-line @typescript-eslint/no-explicit-any errorProcess?: (err: any) => void ) => { return new Promise<AxiosResponse<RES>>((resolve, reject) => { api .put<RES, AxiosResponse<RES>, DATA>(url, data) .then((data) => { resolve(data); }) .catch((err) => { if (errorProcess) { errorProcess(err); } else { // alert.openError(getErrorMessage(err)); } reject(err); }); }); }, /** * DELETE Request * @param url * @returns */ // eslint-disable-next-line @typescript-eslint/no-explicit-any delete: <RES = any, DATA = any>( url: string, params?: DATA, // eslint-disable-next-line @typescript-eslint/no-explicit-any errorProcess?: (err: any) => void ) => { return new Promise<AxiosResponse<RES>>((resolve, reject) => { api .delete<RES, AxiosResponse<RES>, DATA>(url, { params, }) .then((data) => { resolve(data); }) .catch((err) => { if (errorProcess) { errorProcess(err); } else { // alert.openError(getErrorMessage(err)); } reject(err); }); }); }, // eslint-disable-next-line @typescript-eslint/no-explicit-any patch: <RES = any, DATA = any>( url: string, data: DATA, // eslint-disable-next-line @typescript-eslint/no-explicit-any errorProcess?: (err: any) => void ) => { return new Promise<AxiosResponse<RES>>((resolve, reject) => { api .patch<RES, AxiosResponse<RES>, DATA>(url, data) .then((data) => { resolve(data); }) .catch((err) => { if (errorProcess) { errorProcess(err); } else { // alert.openError(getErrorMessage(err)); } reject(err); }); }); }, }; };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/build-on-aws/llm-rag-vectordb-python/blob/090f7ac758c441530f71aaf997adeec9b86a2317/pi-day-2024/01.Bedrock_Claude_Chat/frontend/src/hooks/useHttp.ts#L48-L212
090f7ac758c441530f71aaf997adeec9b86a2317
looker-explore-assistant
github_2023
looker-open-source
typescript
formatDate
const formatDate = (date: Date) => { const options: Intl.DateTimeFormatOptions = { month: 'short', // allowed values: 'numeric', '2-digit', 'long', 'short', 'narrow' day: 'numeric', // allowed values: 'numeric', '2-digit' year: 'numeric', // allowed values: 'numeric', '2-digit' } return date.toLocaleDateString('en-US', options) }
// Function to format the date as "Oct 25, 2023"
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/components/Chat/Message.tsx#L16-L23
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
UtilsHelper.escapeBreakLine
public static escapeBreakLine(originalString: string): string { return originalString.replace(/\n/g, '\\n') }
/** * Adds an extra slash to line breaks \n -> \\n * @param originalString * @returns */
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/utils/Helper.ts#L19-L21
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
UtilsHelper.escapeSpecialCharacter
public static escapeSpecialCharacter(originalString: string): string { let fixedString = originalString fixedString = fixedString.replace(/'/g, "\\'") return fixedString }
/** * Adds an extra slash to line breaks \n -> \\n * @param originalString * @returns */
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/utils/Helper.ts#L32-L36
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
UtilsHelper.firstElement
public static firstElement<T>(array: Array<T>): T { const [firstElement] = array return firstElement }
/** * Returns first element from Array * @param array * @returns */
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/utils/Helper.ts#L43-L46
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
UtilsHelper.cleanResult
public static cleanResult(originalString: string): string { let fixedString = originalString fixedString = fixedString.replace('```json', '') fixedString = fixedString.replace('```JSON', '') fixedString = fixedString.replace('```', '') return fixedString }
/** * Replaces ```JSON with ``` * @param originalString * @returns */
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/utils/Helper.ts#L53-L59
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
UtilsHelper.removeDuplicates
public static removeDuplicates<T>(array: Array<T>): Array<T> { return Array.from(new Set(array)) }
/** * Remove duplicates from Array * @param array * @returns */
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/utils/Helper.ts#L66-L68
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
formatDate
const formatDate = (date: Date) => { const options: Intl.DateTimeFormatOptions = { month: 'short', // allowed values: 'numeric', '2-digit', 'long', 'short', 'narrow' day: 'numeric', // allowed values: 'numeric', '2-digit' year: 'numeric', // allowed values: 'numeric', '2-digit' } return date.toLocaleDateString('en-US', options) }
// Function to format the date as "Oct 25, 2023"
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/src/utils/time.ts#L41-L48
4f4a1bc89c01aae0db06f6762035f3279a9f2384
looker-explore-assistant
github_2023
looker-open-source
typescript
FallbackRender
const FallbackRender = ({ error }: { error: Error }) => ( <div>Error: {error.message}</div> ) describe('useSendVertexMessage', () => { let result: ReturnType<typeof useSendVertexMessage> const dimensions = [ { name: 'orders.created_date', type: 'string', description: 'desc1', tags: ['tag1'], }, ] const measures = [ { name: 'orders.sum_revenue', type: 'number', description: 'The sum of the revenue', tags: ['tag1'], }, ] const semanticModels = { 'ecommerce:orders': { exploreKey: 'ecommerce:orders', modelName: 'ecommerce', exploreId: 'orders', dimensions, measures, } } beforeEach(async () => { // Set initial dimensions and measures await act(async () => { store.dispatch(setSemanticModels(semanticModels)) }) const { result: hookResult } = renderHook(() => useSendVertexMessage(), { wrapper: ({ children }) => ( <Provider store={store}> {/* @ts-ignore */} <ExtensionContext.Provider value={mockExtensionContextValue}> <ErrorBoundary fallbackRender={FallbackRender}> {children} </ErrorBoundary> </ExtensionContext.Provider> </Provider> ), }) result = hookResult.current }) test('generateFilterParams should return correct filter parameters', async () => { const prompt = 'Show me the sales data for this year' await act(async () => { const filterParams = await result.generateFilterParams( prompt, dimensions, measures, ) expect( Object.prototype.hasOwnProperty.call( filterParams, 'orders.created_date', ), ).toBe(true) expect(filterParams['orders.created_date']).toContain('this year') }) }) // Additional test cases can be added here })
// Fallback render function for ErrorBoundary
https://github.com/looker-open-source/looker-explore-assistant/blob/4f4a1bc89c01aae0db06f6762035f3279a9f2384/explore-assistant-extension/tests/generateFilterParams.test.tsx#L31-L107
4f4a1bc89c01aae0db06f6762035f3279a9f2384
aibitat
github_2023
wladpaiva
typescript
AIbitat.chats
get chats() { return this._chats }
/** * Get the chat history between agents and channels. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L170-L172
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.use
use<T extends Provider>(plugin: AIbitat.Plugin<T>) { plugin.setup(this) return this }
/** * Install a plugin. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L177-L180
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.agent
public agent<T extends Provider>( name: string, config: AgentConfig<T> = {} as AgentConfig<T>, ) { this.agents.set(name, config) return this }
/** * Add a new agent to the AIbitat. * * @param name * @param config * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L189-L195
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.channel
public channel<T extends Provider>( name: string, members: string[], config: ChannelConfig<T> = {} as ChannelConfig<T>, ) { this.channels.set(name, { members, ...config, }) return this }
/** * Add a new channel to the AIbitat. * * @param name * @param members * @param config * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L205-L215
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.getAgentConfig
private getAgentConfig(agent: string) { const config = this.agents.get(agent) if (!config) { throw new Error(`Agent configuration "${agent}" not found`) } return { role: 'You are a helpful AI assistant.', // role: `You are a helpful AI assistant. // Solve tasks using your coding and language skills. // In the following cases, suggest typescript code (in a typescript coding block) or shell script (in a sh coding block) for the user to execute. // 1. When you need to collect info, use the code to output the info you need, for example, browse or search the web, download/read a file, print the content of a webpage or a file, get the current date/time, check the operating system. After sufficient info is printed and the task is ready to be solved based on your language skill, you can solve the task by yourself. // 2. When you need to perform some task with code, use the code to perform the task and output the result. Finish the task smartly. // Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill. // When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user. // If you want the user to save the code in a file before executing it, put # filename: <filename> inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user. // If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try. // When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible. // Reply "TERMINATE" when everything is done.`, ...config, } }
/** * Get the specific agent configuration. * * @param agent The name of the agent. * @throws When the agent configuration is not found. * @returns The agent configuration. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L224-L244
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.getChannelConfig
private getChannelConfig(channel: string) { const config = this.channels.get(channel) if (!config) { throw new Error(`Channel configuration "${channel}" not found`) } return { maxRounds: 10, role: '', ...config, } }
/** * Get the specific channel configuration. * * @param channel The name of the channel. * @throws When the channel configuration is not found. * @returns The channel configuration. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L253-L263
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.getGroupMembers
private getGroupMembers(node: string) { const group = this.getChannelConfig(node) return group.members }
/** * Get the members of a group. * @throws When the group is not defined as an array in the connections. * @param node The name of the group. * @returns The members of the group. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L271-L274
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.onTerminate
public onTerminate(listener: (node: string) => void) { this.emitter.on('terminate', listener) return this }
/** * Triggered when a chat is terminated. After this, the chat can't be continued. * * @param listener * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L282-L285
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.terminate
private terminate(node: string) { this.emitter.emit('terminate', node, this) }
/** * Terminate the chat. After this, the chat can't be continued. * * @param node Last node to chat with */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L292-L294
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.onInterrupt
public onInterrupt(listener: (route: Route) => void) { this.emitter.on('interrupt', listener) return this }
/** * Triggered when a chat is interrupted by a node. * * @param listener * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L302-L305
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.interrupt
private interrupt(route: Route) { this._chats.push({ ...route, state: 'interrupt', }) this.emitter.emit('interrupt', route, this) }
/** * Interruption the chat. * * @param route The nodes that participated in the interruption. * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L313-L319
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.onMessage
public onMessage(listener: (chat: Chat) => void) { this.emitter.on('message', listener) return this }
/** * Triggered when a message is added to the chat history. * This can either be the first message or a reply to a message. * * @param listener * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L328-L331
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.newMessage
private newMessage(message: Message) { const chat = { ...message, state: 'success' as const, } this._chats.push(chat) this.emitter.emit('message', chat, this) }
/** * Register a new successful message in the chat history. * This will trigger the `onMessage` event. * * @param message */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L339-L347
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.onError
public onError( listener: ( /** * The error that occurred. * * Native errors are: * - `APIError` * - `AuthorizationError` * - `UnknownError` * - `RateLimitError` * - `ServerError` */ error: unknown, /** * The message when the error occurred. */ {}: Route, ) => void, ) { this.emitter.on('replyError', listener) return this }
/** * Triggered when an error occurs during the chat. * * @param listener * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L355-L376
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.newError
private newError(route: Route, error: unknown) { const chat = { ...route, content: error instanceof Error ? error.message : String(error), state: 'error' as const, } this._chats.push(chat) this.emitter.emit('replyError', error, chat) }
/** * Register an error in the chat history. * This will trigger the `onError` event. * * @param route * @param error */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L385-L393
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.onStart
public onStart<T extends Provider>( listener: (chat: Chat, aibitat: AIbitat<T>) => void, ) { this.emitter.on('start', listener) return this }
/** * Triggered when a chat is interrupted by a node. * * @param listener * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L401-L406
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.start
public async start(message: Message) { // register the message in the chat history this.newMessage(message) this.emitter.emit('start', message, this) // ask the node to reply await this.chat({ to: message.from, from: message.to, }) return this }
/** * Start a new chat. * * @param message The message to start the chat. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L413-L425
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.chat
private async chat(route: Route, keepAlive = true) { // check if the message is for a group // if it is, select the next node to chat with from the group // and then ask them to reply. if (this.channels.get(route.from)) { // select a node from the group let nextNode: string | undefined try { nextNode = await this.selectNext(route.from) } catch (error: unknown) { if (error instanceof APIError) { return this.newError({from: route.from, to: route.to}, error) } throw error } if (!nextNode) { // TODO: should it throw an error or keep the chat alive when there is no node to chat with in the group? // maybe it should wrap up the chat and reply to the original node // For now, it will terminate the chat this.terminate(route.from) return } const nextChat = { from: nextNode, to: route.from, } if (this.shouldAgentInterrupt(nextNode)) { this.interrupt(nextChat) return } // get chats only from the group's nodes const history = this.getHistory({to: route.from}) const group = this.getGroupMembers(route.from) const rounds = history.filter(chat => group.includes(chat.from)).length const {maxRounds} = this.getChannelConfig(route.from) if (rounds >= maxRounds) { this.terminate(route.to) return } await this.chat(nextChat) return } // If it's a direct message, reply to the message let reply: string try { reply = await this.reply(route) } catch (error: unknown) { if (error instanceof APIError) { return this.newError({from: route.from, to: route.to}, error) } throw error } if ( reply === 'TERMINATE' || this.hasReachedMaximumRounds(route.from, route.to) ) { this.terminate(route.to) return } const newChat = {to: route.from, from: route.to} if ( reply === 'INTERRUPT' || (this.agents.get(route.to) && this.shouldAgentInterrupt(route.to)) ) { this.interrupt(newChat) return } if (keepAlive) { // keep the chat alive by replying to the other node await this.chat(newChat, true) } }
/** * Recursively chat between two nodes. * * @param route * @param keepAlive Whether to keep the chat alive. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L433-L515
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.shouldAgentInterrupt
private shouldAgentInterrupt(agent: string) { const config = this.getAgentConfig(agent) return this.defaultInterrupt === 'ALWAYS' || config.interrupt === 'ALWAYS' }
/** * Check if the agent should interrupt the chat based on its configuration. * * @param agent * @returns {boolean} Whether the agent should interrupt the chat. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L523-L526
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.selectNext
private async selectNext(channel: string) { // get all members of the group const nodes = this.getGroupMembers(channel) const channelConfig = this.getChannelConfig(channel) // TODO: move this to when the group is created // warn if the group is underpopulated if (nodes.length < 3) { console.warn( `- Group (${channel}) is underpopulated with ${nodes.length} agents. Direct communication would be more efficient.`, ) } // get the nodes that have not reached the maximum number of rounds const availableNodes = nodes.filter( node => !this.hasReachedMaximumRounds(channel, node), ) // remove the last node that chatted with the channel, so it doesn't chat again const lastChat = this._chats.filter(c => c.to === channel).at(-1) if (lastChat) { const index = availableNodes.indexOf(lastChat.from) if (index > -1) { availableNodes.splice(index, 1) } } if (!availableNodes.length) { // TODO: what should it do when there is no node to chat with? return } // get the provider that will be used for the channel // if the channel has a provider, use that otherwise // use the GPT-4 because it has a better reasoning const provider = this.getProviderForConfig({ // @ts-expect-error model: 'gpt-4', ...this.defaultProvider, ...channelConfig, }) const history = this.getHistory({to: channel}) // build the messages to send to the provider const messages = [ { role: 'system' as const, content: channelConfig.role, }, { role: 'user' as const, content: `You are in a role play game. The following roles are available: ${availableNodes .map(node => `@${node}: ${this.getAgentConfig(node).role}`) .join('\n')}. Read the following conversation. CHAT HISTORY ${history.map(c => `@${c.from}: ${c.content}`).join('\n')} Then select the next role from that is going to speak next. Only return the role. `, }, ] // ask the provider to select the next node to chat with // and remove the @ from the response const {result} = await provider.complete(messages) const name = result!.replace(/^@/g, '') if (this.agents.get(name)) { return name } // if the name is not in the nodes, return a random node return availableNodes[Math.floor(Math.random() * availableNodes.length)] }
/** * Select the next node to chat with from a group. The node will be selected based on the history of chats. * It will select the node that has not reached the maximum number of rounds yet and has not chatted with the channel in the last round. * If it could not determine the next node, it will return a random node. * * @param channel The name of the group. * @returns The name of the node to chat with. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L536-L613
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.hasReachedMaximumRounds
private hasReachedMaximumRounds(from: string, to: string): boolean { return this.getHistory({from, to}).length >= this.maxRounds }
/** * Check if the chat has reached the maximum number of rounds. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L618-L620
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.reply
private async reply(route: Route) { // get the provider for the node that will reply const fromConfig = this.getAgentConfig(route.from) const chatHistory = // if it is sending message to a group, send the group chat history to the provider // otherwise, send the chat history between the two nodes this.channels.get(route.to) ? [ { role: 'user' as const, content: `You are in a whatsapp group. Read the following conversation and then reply. Do not add introduction or conclusion to your reply because this will be a continuous conversation. Don't introduce yourself. CHAT HISTORY ${this.getHistory({to: route.to}) .map(c => `@${c.from}: ${c.content}`) .join('\n')} @${route.from}:`, }, ] : this.getHistory(route).map(c => ({ content: c.content, role: c.from === route.to ? ('user' as const) : ('assistant' as const), })) // build the messages to send to the provider const messages = [ { content: fromConfig.role, role: 'system' as const, }, // get the history of chats between the two nodes ...chatHistory, ] // get the functions that the node can call const functions = fromConfig.functions ?.map(name => this.functions.get(name)) .filter(a => !!a) as Function.FunctionConfig[] | undefined const provider = this.getProviderForConfig({ ...this.defaultProvider, ...fromConfig, }) // get the chat completion const content = await this.handleExecution(provider, messages, functions) this.newMessage({...route, content}) return content }
/** * Ask the for the AI provider to generate a reply to the chat. * * @param route.to The node that sent the chat. * @param route.from The node that will reply to the chat. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L628-L681
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.continue
public async continue(feedback?: string | null) { const lastChat = this._chats.at(-1) if (!lastChat || lastChat.state !== 'interrupt') { throw new Error('No chat to continue') } // remove the last chat's that was interrupted this._chats.pop() const {from, to} = lastChat if (this.hasReachedMaximumRounds(from, to)) { throw new Error('Maximum rounds reached') } if (feedback) { const message = { from, to, content: feedback, } // register the message in the chat history this.newMessage(message) // ask the node to reply await this.chat({ to: message.from, from: message.to, }) } else { await this.chat({from, to}) } return this }
/** * Continue the chat from the last interruption. * If the last chat was not an interruption, it will throw an error. * Provide a feedback where it was interrupted if you want to. * * @param feedback The feedback to the interruption if any. * @returns */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L739-L774
d66dfddae5c7b8c974cbee442707a04635333181
aibitat
github_2023
wladpaiva
typescript
AIbitat.retry
public async retry() { const lastChat = this._chats.at(-1) if (!lastChat || lastChat.state !== 'error') { throw new Error('No chat to retry') } // remove the last chat's that threw an error const {from, to} = this._chats.pop()! await this.chat({from, to}) return this }
/** * Retry the last chat that threw an error. * If the last chat was not an error, it will throw an error. */
https://github.com/wladpaiva/aibitat/blob/d66dfddae5c7b8c974cbee442707a04635333181/src/index.ts#L780-L791
d66dfddae5c7b8c974cbee442707a04635333181