repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
cli
github_2023
reliverse
typescript
computeRepoInfo
function computeRepoInfo( input: string, defaultProvider: GitProvider, auth?: string, subdirectory?: string, ): RepoInfo { const { provider: parsedProvider, repo, ref, subdir } = parseGitURI(input); const actualProvider = (parsedProvider ?? defaultProvider) as GitProvider; const name = repo.replace("/", "...
/** * Creates a final RepoInfo object (including gitUrl and optional headers) * from the raw repo string and user options (e.g., auth, subdirectory). */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/downloading/downloadRepo.ts#L210-L233
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
getUniqueProjectPath
async function getUniqueProjectPath( basePath: string, projectName: string, isDev: boolean, ): Promise<string> { let iteration = 1; let currentPath = basePath; let currentName = projectName; while (await fs.pathExists(currentPath)) { currentName = `${projectName}-${iteration}`; currentPath = isDev...
/** * Generates a new project name with an iteration number if the directory already exists. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/downloading/downloadRepo.ts#L238-L254
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
fetchJson
async function fetchJson<T>(url: string): Promise<T> { try { return await ofetch<T>(url, { headers: { Accept: "application/json" }, }); } catch (error) { throw new Error(`Failed to fetch JSON from "${url}" (error: ${error})`); } }
// ────────────────────────────────────────────────
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L53-L61
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
getPackageMeta
async function getPackageMeta( scope: string, packageName: string, ): Promise<PackageMeta> { const url = `${BASE_URL}/@${scope}/${packageName}/meta.json`; return fetchJson<PackageMeta>(url); }
// ────────────────────────────────────────────────
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L70-L76
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
pickVersionFromMeta
function pickVersionFromMeta(meta: PackageMeta, userVersion?: string): string { if (userVersion) { const info = meta.versions[userVersion]; if (!info) { throw new Error( `Version "${userVersion}" not found in package metadata.`, ); } if (info.yanked) { throw new Error( ...
/** * Picks a suitable version from the PackageMeta. * If userVersion is provided, verifies that it exists and is not yanked. * Otherwise, returns the highest semver-valid, non‑yanked version. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L83-L114
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
getVersionMeta
async function getVersionMeta( scope: string, packageName: string, version: string, ): Promise<VersionMeta> { const url = `${BASE_URL}/@${scope}/${packageName}/${version}_meta.json`; return fetchJson<VersionMeta>(url); }
/** * Fetches version-specific metadata (_meta.json) for a given scope/packageName/version. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L119-L126
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
downloadFile
async function downloadFile( scope: string, packageName: string, version: string, filePath: string, outputDir: string, useSinglePath: boolean, ): Promise<void> { const trimmedFilePath = filePath.replace(/^\//, ""); const url = `${BASE_URL}/@${scope}/${packageName}/${version}/${trimmedFilePath}`; cons...
/** * Downloads a single file from the JSR registry and writes it to disk. * The target path structure depends on the value of useSinglePath. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L132-L158
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
isPackageDownloaded
async function isPackageDownloaded( filePaths: string[], outputDir: string, useSinglePath: boolean, scope: string, packageName: string, version: string, ): Promise<boolean> { try { for (const filePath of filePaths) { const trimmedFilePath = filePath.replace(/^\//, ""); const targetFilePath...
/** * Checks if the package is already downloaded in the target directory. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L163-L186
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
renameTxtToTsx
async function renameTxtToTsx(dir: string): Promise<void> { try { const files = await globby("**/*-tsx.txt", { cwd: dir, absolute: true, }); for (const filePath of files) { const newPath = filePath.replace(/-tsx\.txt$/, ".tsx"); await fs.rename(filePath, newPath); if (verbose...
/** * Renames all -tsx.txt files back to .tsx in the specified directory. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/native-cli/nc-impl.ts#L191-L211
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
looksLikeBinary
function looksLikeBinary(buffer: Buffer, size: number): boolean { for (let i = 0; i < size; i++) { // If there's a null character, let's treat it as binary if (buffer[i] === 0) return true; } return false; }
/** * Check if a buffer looks like binary content * (very naive approach: if we see a null byte or lots of weird chars early on). */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-impl.ts#L52-L58
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
isBinaryFile
async function isBinaryFile( filePath: string, chunkSize = 1000, ): Promise<boolean> { const fd = await fs.promises.open(filePath, "r"); try { const buffer = Buffer.alloc(chunkSize); const { bytesRead } = await fd.read(buffer, 0, chunkSize, 0); return looksLikeBinary(buffer, bytesRead); } finally ...
/** * Asynchronously checks if a file is "binary" by reading the first chunk. */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-impl.ts#L63-L75
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
gatherAllFiles
async function gatherAllFiles( dir: string, shouldSkipDir: (dirName: string) => boolean, ): Promise<string[]> { const filesInDir = await fs.promises.readdir(dir); const result: string[] = []; for (const file of filesInDir) { const fullPath = path.join(dir, file); const stat = await fs.promises.lstat(...
/** * Recursively gathers all files from a directory and its subdirectories. * Skips directories based on the provided filter function. * * @param dir - The root directory to start gathering files from * @param shouldSkipDir - Function that determines if a directory should be skipped * @returns Promise resolving ...
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-impl.ts#L85-L107
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
runWithConcurrency
async function runWithConcurrency<T>( items: T[], concurrency: number, taskFn: (item: T) => Promise<void>, stopOnError: boolean, ): Promise<void> { return new Promise<void>((resolve, reject) => { let index = 0; let active = 0; let isRejected = false; let completedCount = 0; const next = (...
/** * Executes tasks with limited concurrency. Provides error handling and progress tracking. * * @param items - Array of items to process * @param concurrency - Maximum number of concurrent tasks * @param taskFn - Async function to execute for each item * @param stopOnError - If true, stops processing on first e...
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-impl.ts#L118-L164
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
replaceInFile
async function replaceInFile(filePath: string) { try { // Skip binary files if configured if (skipBinaryFiles && (await isBinaryFile(filePath))) { verbose && relinka("info-verbose", `Skipping binary file: ${filePath}`); return; } const fileContent = await fs.promises.readFil...
/** * Processes a single file, replacing specified strings while tracking changes. * * @param filePath - Path to the file being processed * @throws Error if file processing fails */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-impl.ts#L269-L324
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
getPackageNames
async function getPackageNames(projectPath: string): Promise<string[]> { try { const pkgPath = path.join(projectPath, "package.json"); if (!(await fs.pathExists(pkgPath))) return []; const pkg = await fs.readJson(pkgPath); const allDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependen...
/** * Gets all package names from package.json dependencies */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-mod.ts#L17-L34
725066145859e6b29a7c419e0b22ac51e1468943
cli
github_2023
reliverse
typescript
getImportPaths
async function getImportPaths(projectPath: string): Promise<string[]> { const importPaths = new Set<string>(); try { // Find all JS/TS files const files = await globby("**/*.{js,ts,jsx,tsx}", { cwd: projectPath, ignore: ["node_modules/**", "dist/**", ".next/**", "build/**"], }); // Ext...
/** * Gets all import paths from the project files */
https://github.com/reliverse/cli/blob/725066145859e6b29a7c419e0b22ac51e1468943/src/utils/replacements/reps-mod.ts#L39-L72
725066145859e6b29a7c419e0b22ac51e1468943
sign-in-with-solana
github_2023
phantom
typescript
NoProvider
const NoProvider = () => { return ( <StyledMain> <h2>Could not find a provider</h2> </StyledMain> ); };
// =============================================================================
https://github.com/phantom/sign-in-with-solana/blob/e4060d2916469116d5080a712feaf81ea1db4f65/example-dapp/src/components/NoProvider/index.tsx#L21-L27
e4060d2916469116d5080a712feaf81ea1db4f65
sign-in-with-solana
github_2023
phantom
typescript
hexToRGB
const hexToRGB = (hex: string, alpha: number) => { const r = parseInt(hex.slice(1, 3), 16); const g = parseInt(hex.slice(3, 5), 16); const b = parseInt(hex.slice(5, 7), 16); return `rgba(${r},${g},${b},${alpha})`; };
/** * Returns a color from a hex string and alpha numeric * @param {String} hex a hex string * @param {Number} alpha an alpha numeric * @returns {String} a formatted rgba */
https://github.com/phantom/sign-in-with-solana/blob/e4060d2916469116d5080a712feaf81ea1db4f65/example-dapp/src/utils/hexToRGB.ts#L7-L13
e4060d2916469116d5080a712feaf81ea1db4f65
magika
github_2023
google
typescript
Magika.load
async load(options?: MagikaOptions): Promise<void> { await Promise.all([ (this.config.loadUrl(options?.configURL || Magika.CONFIG_URL)), (this.model.loadUrl(options?.modelURL || Magika.MODEL_URL)) ]); }
/** Loads the Magika model and config from URLs. * * @param {MagikaOptions} options The urls where the model and its config are stored. * * Parameters are optional. If not provided, the model will be loaded from GitHub. */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika.ts#L52-L57
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
Magika.identifyBytesFull
async identifyBytesFull(fileBytes: Uint16Array | Uint8Array): Promise<ModelResultLabels> { const result = await this._identifyFromBytes(fileBytes); return this._getLabelsResult(result); }
/** Identifies the content type of a byte array, returning all probabilities instead of just the top one. * * @param {*} fileBytes a Buffer object (a fixed-length sequence of bytes) * @returns A dictionary containing the top label, its score, and a list of content types and their scores. */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika.ts#L64-L67
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
Magika.identifyBytes
async identifyBytes(fileBytes: Uint16Array | Uint8Array): Promise<ModelResult> { const result = await this._identifyFromBytes(fileBytes); return {label: result.label, score: result.score}; }
/** Identifies the content type of a byte array. * * @param {*} fileBytes a Buffer object (a fixed-length sequence of bytes) * @returns A dictionary containing the top label and its score */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika.ts#L74-L77
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
MagikaNode.load
async load(options?: MagikaOptions): Promise<void> { const p: Promise<void>[] = []; if (options?.configPath != null) { p.push(this.config.loadFile(options?.configPath)); } else { p.push(this.config.loadUrl(options?.configURL || Magika.CONFIG_URL)); } if (o...
/** Loads the Magika model and config from URLs. * * @param {MagikaOptions} options The urls or file paths where the model and its config are stored. * * Parameters are optional. If not provided, the model will be loaded from GitHub. * */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika_node.ts#L45-L58
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
MagikaNode.identifyStream
async identifyStream(stream: ReadStream, length: number): Promise<ModelResult> { const result = await this._identifyFromStream(stream, length); return { label: result.label, score: result.score }; }
/** Identifies the content type from a read stream * * @param stream A read stream * @param length Total length of stream data (this is needed to find the middle without keep the file in memory) * @returns A dictionary containing the top label and its score, */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika_node.ts#L66-L69
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
MagikaNode.identifyStreamFull
async identifyStreamFull(stream: ReadStream, length: number): Promise<ModelResultLabels> { const result = await this._identifyFromStream(stream, length); return this._getLabelsResult(result); }
/** Identifies the content type from a read stream * * @param stream A read stream * @param length Total length of stream data (this is needed to find the middle without keep the file in memory) * @returns A dictionary containing the top label, its score, and a list of content types and their score...
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika_node.ts#L77-L80
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
MagikaNode.identifyBytesFull
async identifyBytesFull(fileBytes: Uint16Array | Uint8Array | Buffer): Promise<ModelResultLabels> { const result = await this._identifyFromBytes(new Uint16Array(fileBytes)); return this._getLabelsResult(result); }
/** Identifies the content type of a byte array, returning all probabilities instead of just the top one. * * @param {*} fileBytes a Buffer object (a fixed-length sequence of bytes) * @returns A dictionary containing the top label, its score, and a list of content types and their scores. */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika_node.ts#L87-L91
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
MagikaNode.identifyBytes
async identifyBytes(fileBytes: Uint16Array | Uint8Array | Buffer): Promise<ModelResult> { const result = await this._identifyFromBytes(new Uint16Array(fileBytes)); return { label: result.label, score: result.score }; }
/** Identifies the content type of a byte array. * * @param {*} fileBytes a Buffer object (a fixed-length sequence of bytes) * @returns A dictionary containing the top label and its score */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/magika_node.ts#L98-L101
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
magika
github_2023
google
typescript
getTestFilesWithLabels
const getTestFilesWithLabels = (directory: string): Array<[string, Dirent]> => readdirSync( directory, { recursive: true, withFileTypes: true }) .filter(dirent => dirent.isFile()) .map<[string, Dirent]>((dirent) => [dirent.parentPath.split('/').pop() || 'UNKNOWN', dirent])
/** * Returns a list of test files and their correct labels. * * @param directory the directory to recursively scan for test files. * @returns the list of file paths and labels. */
https://github.com/google/magika/blob/ea2330fe51328ee06e6f7415a9a4f5a0c98edea4/js/test/magika.test.ts#L22-L26
ea2330fe51328ee06e6f7415a9a4f5a0c98edea4
gateway
github_2023
Portkey-AI
typescript
getTagContent
const getTagContent = (tag: string) => { const regex = new RegExp(`<${tag}>(.*?)</${tag}>`, 's'); const match = xml.match(regex); return match ? match[1] : null; };
// Simple XML parser for this specific use case
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/plugins/bedrock/util.ts#L235-L239
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
extractJson
function extractJson(text: string): string[] { const codeBlockRegex = /```+(?:json)?\s*([\s\S]*?)```+/g; const jsonRegex = /{[\s\S]*?}/g; const matches = []; // Extract from code blocks let match; while ((match = codeBlockRegex.exec(text)) !== null) { matches.push(match[1].trim()); } // Extract JS...
// Extract JSON from code blocks and general text
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/plugins/default/jsonKeys.ts#L10-L27
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
extractJson
const extractJson = (text: string): string[] => { const codeBlockRegex = /```+(?:json)?\s*([\s\S]*?)```+/g; const jsonRegex = /{[\s\S]*?}/g; const matches = []; // Extract from code blocks first let match; while ((match = codeBlockRegex.exec(text)) !== null) { matches.push(m...
// Extract JSON from code blocks and general text
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/plugins/default/jsonSchema.ts#L31-L50
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
sendWithTimeout
async function sendWithTimeout(fn: () => Promise<void>, timeoutMs = 200) { const timeoutPromise = new Promise<void>((_, reject) => { const id = setTimeout(() => { clearTimeout(id); reject(new Error('Write timeout')); }, timeoutMs); }); return Promise.race([fn(), timeoutPromise])...
/** * A helper function to enforce a timeout on SSE sends. * @param fn A function that returns a Promise (e.g. stream.writeSSE()) * @param timeoutMs The timeout in milliseconds (default: 2000) */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/start-server.ts#L61-L70
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
onAbort
const onAbort = () => { removeLogClient(clientId); };
// If the client disconnects (closes the tab, etc.), this signal will be aborted
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/start-server.ts#L91-L93
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
showLoadingAnimation
async function showLoadingAnimation() { const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; let i = 0; return new Promise((resolve) => { const interval = setInterval(() => { process.stdout.write(`\r${frames[i]} Starting AI Gateway...`); i = (i + 1) % frames.length; }, 80); ...
// Loading animation function
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/start-server.ts#L156-L173
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
getCacheOptions
function getCacheOptions(cacheConfig: any) { // providerOption.cache needs to be sent here let cacheMode: string | undefined; let cacheMaxAge: string | number = ''; let cacheStatus = 'DISABLED'; if (typeof cacheConfig === 'object' && cacheConfig?.mode) { cacheMode = cacheConfig.mode; cacheMaxAge = ca...
/** * Retrieves the cache options based on the provided cache configuration. * @param cacheConfig - The cache configuration object or string. * @returns An object containing the cache mode and cache max age. */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/handlers/handlerUtils.ts#L1234-L1247
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
transformHeaders
const transformHeaders = ( headers: string, fieldsMapping: Record<string, string> ) => { const field = Object.keys(fieldsMapping).find((key) => headers.includes(`name="${key}"`) ); if (!field) return headers; return headers.replace(`name="${field}"`, `name="${fieldsMapping[field]}"`); };
/** * Transforms the key of the current field in the multipart/form-data request body using the fieldsMapping. * @param headers - The headers of the current multipart/form-data field. * @param fieldsMapping - The mapping of the fields. * @returns The transformed headers. */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/handlers/streamHandlerUtils.ts#L21-L30
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
enqueueFieldValueAndUpdateBuffer
const enqueueFieldValueAndUpdateBuffer = ( chunk: string, controller: TransformStreamDefaultController, buffer: string ) => { controller.enqueue(new TextEncoder().encode(chunk)); return buffer.slice(chunk.length); };
/** * Enqueues the value of the current field in the multipart/form-data request body. * (This currently does not transform the value) * @param chunk - The current chunk of the multipart/form-data body. * @param controller - The controller for the TransformStream. * @param buffer - The buffer to be updated. * @re...
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/handlers/streamHandlerUtils.ts#L40-L47
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
enqueueFileContentAndUpdateBuffer
const enqueueFileContentAndUpdateBuffer = ( chunk: string, controller: TransformStreamDefaultController, buffer: string, rowTransform: (row: Record<string, any>) => Record<string, any> ) => { const jsonLines = chunk.split('\n'); for (const line of jsonLines) { if (line === '\r') { buffer = buffer....
/** * Enqueues the file content and updates the buffer for each jsonl row in the multipart/form-data body. * @param chunk - The current chunk of the multipart/form-data body. * @param controller - The controller for the TransformStream. * @param buffer - The buffer to be updated. * @param rowTransform - The functi...
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/handlers/streamHandlerUtils.ts#L57-L82
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
enqueueFileContentAndUpdateOctetStreamBuffer
const enqueueFileContentAndUpdateOctetStreamBuffer = ( controller: TransformStreamDefaultController, buffer: string, rowTransform: (row: Record<string, any>) => Record<string, any> ) => { const jsonLines = buffer.split('\n'); for (const line of jsonLines) { if (line === '\r') { buffer = buffer.slice...
/** * Enqueues the file content and updates the buffer for each jsonl row in the multipart/form-data body. * @param chunk - The current chunk of the multipart/form-data body. * @param controller - The controller for the TransformStream. * @param buffer - The buffer to be updated. * @param rowTransform - The functi...
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/handlers/streamHandlerUtils.ts#L92-L116
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
AwsMultipartUploadHandler.hmac
hmac(key: Buffer | string, data: string) { return crypto.createHmac('sha256', key).update(data).digest(); }
// Helper to create HMAC
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFile.ts#L51-L53
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
AwsMultipartUploadHandler.sha256
sha256(data: string) { return crypto.createHash('sha256').update(data).digest('hex'); }
// Helper to create SHA256 hash
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFile.ts#L56-L58
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
convertContentTypesToString
const convertContentTypesToString = (acc: string, curr: ContentType) => { if (curr.type !== 'text') return acc; acc += curr.text + '\n'; return acc; };
/* Helper function to use inside reduce to convert ContentType array to string */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFileUtils.ts#L388-L392
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
getMessageContent
const getMessageContent = (message: Message) => { if (message === undefined) return ''; if (typeof message.content === 'object') { return message.content.reduce(convertContentTypesToString, ''); } return message.content || ''; };
/* Handle messages of both string and ContentType array */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFileUtils.ts#L397-L403
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
transformMessagesForLLama3Prompt
const transformMessagesForLLama3Prompt = (messages: Message[]) => { let prompt: string = ''; prompt += LLAMA_3_SPECIAL_TOKENS.PROMPT_START + '\n'; messages.forEach((msg, index) => { prompt += LLAMA_3_SPECIAL_TOKENS.ROLE_START + msg.role + LLAMA_3_SPECIAL_TOKENS.ROLE_END + '\n'; pro...
/* This function transforms the messages for the LLama 3.1 prompt. It adds the special tokens to the beginning and end of the prompt. refer: https://www.llama.com/docs/model-cards-and-prompt-formats/llama3_1 NOTE: Portkey does not restrict messages to alternate user and assistant roles, this is to support more ...
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFileUtils.ts#L411-L428
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
transformMessagesForLLama2Prompt
const transformMessagesForLLama2Prompt = (messages: Message[]) => { let finalPrompt: string = ''; // combine system message with first user message if (messages.length > 0 && messages[0].role === MESSAGE_ROLES.SYSTEM) { messages[0].content = LLAMA_2_SPECIAL_TOKENS.SYSTEM_MESSAGE_START + getMessage...
/* This function transforms the messages for the LLama 2 prompt. It combines the system message with the first user message, and then attaches the message pairs. Finally, it adds the last message to the prompt. refer: https://github.com/meta-llama/llama/blob/main/llama/generation.py#L284-L395 */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFileUtils.ts#L437-L458
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
transformMessagesForMistralPrompt
const transformMessagesForMistralPrompt = (messages: Message[]) => { let finalPrompt: string = `${MISTRAL_CONTROL_TOKENS.BEGINNING_OF_SENTENCE}`; // Mistral does not support system messages. (ref: https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.3/discussions/14) if (messages.length > 0 && messages[0].role...
/* refer: https://docs.mistral.ai/guides/tokenization/ refer: https://github.com/chujiezheng/chat_templates/blob/main/chat_templates/mistral-instruct.jinja */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/uploadFileUtils.ts#L464-L480
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
getTagContent
const getTagContent = (tag: string) => { const regex = new RegExp(`<${tag}>(.*?)</${tag}>`, 's'); const match = xml.match(regex); return match ? match[1] : null; };
// Simple XML parser for this specific use case
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/bedrock/utils.ts#L343-L347
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
base64UrlEncode
function base64UrlEncode(obj: Record<string, any>): string { return btoa(JSON.stringify(obj)) .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); }
/** * Encodes an object as a Base64 URL-encoded string. * @param obj The object to encode. * @returns The Base64 URL-encoded string. */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/google-vertex-ai/utils.ts#L11-L16
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
importPrivateKey
async function importPrivateKey(pem: string): Promise<CryptoKey> { const pemContents = pem .replace(/-----BEGIN PRIVATE KEY-----/g, '') .replace(/-----END PRIVATE KEY-----/g, '') .replace(/\s+/g, ''); const binaryDerString = atob(pemContents); const binaryDer = new Uint8Array(binaryDerString.length);...
/** * Imports a PEM-formatted private key into a CryptoKey object. * @param pem The PEM-formatted private key. * @returns The imported private key. */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/providers/google-vertex-ai/utils.ts#L52-L75
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
RealtimeLlmEventParser.handleEvent
handleEvent(c: Context, event: any, sessionOptions: any): void { switch (event.type) { case 'session.created': this.handleSessionCreated(c, event, sessionOptions); break; case 'session.updated': this.handleSessionUpdated(c, event, sessionOptions); break; case 'conve...
// Main entry point for processing events
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/services/realtimeLlmEventParser.ts#L17-L40
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
RealtimeLlmEventParser.handleSessionCreated
private handleSessionCreated( c: Context, data: any, sessionOptions: any ): void { this.sessionState.sessionDetails = { ...data.session }; const realtimeEventParser = c.get('realtimeEventParser'); if (realtimeEventParser) { c.executionCtx.waitUntil( realtimeEventParser( ...
// Handle `session.created` event
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/services/realtimeLlmEventParser.ts#L43-L61
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
RealtimeLlmEventParser.handleSessionUpdated
private handleSessionUpdated( c: Context, data: any, sessionOptions: any ): void { this.sessionState.sessionDetails = { ...data.session }; const realtimeEventParser = c.get('realtimeEventParser'); if (realtimeEventParser) { c.executionCtx.waitUntil( realtimeEventParser( ...
// Handle `session.updated` event
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/services/realtimeLlmEventParser.ts#L64-L82
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
RealtimeLlmEventParser.handleConversationItemCreated
private handleConversationItemCreated(c: Context, data: any): void { const { item } = data; this.sessionState.conversation.items.set(item.id, data); }
// Conversation-specific handlers
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/services/realtimeLlmEventParser.ts#L85-L88
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
setNestedProperty
function setNestedProperty(obj: any, path: string, value: any) { const parts = path.split('.'); let current = obj; for (let i = 0; i < parts.length - 1; i++) { if (!current[parts[i]]) { current[parts[i]] = {}; } current = current[parts[i]]; } current[parts[parts.length - 1]] = value; }
/** * Helper function to set a nested property in an object. * * @param obj - The object on which to set the property. * @param path - The dot-separated path to the property. * @param value - The value to set the property to. */
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/services/transformToProviderRequest.ts#L13-L23
79e2dcbd617881e169c215a1c30c4bfb481fac7e
gateway
github_2023
Portkey-AI
typescript
transformToProviderRequestJSON
const transformToProviderRequestJSON = ( provider: string, params: Params, fn: string ): { [key: string]: any } => { // Get the configuration for the specified provider let providerConfig = ProviderConfigs[provider]; if (providerConfig.getConfig) { providerConfig = providerConfig.getConfig(params)[fn]; ...
/** * Transforms the request body to match the structure required by the AI provider. * It also ensures the values for each parameter are within the minimum and maximum * constraints defined in the provider's configuration. If a required parameter is missing, * it assigns the default value from the provider's confi...
https://github.com/Portkey-AI/gateway/blob/79e2dcbd617881e169c215a1c30c4bfb481fac7e/src/services/transformToProviderRequest.ts#L127-L145
79e2dcbd617881e169c215a1c30c4bfb481fac7e
tango
github_2023
NetEase
typescript
IdGenerator.setItem
setItem(component: string, id?: string) { if (this.map.has(component)) { const record = this.map.get(component); if (id && !record.includes(id)) { record.push(id); } this.map.set(component, record); } else { const value = id ? [id] : []; this.map.set(component, value)...
/** * 更新组件记录 * @param component */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/id-generator.ts#L25-L36
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
IdGenerator.generateId
generateId(component: string, codeId?: string) { // FIXME: 使用 size 这里可能存在冲突的风险 const size = this.map.get(component)?.length + 1 || 1; const id = codeId || `${camelCase(component)}${size}`; this.setItem(component, id); let fullId = `${component}:${id}`; if (this.prefix) { fullId = `${this....
/** * 获取组件 ID * @param component 组件名, 如 Button, DatePicker * @param codeId 用户自定义的 ID * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/id-generator.ts#L44-L56
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
getNameByMemberExpression
function getNameByMemberExpression(node: t.MemberExpression | t.JSXMemberExpression): string { let objectName; let propertyName; if (t.isIdentifier(node.object) || t.isJSXIdentifier(node.object)) { objectName = node.object.name; } if (t.isIdentifier(node.property) || t.isJSXIdentifier(node.property)) { ...
/** * 获取成员表达式的调用名 * @example Date.now() --> Date.now * @param node * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/generate.ts#L58-L79
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
visitJSXElementAttributes
function visitJSXElementAttributes( node: t.JSXElement, visitCallback: ( name: StringOrNumber, value: any, node: t.JSXAttribute | JSXElementChildrenType, ) => void, ) { node.openingElement.attributes.forEach((attrNode) => { if (isFunction(visitCallback) && attrNode.type === 'JSXAttribute') { ...
/** * 遍历 jsxElement 的 attributes 集合 * @param node * @param visitCallback */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L60-L88
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
removeJSXElementAttributeByName
function removeJSXElementAttributeByName(node: t.JSXElement, attrName: string) { node.openingElement.attributes = node.openingElement.attributes.filter((attrNode) => { if (t.isJSXAttribute(attrNode)) { const name = keyNode2value(attrNode.name); return name !== attrName; } return true; }); }
/** * 删除 jsxElement 的目标属性 * @param node * @param attrName */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L95-L103
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
visitJSXElementByName
function visitJSXElementByName( ast: t.File | t.JSXElement, targetName: string, callback: (node: t.JSXElement) => void, ) { const visitors: TraverseOptions = { JSXElement(path) { if (getJSXElementName(path.node) === targetName) { callback(path.node); } }, }; switch (ast.type) { ...
/** * 匹配名字叫 targetName 的组件 * @param ast * @param targetName * @param callback */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L156-L175
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
addJSXElementAttribute
function addJSXElementAttribute(node: t.JSXElement, name: string, value: any) { if (name === 'children' && node.children) { // jsx children 的情况 node.children = value2jsxChildrenValueNode(value); } else { // basic attributes const jsxAttributeNode = t.jsxAttribute( t.jsxIdentifier(name), ...
/** * 新增 JSXElement 的属性节点 * @param node * @param name * @param value */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L365-L378
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
getLastImportDeclarationIndex
function getLastImportDeclarationIndex(node: t.Program) { let lastImportIndex = 0; node.body.forEach((item, index) => { if (item.type === 'ImportDeclaration') { lastImportIndex = index + 1; } }); return lastImportIndex; }
/** * 从 ast 中找到最后一次 import 的位置的序号 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L429-L437
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
getLastExportDeclarationIndex
function getLastExportDeclarationIndex(node: t.Program) { let lastExportIndex = 0; node.body.forEach((item, index) => { if (item.type === 'ExportNamedDeclaration') { lastExportIndex = index + 1; } }); return lastExportIndex; }
/** * 从 ast 中找到最后一次 export 的位置的序号 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L442-L450
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
getImportDeclarationData
function getImportDeclarationData(node: t.ImportDeclaration): IImportDeclarationPayload { const sourcePath = node2value(node.source); let defaultSpecifier; const specifiers: string[] = []; node.specifiers.forEach((specifier) => { if (specifier.type === 'ImportDefaultSpecifier') { defaultSpecifier = ke...
/** * @deprecated 使用 parseImportDeclaration 代替 * @param node * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L504-L520
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
clearTrackingData
function clearTrackingData(ast: t.File) { traverse(ast, { JSXElement(path) { path.node = removeTrackingAttributes(path.node); }, }); return ast; }
/** * 从文件中移除所有 JSXElement 的追踪属性 * @param ast * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L1146-L1153
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
clearJSXElementTrackingData
function clearJSXElementTrackingData(node: t.JSXElement, overrideProps?: Dict) { traverseExpressionNode(node, { JSXElement(path) { const newNode = createJSXElementAttributesFilter((attrName) => { if (attrName === SLOT.dnd) { return false; } if (overrideProps && attrName in ...
/** * 从 JSXElement 中移除追踪属性 * @param node * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L1160-L1185
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
parseImportDeclaration
function parseImportDeclaration(node: t.ImportDeclaration) { const source = node2value(node.source) as string; const specifiers: IImportSpecifierData[] = []; node.specifiers.forEach((specifierNode) => { const data: IImportSpecifierData = { localName: keyNode2value(specifierNode.local) as string, t...
/** * 解析导入语句 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/helpers/ast/traverse.ts#L1392-L1410
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
Designer.toggleAddComponentPopover
toggleAddComponentPopover( value: boolean, position: { clientX: number; clientY: number; } = this.addComponentPopoverPosition, ) { this._showAddComponentPopover = value; this._addComponentPopoverPosition = position; }
/** * 显示添加组件面板 * @param value 是否显示 * @param position 坐标 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/designer.ts#L280-L289
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DragSource.prototype
get prototype() { return this.workspace.getPrototype(this.data?.name); }
/** * 获取对应的 prototype */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drag-source.ts#L34-L36
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DragSource.set
set(data: ISelectedItemData) { this.data = data; this.isDragging = !!data; }
/** * 更新选中数据 * @param props */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drag-source.ts#L70-L73
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DragSource.clear
clear() { this.data = null; this.isDragging = false; this.dropTarget.clear(); }
/** * 重置 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drag-source.ts#L78-L82
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DragSource.getNode
getNode() { return this.node; }
/** * 获取对应的 node * @deprecated */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drag-source.ts#L88-L90
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DropTarget.prototype
get prototype() { return this.data?.name ? this.workspace.getPrototype(this.data?.name) : null; }
/** * 获取对应的 prototype */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drop-target.ts#L35-L37
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DropTarget.clear
clear() { this.data = null; }
/** * 重置 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drop-target.ts#L73-L75
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
DropTarget.getNode
getNode() { return this.node; }
/** * 获取对应的 node * @deprecated */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/drop-target.ts#L81-L83
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
TangoHistory.back
back() { if (this.couldBack) { const item = this._records[this._index - 1]; this._sync(item.data); this._index--; } }
/** * 上一步 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/history.ts#L94-L100
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
TangoHistory.forward
forward() { if (this.couldForward) { const item = this._records[this._index + 1]; this._sync(item.data); this._index++; } }
/** * 下一步 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/history.ts#L105-L111
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
TangoHistory.go
go(index: number) { const item = this._records[index]; if (item) { this._sync(item.data); this._index = index; } }
/** * 通过相对位置从历史记录加载记录 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/history.ts#L116-L122
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
TangoHistory.push
push(data: PushDataType) { if (this._index < this._records.length - 1) { this._records = this._records.slice(0, this._index + 1); } this._index = this._records.length; this._records.push({ time: Date.now(), ...data, }); const overCount = this._records.length - this._maxSize; ...
/** * push 数据进入历史记录堆栈 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/history.ts#L127-L143
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsRouteConfigFile.getRouteByRoutePath
getRouteByRoutePath(route: string) { let record; for (const item of this.routes) { if (item.path === route) { record = item; break; } } return record; }
/** * 根据路由地址获取 route 对象 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-route-config-file.ts#L44-L53
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsRouteConfigFile.addRoute
addRoute(routePath: string, importFilePath: string) { this.ast = addRouteToRouteFile(this.ast, routePath, importFilePath); return this; }
/** * 添加一条新路由 * @param name */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-route-config-file.ts#L59-L62
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsRouteConfigFile.updateRoute
updateRoute(oldRoutePath: string, newRoutePath: string) { this.ast = updateRouteToRouteFile(this.ast, oldRoutePath, newRoutePath); return this; }
/** * 更新页面路由 * @param oldRoutePath * @param newRoutePath * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-route-config-file.ts#L70-L73
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsRouteConfigFile.removeRoute
removeRoute(route: string) { if (route === '/') { logger.warn('index route should not be removed!'); return; } const record = this.getRouteByRoutePath(route); this.ast = removeRouteFromRouteFile(this.ast, route, record.importPath); return this; }
/** * 删除一条路由 * @param route 路由地址 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-route-config-file.ts#L79-L87
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsServiceFile.addServiceFunctions
addServiceFunctions(configs: Dict<object>) { this.ast = updateServiceConfigToServiceFile(this.ast, configs); return this; }
/** * 批量添加服务函数 * @param configs { [name: string]: object } * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-service-file.ts#L83-L86
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsServiceFile.updateBaseConfig
updateBaseConfig(data: object) { this.ast = updateBaseConfigToServiceFile(this.ast, data); return this; }
/** * 更新服务的基础配置 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-service-file.ts#L105-L108
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsStoreEntryFile.addStore
addStore(name: string) { this.ast = addStoreToEntryFile(this.ast, name); return this; }
/** * 新建模型 * @param name */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-store-entry-file.ts#L43-L46
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsStoreEntryFile.removeStore
removeStore(name: string) { this.ast = removeStoreToEntryFile(this.ast, name); return this; }
/** * 删除模型 * @param name */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-store-entry-file.ts#L52-L55
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsStoreFile.addState
addState(stateName: string, initValue: string) { this.ast = addStoreState(this.ast, stateName, initValue); return this; }
/** * 添加状态属性 * @param stateName * @param initValue */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-store-file.ts#L49-L52
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsStoreFile.removeState
removeState(stateName: string) { this.ast = removeStoreState(this.ast, stateName); return this; }
/** * 移除状态 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-store-file.ts#L57-L60
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsStoreFile.updateState
updateState(stateName: string, code: string) { this.ast = updateStoreState(this.ast, stateName, code); return this; }
/** * 更新状态代码 * @param stateName 状态名 * @param code 代码 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-store-file.ts#L67-L70
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
buildImportMap
function buildImportMap(importedModules: ImportDeclarationDataType) { const map: Dict<IImportSpecifierSourceData> = {}; Object.keys(importedModules).forEach((source) => { const specifiers = importedModules[source]; specifiers?.forEach((specifier) => { map[specifier.localName] = { source, ...
/** * 导入信息转为 变量名->来源 的 map 结构 * @param importedModules * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L42-L54
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
nodeListToTreeData
function nodeListToTreeData(list: IViewNodeData[]) { const map: Record<string, IViewNodeData> = {}; list.forEach((item) => { // 如果不存在,则初始化 if (!map[item.id]) { map[item.id] = { ...item, children: [], }; } // 是否找到父节点,找到则塞进去 if (item.parentId && map[item.parentId]) { ...
/** * 将节点列表转换为 tree data 嵌套数组 * @param list */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L60-L81
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.listImportSources
listImportSources() { return Object.keys(this.importList); }
/** * 依赖列表 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L202-L204
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.listModals
listModals() { const modals: Array<{ label: string; value: string }> = []; const activeViewNodes = this.nodes || new Map(); Array.from(activeViewNodes.values()).forEach((node) => { if (['Modal', 'Drawer'].includes(node.component) && node.props.id) { modals.push({ label: `${node.comp...
/** * 弹窗列表 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L209-L223
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.listForms
listForms() { const forms: Record<string, string[]> = {}; const activeViewNodes = this.nodes; Array.from(activeViewNodes.values()).forEach((node) => { if ( ['XAction', 'XColumnAction', 'XForm', 'XStepForm', 'XSearchForm', 'XFormList'].includes( node.component, ) ) { ...
/** * 表单列表 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L228-L241
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.addImportSpecifiers
addImportSpecifiers(source: string, newSpecifiers: IImportSpecifierData[]) { const existSpecifiers = this.importList[source]; if (existSpecifiers) { const insertedSpecifiers = newSpecifiers.filter((item) => { return !existSpecifiers.find((existItem) => existItem.localName === item.localName); ...
/** * 添加导入符号 * @param source * @param newSpecifiers * @returns */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L249-L261
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.updateImportSpecifiersLegacy
updateImportSpecifiersLegacy(importDeclaration: IImportDeclarationPayload) { const mods = this._importedModules[importDeclaration.sourcePath]; let ast; // 如果模块已存在,需要去重 if (mods) { const targetMod = Array.isArray(mods) ? mods[0] : mods; const specifiers = Array.isArray(mods) ? mods.re...
/** * 更新导入的变量 * @deprecated 使用 updateImportDeclaration 代替 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L267-L291
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.removeUnusedImportSpecifiers
removeUnusedImportSpecifiers() { this.ast = removeUnusedImportSpecifiers(this.ast); return this; }
/** * 清除无效的导入声明 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L296-L299
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.removeNode
removeNode(nodeId: string) { this.ast = removeJSXElement(this.ast, nodeId); return this; }
/** * 删除节点 * @param nodeId */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L309-L312
c48a49961a3b0e8b49f8a617d893e0b4f047147f
tango
github_2023
NetEase
typescript
JsViewFile.updateNodeAttribute
updateNodeAttribute( nodeId: string, attrName: string, attrValue?: any, relatedImports?: string[], ) { return this.updateNodeAttributes(nodeId, { [attrName]: attrValue }, relatedImports); }
/** * 更新节点的属性 * @deprecated 使用 updateNodeAttributes 代替 */
https://github.com/NetEase/tango/blob/c48a49961a3b0e8b49f8a617d893e0b4f047147f/packages/core/src/models/js-view-file.ts#L318-L325
c48a49961a3b0e8b49f8a617d893e0b4f047147f