repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
ha-fusion
github_2023
matt8707
typescript
KonvaViewer.ripple
private ripple(x: number, y: number) { const shape = new Konva.Circle({ x, y, fill: 'rgba(255, 255, 255, 0.75)' }); this.layer.add(shape); const duration = 380; const radius = 35; const animation = new Konva.Animation((frame) => { if (!frame) return; const progress = Math.min(frame.time / duration, 1); shape.radius(Konva.Easings.StrongEaseOut(progress, 0, radius, 1)); shape.opacity(Konva.Easings.StrongEaseOut(progress, 1, -1, 1)); if (progress >= 1) { animation.stop(); shape.destroy(); } }, this.layer).start(); }
/** * Handle ripple effect */
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L281-L305
25c374d31ccf1ea05aaf324d473ff975181c0308
ha-fusion
github_2023
matt8707
typescript
KonvaViewer.destroyViewer
public destroyViewer() { this.unsubscribe?.(); super.destroyBase(); }
/** * Destroy konva */
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/lib/Modal/PictureElements/konvaViewer.ts#L310-L313
25c374d31ccf1ea05aaf324d473ff975181c0308
ha-fusion
github_2023
matt8707
typescript
loadFile
async function loadFile(file: string) { try { const data = await readFile(file, 'utf8'); if (!data.trim()) { return {}; // file is empty, early return object } else { return file.endsWith('.yaml') ? yaml.load(data) : JSON.parse(data); } } catch (error) { if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') { // console.error(`No existing file found for ${file}`); } else { console.error(`Error reading or parsing ${file}:`, error); } return {}; } }
/** * Loads a yaml/json file and returns parsed data */
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/routes/+page.server.ts#L12-L28
25c374d31ccf1ea05aaf324d473ff975181c0308
ha-fusion
github_2023
matt8707
typescript
loadFile
async function loadFile(filePath: string) { try { const data = readFileSync(filePath, 'utf8'); if (!data.trim()) { // file is empty, early return object return {}; } else { return filePath.endsWith('.yaml') ? yaml.load(data) : JSON.parse(data); } } catch (err) { if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') { // console.error(`No existing file found for ${file}`); } else { console.error(`Error reading or parsing ${filePath}:`, err); } return {}; } }
/** * Load file. */
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/routes/_api/youtube/+server.ts#L180-L198
25c374d31ccf1ea05aaf324d473ff975181c0308
ha-fusion
github_2023
matt8707
typescript
saveFile
async function saveFile(credentials: any) { try { const data = JSON.stringify(credentials, null, '\t') + '\n'; writeFileSync(credentialsFilePath, data); } catch (err) { console.error('Failed to save credentials:', err); } }
/** * Save file. */
https://github.com/matt8707/ha-fusion/blob/25c374d31ccf1ea05aaf324d473ff975181c0308/src/routes/_api/youtube/+server.ts#L203-L210
25c374d31ccf1ea05aaf324d473ff975181c0308
unibest
github_2023
codercup
typescript
reset
const reset = () => { userInfo.value = { ...initState } }
// 一般没有reset需求,不需要的可以删除
https://github.com/codercup/unibest/blob/3ac697814116bbcb6c067d60d432deb6efba51af/src/store/user.ts#L19-L21
3ac697814116bbcb6c067d60d432deb6efba51af
unibest
github_2023
codercup
typescript
http
const http = <T>(options: CustomRequestOptions) => { // 1. 返回 Promise 对象 return new Promise<T>((resolve, reject) => { uni.request({ ...options, dataType: 'json', // #ifndef MP-WEIXIN responseType: 'json', // #endif // 响应成功 success(res) { // 状态码 2xx,参考 axios 的设计 if (res.statusCode >= 200 && res.statusCode < 300) { // 2.1 提取核心数据 res.data resolve(res.data as T) } else if (res.statusCode === 401) { // 401错误 -> 清理用户信息,跳转到登录页 // userStore.clearUserInfo() // uni.navigateTo({ url: '/pages/login/login' }) reject(res) } else { // 其他错误 -> 根据后端错误信息轻提示 !options.hideErrorToast && uni.showToast({ icon: 'none', title: (res.data as T & { msg?: string })?.msg || '请求错误', }) reject(res) } }, // 响应失败 fail(err) { uni.showToast({ icon: 'none', title: '网络错误,换个网络试试', }) reject(err) }, }) }) }
/** * 请求方法: 主要是对 uni.request 的封装,去适配 openapi-ts-request 的 request 方法 * @param options 请求参数 * @returns 返回 Promise 对象 */
https://github.com/codercup/unibest/blob/3ac697814116bbcb6c067d60d432deb6efba51af/src/utils/request.ts#L8-L48
3ac697814116bbcb6c067d60d432deb6efba51af
remote-storage
github_2023
FrigadeHQ
typescript
RemoteStorage.getItem
async getItem<T>(key: string, fetchOptions?: any): Promise<T> { const response = await this.call('GET', `${apiPrefix}${key}`, fetchOptions, null) // Check for 404 and return null if so if (response.status === 404) { return null } const data = await response.text() // Check if valid JSON if (!data.startsWith('{') && !data.startsWith('[')) { if (data === 'true') { return true as unknown as T } if (data === 'false') { return false as unknown as T } if (!isNaN(Number(data))) { return Number(data) as unknown as T } return data as T } return JSON.parse(data) as T }
/** * Get an item from remote storage * @param key the key that corresponds to the item to get * @param fetchOptions optional fetch options to pass to the underlying fetch call. Currently only headers for authorization are supported. */
https://github.com/FrigadeHQ/remote-storage/blob/d1a1d712866ca473e1bd781a3c6e35544a327fd2/packages/js-client/src/core/remote-storage.ts#L40-L62
d1a1d712866ca473e1bd781a3c6e35544a327fd2
remote-storage
github_2023
FrigadeHQ
typescript
RemoteStorage.setItem
async setItem<T>(key: string, value: T, fetchOptions?: any): Promise<void> { await this.call('PUT', `${apiPrefix}${key}`, fetchOptions, value) }
/** * Set an item in remote storage * @param key the key that corresponds to the item to set * @param value the value to set * @param fetchOptions optional fetch options to pass to the underlying fetch call. Currently only headers for authorization are supported. */
https://github.com/FrigadeHQ/remote-storage/blob/d1a1d712866ca473e1bd781a3c6e35544a327fd2/packages/js-client/src/core/remote-storage.ts#L70-L72
d1a1d712866ca473e1bd781a3c6e35544a327fd2
remote-storage
github_2023
FrigadeHQ
typescript
RemoteStorage.removeItem
async removeItem(key: string, fetchOptions?: any): Promise<void> { await this.call('DELETE', `${apiPrefix}${key}`, fetchOptions, null) }
/** * Remove an item from remote storage * @param key the key that corresponds to the item to remove * @param fetchOptions optional fetch options to pass to the underlying fetch call. Currently only headers for authorization are supported. */
https://github.com/FrigadeHQ/remote-storage/blob/d1a1d712866ca473e1bd781a3c6e35544a327fd2/packages/js-client/src/core/remote-storage.ts#L79-L81
d1a1d712866ca473e1bd781a3c6e35544a327fd2
transformerlab-app
github_2023
transformerlab
typescript
getWSLHomeDir
async function getWSLHomeDir() { // We do not have to change the default encoding because this command // is run on linux, not windows, so we get utf-8 const { stdout, stderr } = await awaitExec('wsl wslpath -w ~'); if (stderr) console.error(`stderr: ${stderr}`); const homedir = stdout.trim(); return homedir; }
// WINDOWS SPECIFIC FUNCTION for figuring out how to access WSL file system
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/main/util.ts#L27-L34
e7180a976501e7ec415b582d5005442215fe9850
transformerlab-app
github_2023
transformerlab
typescript
getTransformerLabRootDir
async function getTransformerLabRootDir() { return isPlatformWindows() ? path.join(await getWSLHomeDir(), '.transformerlab') : transformerLabRootDir; }
// Need to wrap directories in functions to cover the windows-specific case
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/main/util.ts#L37-L41
e7180a976501e7ec415b582d5005442215fe9850
transformerlab-app
github_2023
transformerlab
typescript
formatJobData
function formatJobData(data) { let json_data = JSON.stringify(data, undefined, 4); return json_data; }
// convert JSON data in to a more readable format
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/renderer/components/Experiment/Export/ExportDetailsModal.tsx#L14-L17
e7180a976501e7ec415b582d5005442215fe9850
transformerlab-app
github_2023
transformerlab
typescript
importRun
async function importRun(model_ids: Iterator) { // storing results let totalImports = 0; let successfulImports = 0; let error_msg = ""; let next = model_ids.next(); while(!next.done) { // In the iterator, each item is a key (model_id) and a value (model_source) // this is just how it gets produced from the form const model_id = next.value[0]; const model_source = next.value[1]; console.log("Importing " + model_id); const api_endpoint = model_source == "local" ? chatAPI.Endpoints.Models.ImportFromLocalPath(model_id) : chatAPI.Endpoints.Models.ImportFromSource(model_source, model_id); const response = await fetch(api_endpoint); // Read the response to see if it was successful and report any errors let response_error = ""; if (response.ok) { const response_json = await response.json(); if (response_json.status == "success") { successfulImports++; } else if ("message" in response_json) { response_error = response_json.message; } else { response_error = "Unspecified error"; } } else { response_error = "API error"; } // Log errors if (response_error) { const new_error = `${model_id}: ${response_error}`; console.log(new_error); error_msg += `${new_error}\n`; } totalImports++; next = model_ids.next(); } const result_msg = `${successfulImports} of ${totalImports} models imported.`; console.log(result_msg); if (error_msg) { alert(`${result_msg}\n\nErrors:\n${error_msg}`); } else { alert(result_msg); } return; }
/* * This funciton takes an Iterator with model information and tries to import * each of those models through individual calls to the backend. * * When it completes it displays an alert with results. */
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/renderer/components/ModelZoo/ImportModelsModal.tsx#L51-L104
e7180a976501e7ec415b582d5005442215fe9850
transformerlab-app
github_2023
transformerlab
typescript
debounce
const debounce = (func: Function, wait: number) => { let timeout: NodeJS.Timeout; return (...args: any[]) => { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; };
// Debounce function
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/renderer/components/OutputTerminal/index.tsx#L8-L14
e7180a976501e7ec415b582d5005442215fe9850
transformerlab-app
github_2023
transformerlab
typescript
convertSlashInUrl
function convertSlashInUrl(url: string) { return url.replace(/\//g, '~~~'); }
// We do this because the API does not like slashes in the URL
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/renderer/lib/transformerlab-api-sdk.ts#L979-L981
e7180a976501e7ec415b582d5005442215fe9850
transformerlab-app
github_2023
transformerlab
typescript
fetcher
const fetcher = (...args: any[]) => fetch(...args).then((res) => { if (!res.ok) { const error = new Error('An error occurred fetching ' + res.url); error.response = res.json(); error.status = res.status; console.log(res); throw error; } return res.json(); });
/** * SWR hooks */
https://github.com/transformerlab/transformerlab-app/blob/e7180a976501e7ec415b582d5005442215fe9850/src/renderer/lib/transformerlab-api-sdk.ts#L1796-L1806
e7180a976501e7ec415b582d5005442215fe9850
ComfyUI-Crystools
github_2023
crystian
typescript
CrystoolsMonitor.createSettingsRate
createSettingsRate = (): void => { this.settingsRate = { id: 'Crystools.RefreshRate', name: 'Refresh per second', category: ['Crystools', this.menuPrefix + ' Configuration', 'refresh'], tooltip: 'This is the time (in seconds) between each update of the monitors, 0 means no refresh', type: 'slider', attrs: { min: 0, max: 2, step: .25, }, defaultValue: .5, // @ts-ignore onChange: async(value: string): Promise<void> => { let valueNumber: number; try { valueNumber = parseFloat(value); if (isNaN(valueNumber)) { throw new Error('invalid value'); } } catch (error) { console.error(error); return; } try { await this.updateServer({rate: valueNumber}); } catch (error) { console.error(error); return; } const data = { cpu_utilization: 0, device: 'cpu', gpus: [ { gpu_utilization: 0, gpu_temperature: 0, vram_total: 0, vram_used: 0, vram_used_percent: 0, }, ], hdd_total: 0, hdd_used: 0, hdd_used_percent: 0, ram_total: 0, ram_used: 0, ram_used_percent: 0, }; if (valueNumber === 0) { this.monitorUI.updateDisplay(data); } this.monitorUI?.updateAllAnimationDuration(valueNumber); }, }; }
/** * for the settings menu * @param monitorSettings */
https://github.com/crystian/ComfyUI-Crystools/blob/72e2e9af4a6b9a58ca5d753cacff37ba1ff9bfa8/web/monitor.ts
72e2e9af4a6b9a58ca5d753cacff37ba1ff9bfa8
ComfyUI-Crystools
github_2023
crystian
typescript
CrystoolsProgressBar.createSettings
createSettings = (): void => { app.ui.settings.addSetting({ id: this.idShowProgressBar, name: 'Show progress bar', category: ['Crystools', this.menuPrefix + ' Progress Bar', 'Show'], tooltip: 'This apply only on "Disabled" (old) menu', type: 'boolean', defaultValue: this.defaultShowStatus, onChange: this.progressBarUI.showProgressBar, }); }
// not on setup because this affect the order on settings, I prefer to options at first
https://github.com/crystian/ComfyUI-Crystools/blob/72e2e9af4a6b9a58ca5d753cacff37ba1ff9bfa8/web/progressBar.ts
72e2e9af4a6b9a58ca5d753cacff37ba1ff9bfa8
ComfyUI-Crystools
github_2023
crystian
typescript
ProgressBarUI.showProgressBar
updateDisplay = (currentStatus: EStatus, timeStart: number, currentProgress: number): void => { if (!(this.showSectionFlag && this.showProgressBarFlag)) { return; } if (!(this.htmlProgressLabelRef && this.htmlProgressSliderRef)) { console.error('htmlProgressLabelRef or htmlProgressSliderRef is undefined'); return; } // console.log('only if showSection and progressBar', timeStart, currentProgress); this.currentStatus = currentStatus; this.timeStart = timeStart; this.currentProgress = currentProgress; if (currentStatus === EStatus.executed) { // finished this.htmlProgressLabelRef.innerHTML = 'cached'; const timeElapsed = Date.now() - timeStart; if (timeStart > 0 && timeElapsed > 0) { this.htmlProgressLabelRef.innerHTML = new Date(timeElapsed).toISOString().substr(11, 8); } this.htmlProgressSliderRef.style.width = '0'; } else if (currentStatus === EStatus.execution_error) { // an error occurred this.htmlProgressLabelRef.innerHTML = 'ERROR'; this.htmlProgressSliderRef.style.backgroundColor = 'var(--error-text)'; } else if (currentStatus === EStatus.executing) { // on going this.htmlProgressLabelRef.innerHTML = `${currentProgress}%`; this.htmlProgressSliderRef.style.width = this.htmlProgressLabelRef.innerHTML; this.htmlProgressSliderRef.style.backgroundColor = 'green'; // by reset the color } }
// remember it can't have more parameters because it is used on settings automatically
https://github.com/crystian/ComfyUI-Crystools/blob/72e2e9af4a6b9a58ca5d753cacff37ba1ff9bfa8/web/progressBarUI.ts
72e2e9af4a6b9a58ca5d753cacff37ba1ff9bfa8
zotero-attanger
github_2023
MuiseDestiny
typescript
onStartup
async function onStartup() { await Promise.all([ Zotero.initializationPromise, Zotero.unlockPromise, Zotero.uiReadyPromise, ]); initLocale(); Zotero.PreferencePanes.register( { pluginID: config.addonID, src: rootURI + "chrome/content/preferences.xhtml", label: "Attanger", image: `chrome://${config.addonRef}/content/icons/favicon.png`, // defaultXUL: true, } ); await onMainWindowLoad(window); }
// import { getPref } from "./utils/prefs";
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/hooks.ts#L8-L25
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
onPrefsEvent
async function onPrefsEvent(type: string, data: { [key: string]: any }) { switch (type) { case "load": registerPrefsScripts(data.window); break; default: return; } }
/** * This function is just an example of dispatcher for Preference UI events. * Any operations should be placed in a function to keep this funcion clear. * @param type event type * @param data event data */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/hooks.ts#L52-L60
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
attachNewFileCallback
const attachNewFileCallback = async () => { const item = ZoteroPane.getSelectedItems()[0]; await attachNewFile({ libraryID: item.libraryID, parentItemID: item.id, collections: undefined, }); };
// 附加新文件
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L127-L134
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
getAttachmentItems
function getAttachmentItems(hasParent = true) { const attachmentItems = []; for (const item of ZoteroPane.getSelectedItems()) { if (item.isAttachment() && (hasParent ? !item.isTopLevelItem() : true)) { attachmentItems.push(item); } else if (item.isRegularItem()) { item .getAttachments() .map((id) => Zotero.Items.get(id)) .filter((item) => item.isAttachment()) .forEach((item) => attachmentItems.push(item)); } } return attachmentItems; }
/** * 获取所有附件条目 */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L347-L362
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
getLastFileInFolder
function getLastFileInFolder(path: string) { const dir = Zotero.File.pathToFile(path); const files = dir.directoryEntries; let lastmod = { lastModifiedTime: 0, path: undefined }; while (files.hasMoreElements()) { // get next file const file = files.getNext().QueryInterface(Components.interfaces.nsIFile); // skip if directory, hidden file or certain file types if (file.isDirectory() || file.isHidden()) { continue; } // check modification time if (file.isFile() && file.lastModifiedTime > lastmod.lastModifiedTime) { lastmod = file; } } // return sorted directory entries return lastmod.path; }
/** * Get the last modified file from directory * @param {string} path Path to directory * @return {string} Path to last modified file in folder or undefined. */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L565-L583
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
renameFile
async function renameFile(attItem: Zotero.Item, retry = 0) { if (!checkFileType(attItem)) { return; } const file = (await attItem.getFilePathAsync()) as string; const parentItemID = attItem.parentItemID as number; const parentItem = await Zotero.Items.getAsync(parentItemID); // getFileBaseNameFromItem let newName = Zotero.Attachments.getFileBaseNameFromItem(parentItem); const extRE = /\.[^.]+$/; const origFilename = PathUtils.split(file).pop() as string; const ext = origFilename.match(extRE); if (ext) { newName = newName + ext[0]; } const origFilenameNoExt = origFilename.replace(extRE, ""); const renamed = await attItem.renameAttachmentFile(newName, false, true); if (renamed !== true) { ztoolkit.log("renamed = " + renamed, "newName", newName); await Zotero.Promise.delay(3e3); if (retry < 5) { return await renameFile(attItem, retry + 1); } } // const origTitle = attItem.getField("title"); // if (origTitle == origFilename || origTitle == origFilenameNoExt) { attItem.setField("title", newName); await attItem.saveTx(); // } return attItem; }
/** * 重命名文件,但不重命名Zotero内显示的名称 - 来自Zotero官方代码 * @param item * @returns */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L590-L621
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
getCollectionPathsOfItem
function getCollectionPathsOfItem(item: Zotero.Item) { const getCollectionPath = function (collectionID: number): string { const collection = Zotero.Collections.get( collectionID, ) as Zotero.Collection; if (!collection.parentID) { return collection.name; } return ( getCollectionPath(collection.parentID) + addon.data.folderSep + collection.name ); }; try { return [ZoteroPane.getSelectedCollection()!.id].map(getCollectionPath)[0]; } catch { return item.getCollections().map(getCollectionPath).slice(0, 1)[0]; } }
/** * 获取Item的分类路径 * @param item * @returns */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L847-L866
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
getValidFolderName
function getValidFolderName(folderName: string): string { // Replace illegal folder name characters if (getPref("slashAsSubfolderDelimiter")) { folderName = folderName.replace(/[\\:*?"<>|]/g, ""); } else { // eslint-disable-next-line no-useless-escape folderName = folderName.replace(/[\/\\:*?"<>|]/g, ""); } // Replace newlines and tabs (which shouldn't be in the string in the first place) with spaces folderName = folderName.replace(/[\r\n\t]+/g, " "); // Replace various thin spaces folderName = folderName.replace(/[\u2000-\u200A]/g, " "); // Replace zero-width spaces folderName = folderName.replace(/[\u200B-\u200E]/g, ""); // Strip characters not valid in XML, since they won't sync and they're probably unwanted // eslint-disable-next-line no-control-regex folderName = folderName.replace( /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ud800-\udfff\ufffe\uffff]/g, "", ); // Normalize to NFC folderName = folderName.normalize(); // Replace bidi isolation control characters folderName = folderName.replace(/[\u2068\u2069]/g, ""); // Don't allow hidden files folderName = folderName.replace(/^\./, ""); // Don't allow blank or illegal names if (!folderName || folderName == "." || folderName == "..") { folderName = "_"; } return folderName; }
/** * 从文件名中删除非法字符 * Modified from Zotero.File.getValidFileName * @param folderName * @returns */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L874-L905
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
showAttachmentItem
function showAttachmentItem(attItem: Zotero.Item) { const popupWin = new ztoolkit.ProgressWindow("Attanger", { closeTime: -1, closeOtherProgressWindows: true, }); // 显示父行 if (attItem && attItem.isTopLevelItem()) { popupWin .createLine({ text: (ZoteroPane.getSelectedCollection() as Zotero.Collection).name, icon: addon.data.icons.collection, }) .show(); } else { const parentItem = attItem.parentItem as Zotero.Item; popupWin .createLine({ text: parentItem.getField("title") as string, icon: parentItem.getImageSrc(), }) .show(); } // 显示附件行 popupWin.createLine({ text: attItem.getField("title") as string, icon: attItem.getImageSrc().replace("pdflink", "pdf-link"), }); // 设置透明度 调整缩进 // @ts-ignore lines私有变量 const lines = popupWin.lines; waitUntil( () => lines?.[1]?._hbox, () => { const hbox = lines?.[1]?._hbox; if (hbox) { hbox.style.opacity = "1"; hbox.style.marginLeft = "2em"; } }, 10, ); popupWin.startCloseTimer(3000); }
/** * 向popupWin添加附件行 * @param attItem * @param type */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L925-L967
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
removeEmptyFolder
async function removeEmptyFolder(path: string | nsIFile) { if (!getPref("autoRemoveEmptyFolder") as boolean) { return false; } if (!path as boolean) { return false; } const folder = Zotero.File.pathToFile(path); let rootFolders = [Zotero.getStorageDirectory().path]; const source_dir = getPref("sourceDir") as string; const dest_dir = getPref("destDir") as string; if (source_dir != "") { rootFolders.push(source_dir); } if (dest_dir != "") { rootFolders.push(dest_dir); } rootFolders = rootFolders.map((path) => PathUtils.normalize(path)); // 不属于插件相关根目录,不处理 if (!rootFolders.find((dir) => folder.path.startsWith(dir))) { return false; } const files = folder.directoryEntries; let fileCount = 0; while (files.hasMoreElements()) { const f = files.getNext().QueryInterface(Components.interfaces.nsIFile); fileCount++; if (f.leafName !== ".DS_Store" && f.leafName !== "Thumbs.db") { return true; } else if (fileCount > 1) { break; } } ztoolkit.log("Remove empty folder: ", folder.path); removeFile(folder, true); return await removeEmptyFolder(PathUtils.parent(folder.path) as string); }
/** * Remove empty folders recursively within zotfile directories * @param {String|nsIFile} path Folder as nsIFile. * @return {void} */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L974-L1010
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
transferItem
async function transferItem( originalItem: Zotero.Item, targetItem: Zotero.Item, ) { ztoolkit.log("迁移标注"); await Zotero.DB.executeTransaction(async function () { await Zotero.Items.moveChildItems(originalItem, targetItem); }); // 迁移相关 ztoolkit.log("迁移相关"); await Zotero.Relations.copyObjectSubjectRelations(originalItem, targetItem); // 迁移索引 ztoolkit.log("迁移索引"); await Zotero.DB.executeTransaction(async function () { await Zotero.Fulltext.transferItemIndex(originalItem, targetItem); }); // 迁移标签 ztoolkit.log("迁移标签"); targetItem.setTags(originalItem.getTags()); // 迁移PDF笔记 ztoolkit.log("迁移PDF笔记"); targetItem.setNote(originalItem.getNote()); await targetItem.saveTx(); }
/** * 迁移数据 */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L1015-L1038
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
addSuffixToFilename
async function addSuffixToFilename(filename: string, suffix?: string) { let incr = 0; let destPath, destName; // 提取文件名(不含扩展名)和扩展名 const [root, ext] = (() => { const parts = filename.split("."); const ext = parts.length > 1 ? parts.pop() : ""; return [parts.join("."), ext]; })(); if (suffix) { // 直接返回不在考虑是否存在 return ext ? `${root}_${suffix}.${ext}` : `${root}_${suffix}`; } while (true) { // 如果存在数字后缀,则添加它 if (incr) { destName = ext ? `${root}_${incr}.${ext}` : `${root}_${incr}`; } else { destName = filename; } destPath = destName; // 假设 destPath 是目标文件路径 // 检查文件是否存在 if (await IOUtils.exists(destPath)) { incr++; } else { return destPath; } } }
/** * 为文件添加后缀,如果存在 * @param filename * @returns */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L1045-L1076
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
getPlainTitle
function getPlainTitle(item: Zotero.Item) { return item .getDisplayTitle() .replace(/<(?:i|b|sub|sub)>(.+?)<\/(?:i|b|sub|sub)>/g, "$1"); }
/** * 清除文件名中的格式标记,返回纯文本的标题。 * 虽然通常用于与文件名进行比较,但并不调用Zotero.File.getValidFileName进行规范化。 */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L1108-L1112
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
getPDFData
async function getPDFData(path: string) { return Zotero.PDFWorker._enqueue(async () => { const buf = new Uint8Array(await IOUtils.read(path)).buffer; let result = {}; try { result = await Zotero.PDFWorker._query("getRecognizerData", { buf }, [ buf, ]); } catch (e: any) { const error = new Error( `Worker 'getRecognizerData' failed: ${JSON.stringify({ error: e.message, })}`, ); try { error.name = JSON.parse(e.message).name; } catch (e: any) { ztoolkit.log(e); } ztoolkit.log(error); throw error; } ztoolkit.log(`Extracted PDF recognizer data for path ${path}`); return result; }, false); }
/** * 对Zotero.PDFWorker.getRecognizerData的重写,以便支持直接给出路径。 */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/modules/menu.ts#L1139-L1166
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
initLocale
function initLocale() { const l10n = new ( typeof Localization === "undefined" ? ztoolkit.getGlobal("Localization") : Localization )([`${config.addonRef}-addon.ftl`], true); addon.data.locale = { current: l10n, }; }
/** * Initialize locale data */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/utils/locale.ts#L8-L17
6c52844cc54cb78299c134a443802060f1e11dc1
zotero-attanger
github_2023
MuiseDestiny
typescript
isWindowAlive
function isWindowAlive(win?: Window) { return win && !Components.utils.isDeadWrapper(win) && !win.closed; }
/** * Check if the window is alive. * Useful to prevent opening duplicate windows. * @param win */
https://github.com/MuiseDestiny/zotero-attanger/blob/6c52844cc54cb78299c134a443802060f1e11dc1/src/utils/window.ts#L8-L10
6c52844cc54cb78299c134a443802060f1e11dc1
ollama-grid-search
github_2023
dezoito
typescript
atomWithLocalStorage
const atomWithLocalStorage = (key: string, initialValue: unknown) => { // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const getInitialValue = () => { const item = localStorage.getItem(key); if (item !== null) { return JSON.parse(item); } return initialValue; }; const baseAtom = atom(getInitialValue()); const derivedAtom = atom( (get) => get(baseAtom), (get, set, update) => { const nextValue = typeof update === "function" ? update(get(baseAtom)) : update; set(baseAtom, nextValue); localStorage.setItem(key, JSON.stringify(nextValue)); // console.log('I set a value in local storage', localStorage.getItem(key)) }, ); return derivedAtom; };
// Refs https://jotai.org/docs/guides/persistence
https://github.com/dezoito/ollama-grid-search/blob/6438a47a0ffaac150eb91c3fcdb82efaaa7641d0/src/Atoms.ts#L15-L36
6438a47a0ffaac150eb91c3fcdb82efaaa7641d0
ollama-grid-search
github_2023
dezoito
typescript
getInitialValue
const getInitialValue = () => { const item = localStorage.getItem(key); if (item !== null) { return JSON.parse(item); } return initialValue; };
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
https://github.com/dezoito/ollama-grid-search/blob/6438a47a0ffaac150eb91c3fcdb82efaaa7641d0/src/Atoms.ts#L17-L23
6438a47a0ffaac150eb91c3fcdb82efaaa7641d0
ollama-grid-search
github_2023
dezoito
typescript
findVariables
const findVariables = (text: string) => { const regex = /\[(\w+)\]/g; const variables: Array<{ start: number; end: number; value: string; }> = []; let match; while ((match = regex.exec(text)) !== null) { variables.push({ start: match.index, end: match.index + match[0].length, value: match[0], }); } return variables; };
// Find all variables in the text
https://github.com/dezoito/ollama-grid-search/blob/6438a47a0ffaac150eb91c3fcdb82efaaa7641d0/src/components/prompt-textarea.tsx#L31-L48
6438a47a0ffaac150eb91c3fcdb82efaaa7641d0
ollama-grid-search
github_2023
dezoito
typescript
selectNextVariable
const selectNextVariable = (afterPosition: number) => { const variables = findVariables(value); if (variables.length === 0) { setSelectedVariable(null); return; } // Find the next variable after the current position const nextVariable = variables.find((v) => v.start > afterPosition); // If no next variable is found, circle back to the first one const variableToSelect = nextVariable || variables[0]; if (variableToSelect && textareaRef.current) { textareaRef.current.focus(); textareaRef.current.setSelectionRange( variableToSelect.start, variableToSelect.end, ); setSelectedVariable(variableToSelect); } else { setSelectedVariable(null); } };
// Select the next variable after the given position
https://github.com/dezoito/ollama-grid-search/blob/6438a47a0ffaac150eb91c3fcdb82efaaa7641d0/src/components/prompt-textarea.tsx#L51-L74
6438a47a0ffaac150eb91c3fcdb82efaaa7641d0
ollama-grid-search
github_2023
dezoito
typescript
handlePaste
const handlePaste = (e: React.ClipboardEvent<HTMLTextAreaElement>) => { if (selectedVariable) { e.preventDefault(); const pastedText = e.clipboardData.getData("text"); const beforeSelection = value.slice(0, selectedVariable.start); const afterSelection = value.slice(selectedVariable.end); const newValue = beforeSelection + pastedText + afterSelection; onChange(newValue); // Select next variable after a short delay setTimeout( () => selectNextVariable(selectedVariable.start + pastedText.length), 0, ); } };
// Handle paste events
https://github.com/dezoito/ollama-grid-search/blob/6438a47a0ffaac150eb91c3fcdb82efaaa7641d0/src/components/prompt-textarea.tsx#L90-L106
6438a47a0ffaac150eb91c3fcdb82efaaa7641d0
ollama-grid-search
github_2023
dezoito
typescript
refetchCurrentQuery
const refetchCurrentQuery = async () => { setEnabled(true); await asyncSleep(1); queryClient.refetchQueries({ queryKey: ["get_inference", params], }); await asyncSleep(1); setEnabled(false); };
// Temporarily re-enables the current query
https://github.com/dezoito/ollama-grid-search/blob/6438a47a0ffaac150eb91c3fcdb82efaaa7641d0/src/components/results/iteration-result.tsx#L74-L83
6438a47a0ffaac150eb91c3fcdb82efaaa7641d0
Quantum
github_2023
rodyherrera
typescript
signToken
const signToken = (identifier: string): string => { const expiresIn = `${process.env.JWT_EXPIRATION_DAYS}d`; return jwt.sign({ id: identifier }, process.env.SECRET_KEY!, { expiresIn }); };
/** * Generates a JSON Web Token (JWT) for authentication. * * @param {string} identifier - The user's unique identifier (typically their database ID). * @returns {string} - The signed JWT. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/authentication.ts#L41-L46
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
createAndSendToken
const createAndSendToken = (res: any, statusCode: number, user: any): void => { const token = signToken(user._id); user.password = undefined; user.__v = undefined; deleteJWTCookie(res); res.cookie('jwt', token, { expires: new Date(Date.now() + Number(process.env.JWT_EXPIRATION_DAYS) * 24 * 60 * 60 * 1000), httpOnly: true }); res.status(statusCode).json({ status: 'success', data: { user } }); };
/** * Creates a new JWT and sends it in the response along with user data. * * @param {Object} res - The Express response object. * @param {number} statusCode - HTTP status code to send in the response. * @param {Object} user - The user object to include in the response. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/authentication.ts#L55-L70
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
repositoryOperationHandler
const repositoryOperationHandler = async (repository: any, action: string) => { await repository.populate({ path: 'user', select: 'username container email', populate: { path: 'github', select: 'accessToken username' } }); const container = await DockerContainer.findOne({ repository }); if(!container){ throw new RuntimeError('Deployment::Container::NotFound', 404); } const containerService = new DockerContainerService(container); const githubService = new Github(repository.user, repository); const currentDeploymentId = repository.deployments?.[0]; if(!currentDeploymentId){ throw new RuntimeError('Deployment::CurrentDeployment::NotFound', 404); } const currentDeployment = await Deployment.findById(currentDeploymentId); if(!currentDeployment){ throw new RuntimeError('Deployment::InvalidReference', 404); } const { githubDeploymentId } = currentDeployment; currentDeployment.status = 'queued'; await currentDeployment.save(); githubService.updateDeploymentStatus(githubDeploymentId, 'queued'); try{ switch(action){ case 'restart': await containerService.restart(); await githubService.updateDeploymentStatus(githubDeploymentId, 'success'); currentDeployment.status = 'success'; sendEmail({ to: repository.user.email, subject: `You have successfully restarted "${repository.alias}"`, html: `Hello @${repository.user.username}, the container is currently restarting, the services will be redeployed and the installation, construction and execution commands will be executed.` }); break; case 'stop': await containerService.stop(); await githubService.updateDeploymentStatus(githubDeploymentId, 'inactive'); currentDeployment.status = 'stopped'; sendEmail({ to: repository.user.email, subject: `Container "${repository.alias}" shut down successfully.`, html: `Hi @${repository.user.username}, the container has been shut down successfully.` }); break; case 'start': await containerService.start(); await githubService.updateDeploymentStatus(githubDeploymentId, 'success'); currentDeployment.status = 'success'; sendEmail({ to: repository.user.email, subject: `Starting and deploying "${repository.alias}"`, html: `Hi @${repository.user.username}, the construction commands will be executed to proceed with the deployment.` }); break; default: throw new RuntimeError('Deployment::Invalid::Action', 400); } }catch(error){ currentDeployment.status = 'failure'; githubService.updateDeploymentStatus(githubDeploymentId, 'failure'); }finally{ await currentDeployment.save(); return currentDeployment; } };
/** * Handles repository-related actions (restart, stop, start). Interacts with the GitHub API for deployment status updates. * * @param {Object} req - The Express request object. * @param {Object} res - The Express response object. * @returns {Promise<void>} */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/deployment.ts#L53-L124
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
getCPUUsageSnapshot
const getCPUUsageSnapshot = (): { idle: number, total: number } => { let totalIdle = 0; let totalTick = 0; const cpus = os.cpus(); for(let i = 0; i < cpus.length; i++){ const cpu = cpus[i]; for(const type in cpu.times){ totalTick += (cpu.times as any)[type]; } totalIdle += cpu.times.idle; } return { idle: totalIdle / cpus.length, total: totalTick / cpus.length }; };
/** * Calculates a single measurement of CPU usage statistics. * * @returns {Object} An object containing 'idle' and 'total' CPU usage metrics. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/server.ts#L24-L36
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
fetchRepository
const fetchRepository = async (repositoryId: string) => { return Repository .findById(repositoryId) .populate({ path: 'user', select: 'username email', populate: { path: 'github', select: 'accessToken username' } }) .populate('container'); };
/** * Fetches the repository details by ID. * @param {string} repositoryId - Repository ID. * @returns {Promise<any>} - The repository document. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/webhook.ts#L18-L30
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
handleRepositoryDeployment
const handleRepositoryDeployment = async (repository: any, githubService: Github) => { await Github.deleteLogAndDirectory('', repository.container.storagePath); return githubService.deployRepository(); };
/** * Deploys a new version of the repository. * @param {any} repository - The repository document. * @param {Github} githubService - GitHub service instance. * @returns {Promise<any>} - The deployment document. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/webhook.ts#L38-L41
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
updateDeploymentRecords
const updateDeploymentRecords = async (repository: any, user: any, deploymentId: string) => { await Promise.all([ User.updateOne({ _id: user._id }, { $push: { deployments: deploymentId } }), Repository.updateOne({ _id: repository._id }, { $push: { deployments: deploymentId } }), ]); repository.deployments.push(deploymentId); };
/** * Updates the deployment records in the database. * @param {any} repository - The repository document. * @param {any} user - The user document. * @param {mongoose.Types.ObjectId} deploymentId - The deployment ID. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/webhook.ts#L49-L55
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
sendDeploymentSuccessEmail
const sendDeploymentSuccessEmail = async (email: string, username: string, repositoryAlias: string) => { await sendEmail({ to: email, subject: `Deployment for "${repositoryAlias}" completed successfully.`, html: ` Hello @${username},<br><br> The "${repositoryAlias}" repository has been updated and we have deployed the new version. It should be available in a few moments.<br><br> Regards. `, }); };
/** * Sends an email notification about the successful deployment. * @param {string} email - Recipient email address. * @param {string} username - User's username. * @param {string} repositoryAlias - Repository alias. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/webhook.ts#L63-L74
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
parseError
const parseError = (err: Error) => { const errorMap: { [key: string]: any } = { CastError: { message: 'Database::Cast::Error', statusCode: 400 }, ValidationError: () => { const { errors } = err as any; const fields = Object.keys(errors); return { message: errors?.[fields?.[0]]?.message || 'Database::Validation::Error', statusCode: 401 } }, JsonWebTokenError: { message: 'JWT::Error', statusCode: 401 }, TokenExpiredError: { message: 'JWT::Expired', statusCode: 401 }, MongoServerError: (code: number) => { if(code === 11000) return { message: 'Database::Duplicated::Fields', statusCode: 400 }; return { message: err.message, statusCode: (err as any).statusCode }; } }; const handler = errorMap[(err as any).name] || errorMap.MongoServerError; // Allow customizing messages for MongoServerError based on the error code return typeof handler === 'function' ? handler((err as any).status) : handler; };
/** * Maps common errors to informative messages and appropriate HTTP status codes. * * @param {Error} err - The error object to analyze. * @returns {Object} An object containing 'message' (string) and 'statusCode' (number). */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/common/globalErrorHandler.ts#L25-L46
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
errorHandler
const errorHandler = async (err: Error, req: Request, res: Response, next: NextFunction) => { (err as any).statusCode = (err as any).statusCode || 500; (err as any).message = err.message || 'Server Error'; if(err instanceof RuntimeError){ return res.status((err as any).statusCode).send({ status: 'error', message: err.message }); } // Parse error for consistent responses const { message, statusCode } = parseError(err); res.status(statusCode).send({ status: 'error', message }); };
/** * Express middleware for centralized error handling. * * @param {Error} err - The error object. * @param {import('express').Request} req - The Express request object. * @param {import('express').Response} res - The Express response object. * @param {import('express').NextFunction} next - The Express next function. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/controllers/common/globalErrorHandler.ts#L56-L65
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
createRepositoryContainer
const createRepositoryContainer = async (repository: IRepository): Promise<IDockerContainer> => { // TODO: Image SHOULD exists, because the main user container uses it. const image = await mongoose.model('DockerImage').findOne({ name: 'alpine', tag: 'latest' }); const network = await mongoose.model('DockerNetwork').create({ user: repository.user, driver: 'bridge', name: repository.alias }); const container = await mongoose.model('DockerContainer').create({ name: repository.alias, user: repository.user, repository: repository._id, image: image._id, network: network._id, command: '/bin/sh', isRepositoryContainer: true }); return container; };
// TODO: refactor with @models/user.ts - createUserContainer
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/models/repository.ts#L143-L161
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
removeWhitespace
const removeWhitespace = (str: string): string => { return str.replace(/\s/g, ''); }
/** * Remove all whitespace from a string. * @param {string} str - The string to process. * @returns {string} - The string without whitespace. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/models/user.ts#L175-L177
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
hashPassword
const hashPassword = async (password: string): Promise<string> => { const saltRounds = 12; return await bcrypt.hash(password, saltRounds); }
/** * Hash a password using bcrypt. * @param {string} password - The password to hash. * @returns {Promise<string>} - The hashed password. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/models/user.ts#L184-L187
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.deleteLogAndDirectory
static async deleteLogAndDirectory(logPath: string, directoryPath: string): Promise<void>{ try{ if(logPath) await fs.promises.rm(logPath); await fs.promises.rm(directoryPath, { recursive: true }); }catch(error){ logger.error('@services/github.ts (deleteLogAndDirectory): CRITCAL ERROR -> Deletion failed: ' + (error as Error).message); } }
/** * Deletes a locally-stored log file and a working directory associated with a repository. * Used as a cleanup mechanism in case of errors. * * @param {string} logPath - Path to the log file to be deleted. * @param {string} directoryPath - Path to the directory to be deleted. * @returns {Promise<void>} - Resolves if deletion is successful, rejects with an error if not. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L62-L69
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.cloneRepository
async cloneRepository(branch: string): Promise<void>{ try{ const container = await this.getContainer(); if(!container){ throw new RuntimeError('Github::Container::NotFound', 404); } const repositoryInfo = await this.octokit.repos.get({ owner: this.userGithub.username, repo: this.repository.name }); const cloneEndpoint = repositoryInfo.data.private ? repositoryInfo.data.clone_url.replace('https://', `https://${this.userGithub.getDecryptedAccessToken()}@`) : repositoryInfo.data.clone_url; await exec(`git clone --branch ${branch} ${cloneEndpoint} ${container.storagePath}`); }catch(error){ logger.error('@services/github.ts (cloneRepository): ' + (error as Error).message); } }
/** * Clones a GitHub repository into a local directory. * * @returns {Promise<void>} - Resolves if the cloning process is successful, rejects with an error if not. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L81-L98
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.readEnvironmentVariables
async readEnvironmentVariables(): Promise<Record<string, string>>{ const container = await this.getContainer(); if(!container){ throw new RuntimeError('Github::Container::NotFound', 404); } const files = await simpleGit(container.storagePath).raw(['ls-tree', 'HEAD', '-r', '--name-only']); const envFiles = files.split('\n').filter(file => file.includes('.env')); const environmentVariables: Record<string, string> = {}; for(const envFile of envFiles){ const file = await simpleGit(container.storagePath).raw(['show', 'HEAD:' + envFile]); const lines = file.split('\n'); lines.forEach(line => { if(line.trim() === '' || line.trim().startsWith('#')){ return; } const [key, value] = line.split('='); environmentVariables[key.trim()] = value?.trim() || ''; }); } return environmentVariables; }
/** * Reads environment variables defined in `.env` files within a cloned repository. * * @returns {Promise<Object>} - An object containing key-value pairs of environment variables. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L105-L125
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.getLatestCommit
async getLatestCommit(): Promise<any>{ const { data: commits } = await this.octokit.repos.listCommits({ owner: this.userGithub.username, repo: this.repository.name, per_page: 1, sha: 'main' }); return commits[0]; }
/** * Retrieves information about the latest commit on the main branch. * * @returns {Promise<Object>} - An object containing details about the commit (message, author, etc.). */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L132-L140
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.createNewDeployment
async createNewDeployment(githubDeploymentId: number): Promise<IDeployment>{ const environmentVariables = await this.readEnvironmentVariables(); const currentDeployment = this.repository.deployments.pop(); if(currentDeployment){ const deployment = await Deployment.findById(currentDeployment._id); if(deployment && deployment.environment){ const { environment } = deployment; for(const [key, value] of Object.entries(environment.variables)){ if(!(key in environmentVariables)){ continue; } environmentVariables[key] = value; } } } const latestCommit = await this.getLatestCommit(); const newDeployment = new Deployment({ user: this.user._id, githubDeploymentId, repository: this.repository._id, environment: { variables: environmentVariables }, commit: { message: latestCommit.commit.message, author: { name: latestCommit.commit.author.name, email: latestCommit.commit.author.email }, status: 'pending' } }); await newDeployment.save(); return newDeployment; }
/** * Creates a new deployment record in the database and updates old deployments. * * @param {number} githubDeploymentId - The ID of the newly created GitHub deployment. * @returns {Promise<Deployment>} - The newly created Deployment object. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L148-L182
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.updateDeploymentStatus
async updateDeploymentStatus(deploymentId: string | number, state: DeploymentState): Promise<void>{ await this.octokit.repos.createDeploymentStatus({ owner: this.userGithub.username, repo: this.repository.name, deployment_id: deploymentId as number, state }); }
/** * Updates the deployment status on GitHub (e.g., "success", "failure", "pending"). * * @param {string} deploymentId - The ID of the deployment to update. * @param {string} DeploymentState - The new status (e.g., "pending", "success", "failure"). * @returns {Promise<void>} - Resolves when the update is sent to GitHub. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L191-L198
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.createGithubDeployment
async createGithubDeployment(): Promise<number>{ const { data: { id: deploymentId } }: any = await this.octokit.repos.createDeployment({ owner: this.userGithub.username, repo: this.repository.name, ref: this.repository.branch, auto_merge: false, required_contexts: [], environment: 'Production' }); if(!deploymentId) throw new RuntimeError('Deployment::Not::Created', 500); return deploymentId; }
/** * Creates a new deployment on GitHub for the associated repository. * * @returns {Promise<number>} - The ID of the newly created deployment. * @throws {RuntimeError} - If the deployment creation fails on GitHub's side. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L206-L218
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.getRepositoryDetails
async getRepositoryDetails(): Promise<any>{ const { data: repositoryDetails } = await this.octokit.repos.get({ owner: this.userGithub.username, repo: this.repository.name }); return repositoryDetails; }
/** * Retrieves detailed information about the associated GitHub repository. * * @returns {Promise<Object>} - An object containing repository details (e.g., name, description, owner, etc.). */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L225-L231
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.getRepositoryInfo
async getRepositoryInfo(): Promise<any | null>{ try{ const latestCommit = await this.getLatestCommit(); const details = await this.getRepositoryDetails(); const information = { branch: details.default_branch, website: details.homepage, latestCommitMessage: latestCommit.commit.message, latestCommit: latestCommit.commit.author.date }; return information; }catch(error){ // TODO: Do it better. // There is no hook that allows an event to be fired when a repository // is deleted (or so I think). For that reason, if a repository is // deleted, an error will be thrown when trying to request information // regarding it. By capturing and handling the error, we will // remove the repository from the platform. if((error as any)?.response?.data?.message === 'Not Found'){ // I am using "mongoose.model" because, when importing // "Repository" you get a circular import error. await mongoose.model('Repository').findByIdAndDelete(this.repository._id); return null; } throw error; } }
/** * Fetches essential repository information, including the latest commit details. * Handles potential errors if the repository has been deleted. * * @returns {Promise<Object>} - An object containing: * * branch: The default branch name * * website: The repository's homepage URL (if defined) * * latestCommitMessage: The message of the most recent commit * * latestCommit: The date and time of the most recent commit * @returns {null} - If the repository is deleted on GitHub. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L244-L270
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.createWebhook
async createWebhook(webhookUrl: string, webhookSecret: string): Promise<number | void>{ try{ const response = await this.octokit.repos.createWebhook({ owner: this.userGithub.username, repo: this.repository.name, name: 'web', config: { url: webhookUrl, content_type: 'json', secret: webhookSecret }, events: ['push'], active: true }); const { id } = response.data; return id; }catch(error){ if(!(error as any)?.response?.data?.errors?.[0]) return; const errorMessage = (error as any).response.data.errors[0].message; // TODO: In future versions, it would be useful to be able to clone // repositories that do not exactly belong to the authenticated user, obviously // hooks should not be registered for this, therefore this error should only be // thrown when a repository that belongs to the authenticated user exceeds that limit. if(errorMessage === 'The "push" event cannot have more than 20 hooks'){ throw new RuntimeError('Github::Repository::Excess::Hooks', 400); } // TODO: Maybe it would be useful here to notify the administrator by email? throw new RuntimeError('Github::Webhook::Creation::Error', 500); } }
/** * Creates a new webhook for the repository on GitHub, configured to trigger on 'push' events. * * @param {string} webhookUrl - The URL to which webhook events will be sent. * @param {string} webhookSecret - A secret used to verify the authenticity of webhook payloads. * @returns {Promise<number>} - The ID of the newly created webhook. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L279-L308
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.deleteWebhook
async deleteWebhook(): Promise<any | void>{ // Some repositories will not have a webhook, and this is because if // the repository is archived (Read-Only) it will not allow // updates, therefore no hooks. if(!this.repository.webhookId) return; try{ const response = await this.octokit.repos.deleteWebhook({ owner: this.userGithub.username, repo: this.repository.name, hook_id: Number(this.repository.webhookId) }); return response; }catch(error: any){ const errorMessage = error.message || ''; const errorStatus = error.status || 500; if(errorStatus === 404 || errorMessage.includes('Not Found')){ logger.warn(`@services/github.ts (deleteWebhook): Webhook not found, ignoring error. Repo: ${this.repository.name}`); return; } logger.error(`@services/github.ts (deleteWebhook): Error deleting webhook: ${errorMessage}`); throw error; } }
/** * Deletes an existing webhook from the repository on GitHub. Handles cases where repositories might not have webhooks. * * @returns {Promise<void>} - Resolves if deletion is successful, or if there's no webhook to delete. * @throws {Error} - If the webhook deletion process encounters an error on GitHub's side. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L316-L340
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.getRepositoryDeployments
async getRepositoryDeployments(): Promise<any[]>{ const { data: deployments } = await this.octokit.repos.listDeployments({ owner: this.userGithub.username, repo: this.repository.name }); return deployments; }
/** * Lists existing deployments for the repository on GitHub. * * @returns {Promise<Array<Object>>} - An array of deployment objects, each containing deployment details. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L347-L353
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.deleteRepositoryDeployment
async deleteRepositoryDeployment(deploymentId: string | number): Promise<void>{ await this.octokit.repos.deleteDeployment({ owner: this.userGithub.username, repo: this.repository.name, deployment_id: deploymentId as number }); }
/** * Deletes a specified deployment on GitHub. * * @param {number} deploymentId - The ID of the deployment to delete. * @returns {Promise<void>} - Resolves if the deployment deletion is successful. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts#L361-L367
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
Github.deployRepository
async deployRepository(): Promise<IDeployment>{ await this.cloneRepository(this.repository.branch); const githubDeploymentId = await this.createGithubDeployment(); const newDeployment = await this.createNewDeployment(githubDeploymentId); newDeployment.url = `https://github.com/${this.userGithub.username}/${this.repository.name}/deployments/${githubDeploymentId}`; newDeployment.status = 'pending'; await newDeployment.save(); await this.updateDeploymentStatus(githubDeploymentId, 'in_progress'); return newDeployment; }
/** * Orchestrates the deployment process for a repository. Includes * cloning, creating a GitHub deployment, and updating * the deployment status. * * @returns {Promise<Deployment>} - The newly created Deployment object, representing the deployment record in the Quantum Cloud system. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/github.ts
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
getLogDir
const getLogDir = (id: string): string => { return path.join('/var/lib/quantum', process.env.NODE_ENV as string, 'containers', id, 'logs'); };
/** * Generates the log directory path for a given container ID * @param id - The container ID * @returns The full path to the log directory */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/logManager.ts#L25-L27
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
getLogFile
const getLogFile = async (logName: string, logDir: string): Promise<string> => { await ensureDirectoryExists(logDir); const logFile = path.join(logDir, `${logName}.log`); }
/** * Generates the full path for a log file * @param logName - The name of the log file * @param id - The container ID * @returns The full path to the log file */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/logManager.ts#L35-L38
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
removeLogStream
const removeLogStream = (logId: string): void => { const stream = logs.get(logId); if(stream){ stream.end(); logs.delete(logId); } };
/** * Removes an existing log stream for a given container * @param id - The container ID */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/logManager.ts#L64-L70
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
sendEmail
const sendEmail = async({ to = process.env.WEBMASTER_MAIL, subject, html }: EmailOptions): Promise<void> => { if(!IS_SMTP_DEFINED) return; try{ await transporter.sendMail({ from: `Quantum Cloud Platform <${process.env.SMTP_AUTH_USER}>`, to, subject, html }); }catch(error){ logger.error('@services/sendEmail.ts (sendEmail): ' + error); } };
/** * Asynchronously sends an email using the preconfigured Nodemailer transporter. * @param {EmailOptions} emailOptions - Options for configuring the email. * @returns {Promise<void>} A promise that resolves when the email is sent. * @throws {Error} If there's an error during the sending process. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/services/sendEmail.ts#L61-L73
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.constructor
constructor({ requestQueryString, model, fields = [], populate = null }: Options) { this.model = model; this.requestQueryString = requestQueryString; this.fields = fields; this.populate = populate; this.buffer = { find: {}, sort: {}, select: '', skip: 0, limit: 100, totalResults: 0, skippedResults: 0, page: 1, totalPages: 1 }; }
/** * Creates an instance of APIFeatures. * @constructor * @param {Options} options - Options object. * @param {RequestQueryString} options.requestQueryString - Request query string object. * @param {Model<Document>} options.model - Mongoose model. * @param {string[]} [options.fields] - Array of fields to include in the query. * @param {string|PopulateOptions|(string|PopulateOptions)[]} [options.populate] - Populate options for related documents. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L27-L43
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.perform
async perform(): Promise<{ records: Document[]; totalResults: number; skippedResults: number; page: number; limit: number; totalPages: number; }>{ const { find, sort, select, skip, limit } = this.buffer; let query = this.model.find(find).skip(skip).limit(limit).select(select).sort(sort); if(this.populate){ if(Array.isArray(this.populate)){ this.populate.forEach((pop) => { query = query.populate(pop as string); }); }else{ query = query.populate(this.populate as PopulateOptions); } } const records = await query; return { records, totalResults: this.buffer.totalResults, skippedResults: this.buffer.skippedResults, page: this.buffer.page, limit: this.buffer.limit, totalPages: this.buffer.totalPages }; }
/** * Performs the query and returns the results. * @async * @returns {Promise<{records: Document[], totalResults: number, skippedResults: number, page: number, limit: number, totalPages: number}>} Query results and pagination data. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L50-L78
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.search
search(): APIFeatures{ const { q } = this.requestQueryString; if(q){ const escapedTerm = q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); this.buffer.find.$text = { $search: escapedTerm }; this.buffer.sort = { score: { $meta: 'textScore' }, ...(this.buffer.sort as object) }; this.buffer.select += ' score'; } return this; }
/** * Applies a text search query based on the 'q' parameter in the request query string. * @returns {APIFeatures} The current instance of APIFeatures. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L84-L93
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.filter
filter(auxFilter: any = {}): APIFeatures{ const excludedFields = ['page', 'sort', 'limit', 'fields', 'populate']; const query = Object.keys(this.requestQueryString) .filter(key => !excludedFields.includes(key)) .reduce((obj, key) => { obj[key] = this.requestQueryString[key]; return obj; }, {} as Record<string, any>); const filter = filterObject(query, ...this.fields); Object.assign(this.buffer.find, { ...filter, ...auxFilter }); return this; }
/** * Applies a filter based on the request query string parameters, excluding specific fields. * @returns {APIFeatures} The current instance of APIFeatures. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L99-L111
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.sort
sort(): APIFeatures{ const { sort: sortQuery } = this.requestQueryString; if(sortQuery){ const sortBy = sortQuery.split(',').join(' '); if(typeof this.buffer.sort === 'object' && !Array.isArray(this.buffer.sort)){ const sortFields = sortBy.split(' '); sortFields.forEach((field) => { const order = field.startsWith('-') ? -1 : 1; const fieldName = field.startsWith('-') ? field.substring(1) : field; (this.buffer.sort as Record<string, any>)[fieldName] = order; }); }else{ this.buffer.sort = sortBy; } }else{ this.buffer.sort = '-createdAt'; } return this; }
/** * Applies a sort order based on the 'sort' parameter in the request query string. * @returns {APIFeatures} The current instance of APIFeatures. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L117-L135
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.limitFields
limitFields(): APIFeatures{ const { fields } = this.requestQueryString; if(fields){ this.buffer.select = fields.split(',').join(' '); } return this; }
/** * Applies a field selection based on the 'fields' parameter in the request query string. * @returns {APIFeatures} The current instance of APIFeatures. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L141-L147
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
APIFeatures.paginate
async paginate(): Promise<APIFeatures>{ const limit = this.requestQueryString.limit ? parseInt(this.requestQueryString.limit, 10) : this.buffer.limit; if(limit !== -1){ const page = this.requestQueryString.page ? Math.max(1, parseInt(this.requestQueryString.page, 10)) : 1; const skip = (page - 1) * limit; this.buffer.skip = skip; this.buffer.limit = limit; this.buffer.page = page; this.buffer.skippedResults = skip; const totalResults = await this.model.countDocuments(this.buffer.find).exec(); this.buffer.totalResults = totalResults; this.buffer.totalPages = Math.ceil(totalResults / limit) || 1; if(this.requestQueryString.page && skip >= totalResults){ throw new RuntimeError('Core::PageOutOfRange', 404); } } return this; }
/** * Applies pagination based on the 'page' and 'limit' parameters in the request query string. * @async * @returns {Promise<APIFeatures>} The current instance of APIFeatures. * @throws {RuntimeError} If the requested page is out of range. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/apiFeatures.ts#L155-L172
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
mongoConnector
const mongoConnector = async (): Promise<void> => { const { NODE_ENV, PRODUCTION_DATABASE, DEVELOPMENT_DATABASE, MONGO_AUTH_SOURCE, MONGO_URI } = process.env; const databaseName = NODE_ENV === 'production'? PRODUCTION_DATABASE : DEVELOPMENT_DATABASE; const uri = `${MONGO_URI}/${databaseName}`; logger.info(`@utilities/mongoConnector.ts (mongoConnector): Connecting to MongoDB (${databaseName})...`); mongoose.set('strictQuery', false); mongoose.set('strictPopulate', false); const options = { maxPoolSize: 10, autoIndex: NODE_ENV !== 'production', connectTimeoutMS: 10000, socketTimeoutMS: 45000, authSource: MONGO_AUTH_SOURCE, appName: 'quantum-cloud', serverSelectionTimeoutMS: 5000, maxIdleTimeMS: 30000, retryWrites: true }; try{ await mongoose.connect(uri, options); logger.info(`@utilities/mongoConnector.ts (mongoConnector): Connected to MongoDB (${databaseName}).`); }catch(error){ logger.fatal('@utilities/mongoConnector.ts (mongoConnector): Error connecting to MongoDB: ' + error); } };
/** * Establishes a connection to the appropriate MongoDB database based on the environment. * Logs errors to the console for troubleshooting. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/mongoConnector.ts#L8-L43
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
RuntimeError.constructor
constructor(message: string, statusCode: number){ super(message); this.statusCode = statusCode; Error.captureStackTrace(this,this.constructor); }
/** * @constructor * @param {string} message - Descriptive error message explaining the runtime problem. * @param {number} statusCode - An HTTP-like status code for categorizing the error. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/server/utilities/runtimeError.ts#L28-L32
5855dbd179a24d2d9578e1b6b286f3883d320dbc
Quantum
github_2023
rodyherrera
typescript
MultiProvider
const MultiProvider: React.FC<MultiProviderProps> = ({ providers, children }) => { if(!providers || !providers.length){ throw new Error('MultiProvider requires a non-empty "providers" array'); } if(!children){ throw new Error('MultiProvider requires "children" to wrap'); } return providers.reduceRight<ReactNode>( (acc, provider) => React.cloneElement(provider, provider.props, acc), children ); };
/** * A component that wraps its children with multiple context providers. * * @param {MultiProviderProps} props The component props. * @param {ReactElement[]} props.providers An array of React elements representing the providers. * @param {ReactNode} props.children The children that will be wrapped by the providers. * @returns {ReactNode} The children wrapped with the provided context providers. */
https://github.com/rodyherrera/Quantum/blob/5855dbd179a24d2d9578e1b6b286f3883d320dbc/setup-utility/client/src/components/atoms/MultiProvider.tsx#L16-L29
5855dbd179a24d2d9578e1b6b286f3883d320dbc
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyService.createApiKey
async createApiKey(user: User, dto: CreateApiKey) { await this.isApiKeyUnique(user, dto.name) const plainTextApiKey = generateApiKey() // Generate the preview key in format ks_****<last 4 chars> const previewKey = `ks_****${plainTextApiKey.slice(-4)}` this.logger.log( `User ${user.id} created API key ${previewKey} with name ${dto.name}` ) const hashedApiKey = toSHA256(plainTextApiKey) const apiKey = await this.prisma.apiKey.create({ data: { name: dto.name, slug: await generateEntitySlug(dto.name, 'API_KEY', this.prisma), value: hashedApiKey, preview: previewKey, authorities: dto.authorities ? { set: dto.authorities } : [], expiresAt: addHoursToDate(dto.expiresAfter), user: { connect: { id: user.id } } } }) this.logger.log(`User ${user.id} created API key ${apiKey.id}`) return { ...apiKey, value: plainTextApiKey } }
/** * Creates a new API key for the given user. * * @throws `ConflictException` if the API key already exists. * @param user The user to create the API key for. * @param dto The data to create the API key with. * @returns The created API key. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/api-key/service/api-key.service.ts#L41-L79
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyService.updateApiKey
async updateApiKey( user: User, apiKeySlug: ApiKey['slug'], dto: UpdateApiKey ) { await this.isApiKeyUnique(user, dto.name) const apiKey = await this.prisma.apiKey.findUnique({ where: { slug: apiKeySlug } }) const apiKeyId = apiKey.id if (!apiKey) { throw new NotFoundException(`API key ${apiKeySlug} not found`) } const updatedApiKey = await this.prisma.apiKey.update({ where: { id: apiKeyId, userId: user.id }, data: { name: dto.name, slug: dto.name ? await generateEntitySlug(dto.name, 'API_KEY', this.prisma) : apiKey.slug, authorities: { set: dto.authorities ? dto.authorities : apiKey.authorities }, expiresAt: dto.expiresAfter ? addHoursToDate(dto.expiresAfter) : undefined }, select: this.apiKeySelect }) this.logger.log(`User ${user.id} updated API key ${apiKeyId}`) return updatedApiKey }
/** * Updates an existing API key of the given user. * * @throws `ConflictException` if the API key name already exists. * @throws `NotFoundException` if the API key with the given slug does not exist. * @param user The user to update the API key for. * @param apiKeySlug The slug of the API key to update. * @param dto The data to update the API key with. * @returns The updated API key. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/api-key/service/api-key.service.ts#L91-L132
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyService.deleteApiKey
async deleteApiKey(user: User, apiKeySlug: ApiKey['slug']) { try { await this.prisma.apiKey.delete({ where: { slug: apiKeySlug, userId: user.id } }) } catch (error) { throw new NotFoundException(`API key ${apiKeySlug} not found`) } this.logger.log(`User ${user.id} deleted API key ${apiKeySlug}`) }
/** * Deletes an API key of the given user. * * @throws `NotFoundException` if the API key with the given slug does not exist. * @param user The user to delete the API key for. * @param apiKeySlug The slug of the API key to delete. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/api-key/service/api-key.service.ts#L141-L154
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyService.getApiKeyBySlug
async getApiKeyBySlug(user: User, apiKeySlug: ApiKey['slug']) { const apiKey = await this.prisma.apiKey.findUnique({ where: { slug: apiKeySlug, userId: user.id }, select: this.apiKeySelect }) if (!apiKey) { throw new NotFoundException(`API key ${apiKeySlug} not found`) } return apiKey }
/** * Retrieves an API key of the given user by slug. * * @throws `NotFoundException` if the API key with the given slug does not exist. * @param user The user to retrieve the API key for. * @param apiKeySlug The slug of the API key to retrieve. * @returns The API key with the given slug. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/api-key/service/api-key.service.ts#L164-L178
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyService.getAllApiKeysOfUser
async getAllApiKeysOfUser( user: User, page: number, limit: number, sort: string, order: string, search: string ) { const items = await this.prisma.apiKey.findMany({ where: { userId: user.id, name: { contains: search } }, skip: page * limit, take: limitMaxItemsPerPage(limit), orderBy: { [sort]: order }, select: this.apiKeySelect }) const totalCount = await this.prisma.apiKey.count({ where: { userId: user.id, name: { contains: search } } }) const metadata = paginate(totalCount, `/api-key`, { page, limit: limitMaxItemsPerPage(limit), sort, order, search }) return { items, metadata } }
/** * Retrieves all API keys of the given user. * * @param user The user to retrieve the API keys for. * @param page The page number to retrieve. * @param limit The maximum number of items to retrieve per page. * @param sort The column to sort by. * @param order The order to sort by. * @param search The search string to filter the API keys by. * @returns The API keys of the given user, filtered by the search string. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/api-key/service/api-key.service.ts#L191-L230
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyService.isApiKeyUnique
private async isApiKeyUnique(user: User, apiKeyName: string) { let apiKey: ApiKey | null = null try { apiKey = await this.prisma.apiKey.findUnique({ where: { userId_name: { userId: user.id, name: apiKeyName } } }) } catch (_error) {} if (apiKey) { throw new ConflictException( `API key with name ${apiKeyName} already exists` ) } }
/** * Checks if an API key with the given name already exists for the given user. * * @throws `ConflictException` if the API key already exists. * @param user The user to check for. * @param apiKeyName The name of the API key to check. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/api-key/service/api-key.service.ts#L239-L258
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthController.handleOAuthProcess
private async handleOAuthProcess( email: string, name: string, profilePictureUrl: string, oauthProvider: AuthProvider, response: Response ) { try { const data = await this.authService.handleOAuthLogin( email, name, profilePictureUrl, oauthProvider ) const user = setCookie(response, data) sendOAuthSuccessRedirect(response, user) } catch (error) { this.logger.warn( 'User attempted to log in with a different OAuth provider' ) sendOAuthFailureRedirect( response, 'User attempted to log in with a different OAuth provider' ) } }
/* istanbul ignore next */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/controller/auth.controller.ts#L185-L210
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AdminGuard.canActivate
canActivate( context: ExecutionContext ): boolean | Promise<boolean> | Observable<boolean> { const request = context.switchToHttp().getRequest() const user: User = request.user return user.isAdmin }
/** * This guard will check if the request's user is an admin. * If the user is an admin, then the canActivate function will return true. * If the user is not an admin, then the canActivate function will return false. * * @param context The ExecutionContext for the request. * @returns A boolean indicating whether or not the request's user is an admin. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/guard/admin/admin.guard.ts#L15-L22
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
ApiKeyGuard.canActivate
canActivate( context: ExecutionContext ): boolean | Promise<boolean> | Observable<boolean> { const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass() ]) if (isPublic) { return true } const requiredAuthorities = this.reflector.get<Authority[]>( REQUIRED_API_KEY_AUTHORITIES, context.getHandler() ) if (!requiredAuthorities || requiredAuthorities.length === 0) { return true } const user: AuthenticatedUserContext = context .switchToHttp() .getRequest().user if (!user || !user.isAuthViaApiKey) { return true } const forbidApiKey = this.reflector.get<boolean>( FORBID_API_KEY, context.getHandler() ) if (forbidApiKey && user.isAuthViaApiKey) { throw new UnauthorizedException('API key authentication is forbidden.') } if (!user.apiKeyAuthorities) { throw new UnauthorizedException('The API key has no authorities.') } if (user.apiKeyAuthorities.has(Authority.ADMIN)) { return true } for (const requiredAuthority of requiredAuthorities) { if (!user.apiKeyAuthorities.has(requiredAuthority)) { throw new UnauthorizedException( `The API key is missing the required authority: ${requiredAuthority}` ) } } return true }
/** * This method will check if the user is authenticated via an API key, * and if the API key has the required authorities for the route. * * If the user is not authenticated via an API key, or if the API key does not have the required authorities, * then the canActivate method will return true. * * If the user is authenticated via an API key, and the API key has the required authorities, * then the canActivate method will return true. * * If the user is authenticated via an API key, but the API key does not have the required authorities, * then the canActivate method will throw an UnauthorizedException. * * If the user is authenticated via an API key, but the API key is forbidden for the route, * then the canActivate method will throw an UnauthorizedException. * * @param context The ExecutionContext for the request. * @returns A boolean indicating whether or not the user is authenticated via an API key and has the required authorities for the route. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/guard/api-key/api-key.guard.ts#L38-L93
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthGuard.canActivate
async canActivate(context: ExecutionContext): Promise<boolean> { // Get the kind of route. Routes marked with the @Public() decorator are public. const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass() ]) // We don't want to check for authentication if the route is public. if (isPublic) { return true } let user: AuthenticatedUserContext | null = null const request = context.switchToHttp().getRequest() const authType = this.getAuthType(request) const parsedEnv = EnvSchema.safeParse(process.env) let nodeEnv if (!parsedEnv.success) { nodeEnv = 'dev' // Default to a valid value or handle appropriately } else { nodeEnv = parsedEnv.data.NODE_ENV } if (nodeEnv !== 'e2e' && authType === 'NONE') { throw new ForbiddenException('No authentication provided') } // In case the environment is e2e, we want to authenticate the user using the email // else we want to authenticate the user using the JWT token. if (authType !== 'API_KEY' && nodeEnv === 'e2e') { const email = request.headers[X_E2E_USER_EMAIL] if (!email) { throw new ForbiddenException() } user = await getUserByEmailOrId(email, this.prisma) } else { const request = context.switchToHttp().getRequest() if (authType === 'API_KEY') { const apiKeyValue = this.extractApiKeyFromHeader(request) if (!apiKeyValue) { throw new ForbiddenException('No API key provided') } const apiKey = await this.prisma.apiKey.findUnique({ where: { value: toSHA256(apiKeyValue) }, include: { user: true } }) if (!apiKey) { throw new ForbiddenException('Invalid API key') } const defaultWorkspace = await this.prisma.workspace.findFirst({ where: { ownerId: apiKey.userId, isDefault: true } }) user = { ...apiKey.user, defaultWorkspace } user.isAuthViaApiKey = true user.apiKeyAuthorities = new Set(apiKey.authorities) } else if (authType === 'JWT') { const token = this.extractTokenFromCookies(request) if (!token) { throw new ForbiddenException() } try { const payload = await this.jwtService.verifyAsync(token, { secret: process.env.JWT_SECRET }) const cachedUser = await this.cache.getUser(payload['id']) if (cachedUser) user = cachedUser else { user = await getUserByEmailOrId(payload['id'], this.prisma) } } catch { throw new ForbiddenException() } } else { throw new ForbiddenException('No authentication provided') } } // If the user is not found, we throw a ForbiddenException. if (!user) { throw new ForbiddenException() } // If the user is not active, we throw an UnauthorizedException. if (!user.isActive) { throw new UnauthorizedException('User is not active') } const onboardingBypassed = this.reflector.getAllAndOverride<boolean>(ONBOARDING_BYPASSED, [ context.getHandler(), context.getClass() ]) ?? false // If the onboarding is not finished, we throw an UnauthorizedException. if (!onboardingBypassed && !user.isOnboardingFinished) { throw new UnauthorizedException('Onboarding not finished') } // We attach the user to the request object. request['user'] = user return true }
/** * This method is called by NestJS every time an HTTP request is made to an endpoint * that is protected by this guard. It checks if the request is authenticated and if * the user is active. If the user is not active, it throws an UnauthorizedException. * If the onboarding is not finished, it throws an UnauthorizedException. * @param context The ExecutionContext object that contains information about the * request. * @returns A boolean indicating if the request is authenticated and the user is active. */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/guard/auth/auth.guard.ts#L42-L162
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthService.sendOtp
async sendOtp(email: string): Promise<void> { if (!email || !email.includes('@')) { this.logger.error(`Invalid email address: ${email}`) throw new BadRequestException('Please enter a valid email address') } const user = await this.createUserIfNotExists(email, AuthProvider.EMAIL_OTP) const otp = await generateOtp(email, user.id, this.prisma) await this.mailService.sendOtp(email, otp.code) this.logger.log(`Login code sent to ${email}`) }
/** * Sends a login code to the given email address * @throws {BadRequestException} If the email address is invalid * @param email The email address to send the login code to */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/service/auth.service.ts#L40-L51
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthService.resendOtp
async resendOtp(email: string): Promise<void> { const user = await getUserByEmailOrId(email, this.prisma) const otp = await generateOtp(email, user.id, this.prisma) await this.mailService.sendOtp(email, otp.code) }
/** * resend a login code to the given email address after resend otp button is pressed * @throws {BadRequestException} If the email address is invalid * @param email The email address to resend the login code to */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/service/auth.service.ts#L58-L62
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthService.validateOtp
async validateOtp( email: string, otp: string ): Promise<UserAuthenticatedResponse> { const user = await getUserByEmailOrId(email, this.prisma) if (!user) { this.logger.error(`User not found: ${email}`) throw new NotFoundException('User not found') } const isOtpValid = (await this.prisma.otp.findUnique({ where: { userCode: { code: otp, userId: user.id }, expiresAt: { gt: new Date() } } })) !== null if (!isOtpValid) { this.logger.error(`Invalid login code for ${email}: ${otp}`) throw new UnauthorizedException('Invalid login code') } await this.prisma.otp.delete({ where: { userCode: { code: otp, userId: user.id } } }) this.cache.setUser(user) // Save user to cache this.logger.log(`User logged in: ${email}`) const token = await this.generateToken(user.id) return { ...user, token } }
/** * Validates a login code sent to the given email address * @throws {NotFoundException} If the user is not found * @throws {UnauthorizedException} If the login code is invalid * @param email The email address the login code was sent to * @param otp The login code to validate * @returns An object containing the user and a JWT token */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/service/auth.service.ts#L73-L118
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthService.handleOAuthLogin
async handleOAuthLogin( email: string, name: string, profilePictureUrl: string, oauthProvider: AuthProvider ): Promise<UserAuthenticatedResponse> { // We need to create the user if it doesn't exist yet const user = await this.createUserIfNotExists( email, oauthProvider, name, profilePictureUrl ) const token = await this.generateToken(user.id) return { ...user, token } }
/** * Handles a login with an OAuth provider * @param email The email of the user * @param name The name of the user * @param profilePictureUrl The profile picture URL of the user * @param oauthProvider The OAuth provider used * @returns An object containing the user and a JWT token */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/service/auth.service.ts#L129-L149
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthService.createUserIfNotExists
private async createUserIfNotExists( email: string, authProvider: AuthProvider, name?: string, profilePictureUrl?: string ) { let user: UserWithWorkspace | null try { user = await getUserByEmailOrId(email, this.prisma) } catch (ignored) {} // We need to create the user if it doesn't exist yet if (!user) { user = await createUser( { email, name, profilePictureUrl, authProvider }, this.prisma ) } // If the user has used OAuth to log in, we need to check if the OAuth provider // used in the current login is different from the one stored in the database if (user.authProvider !== authProvider) { throw new UnauthorizedException( 'The user has signed up with a different authentication provider.' ) } return user }
/** * Creates a user if it doesn't exist yet. If the user has signed up with a * different authentication provider, it throws an UnauthorizedException. * @param email The email address of the user * @param authProvider The AuthProvider used * @param name The name of the user * @param profilePictureUrl The profile picture URL of the user * @returns The user * @throws {UnauthorizedException} If the user has signed up with a different * authentication provider */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/service/auth.service.ts#L184-L218
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthService.logout
async logout(res: Response): Promise<void> { res.clearCookie('token', { domain: process.env.DOMAIN ?? 'localhost' }) this.logger.log('User logged out and token cookie cleared.') }
/** * Clears the token cookie on logout * @param res The response object */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/auth/service/auth.service.ts#L228-L233
557b3b63dd7c589d484d4eab0b46e90a7c696af3
keyshade
github_2023
keyshade-xyz
typescript
AuthorityCheckerService.checkAuthorityOverWorkspace
public async checkAuthorityOverWorkspace( input: AuthorityInput ): Promise<Workspace> { const { userId, entity, authorities, prisma } = input let workspace: Workspace try { if (entity.slug) { workspace = await prisma.workspace.findUnique({ where: { slug: entity.slug } }) } else { workspace = await prisma.workspace.findFirst({ where: { name: entity.name, members: { some: { userId: userId } } } }) } } catch (error) { this.customLoggerService.error(error) throw new InternalServerErrorException(error) } if (!workspace) { throw new NotFoundException(`Workspace ${entity.slug} not found`) } const permittedAuthorities = await getCollectiveWorkspaceAuthorities( workspace.id, userId, prisma ) this.checkHasPermissionOverEntity(permittedAuthorities, authorities, userId) return workspace }
/** * Checks if the user has the required authorities to access the given workspace. * * @param input The input object containing the userId, entity, authorities, and prisma client * @returns The workspace if the user has the required authorities * @throws InternalServerErrorException if there's an error when communicating with the database * @throws NotFoundException if the workspace is not found * @throws UnauthorizedException if the user does not have the required authorities */
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L45-L85
557b3b63dd7c589d484d4eab0b46e90a7c696af3