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 /...
/** * 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 === ...
/** * 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)?...
/** * 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 的设计 ...
/** * 请求方法: 主要是对 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 ...
/** * 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 homedi...
// 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_sour...
/* * 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', ty...
/** * 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.defaultS...
// 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 ...
// 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", ...
// 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() ...
/** * 获取所有附件条目 */
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)...
/** * 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 ...
/** * 重命名文件,但不重命名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 ( getCollection...
/** * 获取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, ...
/** * 从文件名中删除非法字符 * 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 Zote...
/** * 向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("sou...
/** * 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.copyObjectSubjectRel...
/** * 迁移数据 */
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) { ...
/** * 为文件添加后缀,如果存在 * @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) { cons...
/** * 对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; }; ...
// 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 +...
// 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); ...
// 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); ...
// 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 * ...
/** * 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...
/** * 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]; } ...
/** * 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' } ...
/** * 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 } }), ]); reposito...
/** * 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}" r...
/** * 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 { m...
/** * 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: 'er...
/** * 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 fun...
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('DockerN...
// 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...
/** * 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...
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({ ...
/** * 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', '--...
/** * 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(currentDep...
/** * 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 th...
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, requir...
/** * 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, ...
/** * 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 ...
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: { ...
/** * 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<nu...
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 = ...
/** * 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...
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.use...
/** * 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 ...
/** * 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: ''...
/** * 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] - Ar...
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).lim...
/** * 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) };...
/** * 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.requestQueryS...
/** * 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(' '); ...
/** * 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 ...
/** * 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 = ...
/** * 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 p...
/** * 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 provid...
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} create...
/** * 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 ne...
/** * 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 upd...
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(`...
/** * 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...
/** * 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 * lim...
/** * 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 se...
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) {} ...
/** * 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 ) ...
/* 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 indica...
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 = thi...
/** * 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. * ...
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...
/** * 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 U...
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 o...
/** * 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 = (awai...
/** * 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 co...
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,...
/** * 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 do...
/** * 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...
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.sl...
/** * 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...
https://github.com/keyshade-xyz/keyshade/blob/557b3b63dd7c589d484d4eab0b46e90a7c696af3/apps/api/src/common/authority-checker.service.ts#L45-L85
557b3b63dd7c589d484d4eab0b46e90a7c696af3