Comprehensive internal utility library for Prisma's CLI operations, schema management, generator handling, and engine interactions
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The utilities domain provides comprehensive cross-platform file system operations, environment handling, formatting utilities, and general-purpose helper functions for the Prisma ecosystem.
loadEnvFile({ schemaPath, config, printMessage? })Loads environment variables from files next to the schema with comprehensive configuration support.
function loadEnvFile({
schemaPath,
config,
printMessage = false,
}: {
schemaPath?: string
printMessage?: boolean
config: PrismaConfigInternal
}): Promise<void>Parameters:
schemaPath?: string - Path to the Prisma schemaconfig: PrismaConfigInternal - Prisma configuration objectprintMessage?: boolean - Whether to print loading messagesReturns: Promise<void> - Loads variables into process.env
Example:
await loadEnvFile({
schemaPath: './prisma/schema.prisma',
config: loadedConfig,
printMessage: true
})tryLoadEnvs({ rootEnvPath, schemaEnvPath }, opts?)Attempts to load environment files with comprehensive error handling and conflict detection.
function tryLoadEnvs(
{
rootEnvPath,
schemaEnvPath,
}: {
rootEnvPath: string | null | undefined
schemaEnvPath: string | null | undefined
},
opts: { conflictCheck: 'warn' | 'error' | 'none' } = {
conflictCheck: 'none',
}
): LoadedEnvParameters:
rootEnvPath: string | null | undefined - Path to root .env fileschemaEnvPath: string | null | undefined - Path to schema-specific .env fileopts: { conflictCheck: 'warn' | 'error' | 'none' } - Conflict handling optionsReturns: LoadedEnv - Information about loaded environment files
LoadedEnv Type:
type LoadedEnv =
| {
message?: string
parsed: {
[x: string]: string
}
}
| undefinedgetEnvPaths(schemaPath, options?)Gets paths for environment files relative to schema location.
function getEnvPaths(
schemaPath: string,
options?: { cwd?: string }
): string[]Parameters:
schemaPath: string - Path to the Prisma schemaoptions?: { cwd?: string } - Current working directoryReturns: string[] - Array of potential env file paths
getMigrateConfigDir(schemaPath)Gets the migration configuration directory path based on schema location.
function getMigrateConfigDir(schemaPath: string): stringParameters:
schemaPath: string - Path to the Prisma schemaReturns: string - Path to migrations directory
extractPreviewFeatures(generators)Extracts preview features from generator configurations.
function extractPreviewFeatures(generators: GeneratorConfig[]): string[]Parameters:
generators: GeneratorConfig[] - Array of generator configurationsReturns: string[] - Array of preview feature names
pathToPosix(path)Converts Windows-style paths to POSIX format for cross-platform compatibility.
function pathToPosix(path: string): stringParameters:
path: string - Path to convertReturns: string - POSIX-style path
longestCommonPathPrefix(paths)Finds the longest common path prefix among multiple paths.
function longestCommonPathPrefix(paths: string[]): stringParameters:
paths: string[] - Array of file pathsReturns: string - Longest common prefix
Example:
const paths = [
'/home/user/project/src/file1.ts',
'/home/user/project/src/file2.ts',
'/home/user/project/tests/test1.ts'
]
const commonPrefix = longestCommonPathPrefix(paths)
console.log(commonPrefix) // '/home/user/project/'chmodPlusX(file)Makes a file executable by adding execute permissions (cross-platform).
function chmodPlusX(file: string): voidParameters:
file: string - Path to the file to make executablefsFunctionalNamespace containing functional file system utilities.
namespace fsFunctional {
// Functional file system operations
function readFile(path: string): Promise<string>
function writeFile(path: string, content: string): Promise<void>
function exists(path: string): Promise<boolean>
// Additional functional utilities...
}fsUtilsNamespace containing general file system utility functions.
namespace fsUtils {
// File system utility functions
function ensureDir(path: string): Promise<void>
function copyFile(src: string, dest: string): Promise<void>
function removeFile(path: string): Promise<void>
// Additional utilities...
}keyBy<T>(array, getKey)Creates an object from an array using a key extraction function.
function keyBy<T>(
array: T[],
getKey: (item: T) => string
): { [key: string]: T }Parameters:
array: T[] - Array to processgetKey: (item: T) => string - Function to extract keysReturns: { [key: string]: T } - Object indexed by extracted keys
Example:
const users = [
{ id: '1', name: 'Alice' },
{ id: '2', name: 'Bob' }
]
const usersById = keyBy(users, user => user.id)
console.log(usersById['1'].name) // 'Alice'pick(obj, keys)Creates a new object with only the specified keys from the source object.
function pick<T, K extends keyof T>(
obj: T,
keys: K[]
): Pick<T, K>Parameters:
obj: T - Source objectkeys: K[] - Keys to include in the new objectReturns: Pick<T, K> - Object with only specified keys
mapObjectValues(obj, mapper)Maps object values using a transformation function.
function mapObjectValues<T, U>(
obj: { [key: string]: T },
mapper: (value: T, key: string) => U
): { [key: string]: U }Parameters:
obj: { [key: string]: T } - Source objectmapper: (value: T, key: string) => U - Value transformation functionReturns: { [key: string]: U } - Object with transformed values
maxBy<T>(array, getValue)Finds the maximum element in an array using a value extraction function.
function maxBy<T>(
array: T[],
getValue: (item: T) => number
): T | undefinedParameters:
array: T[] - Array to searchgetValue: (item: T) => number - Function to extract comparison valuesReturns: T | undefined - Element with maximum value or undefined if array is empty
maxWithComparator<T>(array, comparator)Finds the maximum element using a custom comparator function.
function maxWithComparator<T>(
array: T[],
comparator: (a: T, b: T) => number
): T | undefinedhasOwnProperty(obj, prop)Type-safe Object.hasOwnProperty check with proper typing.
function hasOwnProperty<T>(
obj: T,
prop: PropertyKey
): prop is keyof TParameters:
obj: T - Object to checkprop: PropertyKey - Property to check forReturns: prop is keyof T - Type guard indicating property existence
isValidJsIdentifier(name)Validates if a string is a valid JavaScript identifier.
function isValidJsIdentifier(name: string): booleanParameters:
name: string - String to validateReturns: boolean - True if valid JavaScript identifier
isPromiseLike(value)Type guard to check if a value is Promise-like (has .then method).
function isPromiseLike(value: any): value is PromiseLike<any>Parameters:
value: any - Value to checkReturns: value is PromiseLike<any> - Type guard for Promise-like objects
isCi()Detects if the code is running in a Continuous Integration environment.
function isCi(): booleanReturns: boolean - True if running in CI
isInteractive()Detects if the terminal supports interactive input/output.
function isInteractive(): booleanReturns: boolean - True if terminal is interactive
canPrompt()Determines if interactive prompts are available and appropriate.
function canPrompt(): booleanReturns: boolean - True if prompts can be shown
isInContainer()Detects if the process is running inside a container (Docker, etc.).
function isInContainer(): booleanReturns: boolean - True if running in a container
isCurrentBinInstalledGlobally()Checks if the current binary is globally installed.
function isCurrentBinInstalledGlobally(): booleanReturns: boolean - True if globally installed
isInNpmLifecycleHook()Detects if the code is running within an npm lifecycle hook.
function isInNpmLifecycleHook(): booleanReturns: boolean - True if in npm lifecycle hook
maybeInGitHook()Detects if the code might be running in a Git hook.
function maybeInGitHook(): booleanReturns: boolean - True if possibly in Git hook
formatms(ms)Formats milliseconds into human-readable time duration.
function formatms(ms: number): stringParameters:
ms: number - Milliseconds to formatReturns: string - Formatted duration string
Example:
console.log(formatms(1000)) // '1s'
console.log(formatms(60000)) // '1m'
console.log(formatms(1500)) // '1.5s'
console.log(formatms(90000)) // '1m 30s'formatTable(data)Formats data into a console-friendly table layout.
function formatTable(data: Array<{ [key: string]: any }>): stringParameters:
data: Array<{ [key: string]: any }> - Array of objects to format as tableReturns: string - Formatted table string
drawBox(options)Draws a decorative text box around content for console output.
function drawBox(options: DrawBoxOptions): stringDrawBoxOptions:
interface DrawBoxOptions {
content: string // Content to box
title?: string // Optional title
padding?: number // Internal padding (default: 1)
borderStyle?: 'single' | 'double' | 'rounded' // Border style
}link(url)Creates a formatted clickable link for console output.
function link(url: string): stringParameters:
url: string - URL to formatReturns: string - Formatted link string
maskSchema(schema)Masks sensitive information in Prisma schema strings for logging.
function maskSchema(schema: string): stringParameters:
schema: string - Schema content to maskReturns: string - Schema with sensitive data masked
Example:
const schema = `
datasource db {
provider = "postgresql"
url = "postgresql://user:secret@localhost:5432/db"
}
`
const masked = maskSchema(schema)
// Returns schema with URL credentials maskedload<T>(id, platformInfo)Wrapper around require for loading Node-API libraries with enhanced error handling and platform-specific troubleshooting.
function load<T>(id: string, platformInfo: PlatformInfo): TParameters:
id: string - Module identifier to loadplatformInfo: PlatformInfo - Platform information for error reportingReturns: T - Loaded library/module
Throws: Enhanced error with platform-specific troubleshooting information
Example:
import { load } from '@prisma/internals'
import { getPlatform } from '@prisma/get-platform'
try {
const platformInfo = await getPlatform()
const queryEngine = load<QueryEngine>('@prisma/query-engine', platformInfo)
console.log('Query engine loaded successfully')
} catch (error) {
console.error('Failed to load query engine:', error.message)
// Error includes platform-specific troubleshooting steps
}locateLocalCloudflareD1(options)Locates local Cloudflare D1 SQLite database files created by Wrangler for development.
function locateLocalCloudflareD1(options: {
arg: '--to-local-d1' | '--from-local-d1'
}): Promise<string>Parameters:
options.arg: '--to-local-d1' | '--from-local-d1' - Command flag determining operation directionReturns: Promise<string> - Path to the local D1 database file
Throws:
.wrangler/state/v3/d1/miniflare-D1DatabaseObject/Example:
import { locateLocalCloudflareD1 } from '@prisma/internals'
try {
const d1Path = await locateLocalCloudflareD1({
arg: '--to-local-d1'
})
console.log('Found local D1 database:', d1Path)
// Use file:// URL format: `file:${d1Path}`
} catch (error) {
if (error.message.includes('No Cloudflare D1 databases found')) {
console.log('Run `wrangler d1 create <DATABASE_NAME>` and `wrangler dev` first')
} else if (error.message.includes('Multiple Cloudflare D1 databases found')) {
console.log('Use --to-url or --from-url with explicit file path instead')
}
}Directory Structure:
.wrangler/
state/
v3/
d1/
miniflare-D1DatabaseObject/
<uuid1>.sqlite ← Located by this function
<uuid2>.sqlite ← Multiple files cause errorgetCommandWithExecutor(command)Gets command with appropriate executor (npx, yarn, pnpm, etc.) based on project setup.
function getCommandWithExecutor(command: string): stringParameters:
command: string - Base command to executeReturns: string - Command prefixed with appropriate executor
Example:
const cmd = getCommandWithExecutor('prisma generate')
console.log(cmd) // 'npx prisma generate' or 'yarn prisma generate'callOnceOnSuccess<T>(fn)Ensures a function is called only once on successful execution.
function callOnceOnSuccess<T>(fn: () => T): () => TParameters:
fn: () => T - Function to wrapReturns: () => T - Wrapped function that executes only once successfully
parseAWSNodejsRuntimeEnvVarVersion(version)Parses AWS Lambda Node.js runtime version from environment variables.
function parseAWSNodejsRuntimeEnvVarVersion(version: string): string | nullParameters:
version: string - AWS runtime version stringReturns: string | null - Parsed Node.js version or null
serializeQueryEngineName(name)Serializes query engine name for consistent identification.
function serializeQueryEngineName(name: string): stringParameters:
name: string - Query engine nameReturns: string - Serialized name
isPrismaPostgres(url)Detects if a URL is for Prisma Postgres service.
function isPrismaPostgres(url: string): booleanisPrismaPostgresDev(url)Detects if a URL is for Prisma Postgres development environment.
function isPrismaPostgresDev(url: string): booleanPRISMA_POSTGRES_PROTOCOLProtocol constant for Prisma Postgres connections.
const PRISMA_POSTGRES_PROTOCOL: stringPRISMA_POSTGRES_PROVIDERProvider constant for Prisma Postgres.
const PRISMA_POSTGRES_PROVIDER: stringloggerComprehensive logging namespace providing structured logging with color-coded output and environment-aware controls.
namespace logger {
// Core logging functions
function log(...data: any[]): void
function info(message: any, ...optionalParams: any[]): void
function warn(message: any, ...optionalParams: any[]): void
function error(message: any, ...optionalParams: any[]): void
function query(message: any, ...optionalParams: any[]): void
// Configuration
const tags: {
error: string // red('prisma:error')
warn: string // yellow('prisma:warn')
info: string // cyan('prisma:info')
query: string // blue('prisma:query')
}
const should: {
warn(): boolean // Returns !process.env.PRISMA_DISABLE_WARNINGS
}
}logger.log(...data)Direct console.log wrapper for general output.
function log(...data: any[]): voidParameters:
...data: any[] - Data to logExample:
import { logger } from '@prisma/internals'
logger.log('Starting Prisma operation...')
logger.log('User:', { id: 1, name: 'Alice' })logger.info(message, ...optionalParams)Logs informational messages with cyan-colored prisma:info tag.
function info(message: any, ...optionalParams: any[]): voidParameters:
message: any - Primary message...optionalParams: any[] - Additional parametersExample:
logger.info('Database connected successfully')
logger.info('Found models:', modelNames)logger.warn(message, ...optionalParams)Logs warning messages with yellow-colored prisma:warn tag. Respects PRISMA_DISABLE_WARNINGS environment variable.
function warn(message: any, ...optionalParams: any[]): voidParameters:
message: any - Warning message...optionalParams: any[] - Additional parametersEnvironment Control:
PRISMA_DISABLE_WARNINGS=1 to suppress warningsExample:
logger.warn('Deprecated feature usage detected')
logger.warn('Migration will affect', affectedTables.length, 'tables')logger.error(message, ...optionalParams)Logs error messages with red-colored prisma:error tag.
function error(message: any, ...optionalParams: any[]): voidParameters:
message: any - Error message...optionalParams: any[] - Additional parametersExample:
logger.error('Connection failed:', error.message)
logger.error('Invalid schema format at line', lineNumber)logger.query(message, ...optionalParams)Logs database query information with blue-colored prisma:query tag.
function query(message: any, ...optionalParams: any[]): voidParameters:
message: any - Query information...optionalParams: any[] - Additional parametersExample:
logger.query('SELECT * FROM users WHERE id = $1', [userId])
logger.query('Migration completed in', duration, 'ms')logger.tagsColor-coded tag constants for consistent logging format.
const tags: {
error: string // red('prisma:error')
warn: string // yellow('prisma:warn')
info: string // cyan('prisma:info')
query: string // blue('prisma:query')
}logger.shouldEnvironment-aware logging controls.
const should: {
warn(): boolean // Returns !process.env.PRISMA_DISABLE_WARNINGS
}Example Usage:
import { logger } from '@prisma/internals'
// Complete logging example
async function runMigration() {
logger.info('Starting migration process')
try {
if (logger.should.warn() && hasWarnings) {
logger.warn('Migration contains potential data loss operations')
}
logger.query('BEGIN TRANSACTION')
await runMigrationSteps()
logger.query('COMMIT TRANSACTION')
logger.info('Migration completed successfully')
} catch (error) {
logger.query('ROLLBACK TRANSACTION')
logger.error('Migration failed:', error.message)
throw error
}
}
// Environment control
process.env.PRISMA_DISABLE_WARNINGS = '1'
logger.warn('This warning will not be shown')handleLibraryLoadingErrors(error)Handles errors that occur when loading engine libraries with helpful messaging.
function handleLibraryLoadingErrors(error: Error): neverParameters:
error: Error - Library loading errorThrows: Enhanced error with helpful troubleshooting information
handlePanic(error)Handles panic errors with appropriate user-friendly messaging.
function handlePanic(error: Error): neverParameters:
error: Error - Panic error to handleThrows: User-friendly panic error
printConfigWarnings(warnings)Prints configuration warnings to the console with proper formatting.
function printConfigWarnings(warnings: string[]): voidParameters:
warnings: string[] - Array of warning messagessetClassName(obj, className)Sets the class name property for error objects and debugging.
function setClassName(obj: any, className: string): voidParameters:
obj: any - Object to set class name onclassName: string - Class name to setmissingGeneratorMessage(provider?)Creates an informative message about missing generators.
function missingGeneratorMessage(provider?: string): stringParameters:
provider?: string - Optional generator provider nameReturns: string - Formatted missing generator message
parseEnvValue(value)Parses environment variable values with proper type conversion.
function parseEnvValue(value: string): EnvValueParameters:
value: string - Environment variable valueReturns: EnvValue - Parsed environment value object
parseBinaryTargetsEnvValue(value)Parses binary targets from environment variable values.
function parseBinaryTargetsEnvValue(value: string): BinaryTargetsEnvValue[]Parameters:
value: string - Environment variable containing binary targetsReturns: BinaryTargetsEnvValue[] - Parsed binary targets array
extractSchemaContent(input)Extracts schema content from various input formats.
function extractSchemaContent(input: SchemaFileInput): stringParameters:
input: SchemaFileInput - Schema input (string or multiple files)Returns: string - Extracted schema content
toSchemasContainer(schemas)Converts schemas to internal container format.
function toSchemasContainer(schemas: MultipleSchemas): SchemasContainertoSchemasWithConfigDir(schemas, configDir)Converts schemas to container format with configuration directory.
function toSchemasWithConfigDir(
schemas: MultipleSchemas,
configDir: string
): SchemasContainerversionPackage version from package.json.
const version: stringbinaryTargetRegexRegular expression for validating binary target formats.
const binaryTargetRegex: RegExpvercelPkgPathRegexRegular expression for detecting Vercel package paths.
const vercelPkgPathRegex: RegExpbylineDefault export providing line-by-line stream reading utility.
const byline: {
createStream(): NodeJS.ReadWriteStream
// Additional stream processing methods
}import {
tryLoadEnvs,
getEnvPaths,
isCi,
isInteractive,
canPrompt,
formatms
} from '@prisma/internals'
async function setupEnvironment(schemaPath: string) {
const startTime = Date.now()
// Detect environment
console.log('Environment Detection:')
console.log(`CI: ${isCi()}`)
console.log(`Interactive: ${isInteractive()}`)
console.log(`Can Prompt: ${canPrompt()}`)
// Load environment files
console.log('\nLoading environment files...')
const envPaths = getEnvPaths(schemaPath)
console.log('Potential env paths:', envPaths)
const loadedEnv = await tryLoadEnvs(schemaPath, {
printMessage: true
})
console.log('Environment loading result:', loadedEnv.message)
console.log('Loaded from:', loadedEnv.paths)
const setupTime = Date.now() - startTime
console.log(`Environment setup completed in ${formatms(setupTime)}`)
return loadedEnv
}import {
keyBy,
pick,
mapObjectValues,
maxBy,
hasOwnProperty,
isValidJsIdentifier
} from '@prisma/internals'
interface Model {
name: string
fields: Array<{ name: string; type: string; isOptional: boolean }>
createdAt: Date
}
function processModels(models: Model[]) {
// Index models by name
const modelsByName = keyBy(models, model => model.name)
// Get basic model info
const modelSummaries = models.map(model =>
pick(model, ['name', 'createdAt'])
)
// Transform field types
const modelsWithTransformedFields = mapObjectValues(
modelsByName,
model => ({
...model,
fields: model.fields.map(field => ({
...field,
isValidIdentifier: isValidJsIdentifier(field.name)
}))
})
)
// Find most recent model
const newestModel = maxBy(models, model => model.createdAt.getTime())
// Validate model names
for (const model of models) {
if (!hasOwnProperty(modelsByName, model.name)) {
console.warn(`Model ${model.name} not found in index`)
}
}
return {
byName: modelsWithTransformedFields,
summaries: modelSummaries,
newest: newestModel
}
}import {
chmodPlusX,
pathToPosix,
longestCommonPathPrefix,
fsFunctional,
fsUtils
} from '@prisma/internals'
async function setupProjectFiles(projectPath: string) {
// Convert to POSIX paths for cross-platform compatibility
const posixPath = pathToPosix(projectPath)
// Generate script paths
const scriptPaths = [
`${posixPath}/scripts/generate.sh`,
`${posixPath}/scripts/migrate.sh`,
`${posixPath}/scripts/deploy.sh`
]
// Find common directory
const commonPrefix = longestCommonPathPrefix(scriptPaths)
console.log('Scripts directory:', commonPrefix)
// Ensure directory exists
await fsUtils.ensureDir(commonPrefix)
// Create and make scripts executable
for (const scriptPath of scriptPaths) {
const scriptName = scriptPath.split('/').pop()
const scriptContent = `#!/bin/bash\necho "Running ${scriptName}..."`
await fsFunctional.writeFile(scriptPath, scriptContent)
chmodPlusX(scriptPath)
console.log(`Created executable script: ${scriptPath}`)
}
}Install with Tessl CLI
npx tessl i tessl/npm-prisma--internals