Workflow base code of n8n providing foundational workflow execution engine for automation platform
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Essential utility functions for object manipulation, async operations, data transformation, validation, and common programming tasks that support workflow execution and development.
Core functions for working with objects, deep copying, and data transformation.
/**
* Check if object is empty (no enumerable properties)
* @param obj - Object to check
* @returns Boolean indicating if object is empty
*/
function isObjectEmpty(obj: object): boolean;
/**
* Create deep copy of object or array
* @param source - Source object to copy
* @returns Deep copied object
*/
function deepCopy<T>(source: T): T;
/**
* Remove circular references from object
* @param obj - Object to clean
* @returns Object without circular references
*/
function removeCircularRefs(obj: object): object;
/**
* Replace circular references with placeholder strings
* @param obj - Object to process
* @returns Object with circular references replaced
*/
function replaceCircularReferences(obj: object): object;
/**
* Check if property name is safe for object access
* @param property - Property name to check
* @returns Boolean indicating if property is safe
*/
function isSafeObjectProperty(property: string): boolean;
/**
* Safely set object property value
* @param obj - Target object
* @param property - Property name
* @param value - Value to set
* @returns Boolean indicating if property was set
*/
function setSafeObjectProperty(obj: object, property: string, value: any): boolean;Safe JSON parsing and stringification with error handling.
/**
* Safe JSON parsing with error handling
* @param jsonString - JSON string to parse
* @param fallback - Fallback value if parsing fails
* @returns Parsed object or fallback value
*/
function jsonParse<T = any>(jsonString: string, fallback?: T): T;
/**
* Safe JSON stringification with circular reference handling
* @param obj - Object to stringify
* @param space - Indentation space (optional)
* @returns JSON string
*/
function jsonStringify(obj: any, space?: number): string;Asynchronous operation helpers including sleep and cancellation.
/**
* Async sleep utility
* @param ms - Milliseconds to sleep
* @returns Promise that resolves after specified time
*/
function sleep(ms: number): Promise<void>;
/**
* Sleep with abort signal support
* @param ms - Milliseconds to sleep
* @param signal - Abort signal for cancellation
* @returns Promise that resolves after time or is cancelled
*/
function sleepWithAbort(ms: number, signal?: AbortSignal): Promise<void>;
/**
* Create deferred promise for async coordination
* @returns Deferred promise with resolve/reject methods
*/
function createDeferredPromise<T>(): IDeferredPromise<T>;
interface IDeferredPromise<T> {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}String manipulation and encoding/decoding functions.
/**
* Base64 decode to UTF-8 string
* @param str - Base64 encoded string
* @returns Decoded UTF-8 string
*/
function base64DecodeUTF8(str: string): string;
/**
* Generate random string of specified length
* @param length - Desired string length
* @param charset - Character set to use (optional)
* @returns Random string
*/
function randomString(length: number, charset?: string): string;
/**
* Generate random integer between min and max (inclusive)
* @param min - Minimum value
* @param max - Maximum value
* @returns Random integer
*/
function randomInt(min: number, max: number): number;File type detection and MIME type handling.
/**
* Get file type from MIME type
* @param mimeType - MIME type string
* @returns File type category
*/
function fileTypeFromMimeType(mimeType: string): BinaryFileType;
type BinaryFileType = 'text' | 'json' | 'image' | 'audio' | 'video' | 'pdf' | 'html';Validation helpers and assertion utilities.
/**
* Assert condition is true or throw error
* @param condition - Condition to assert
* @param message - Error message if assertion fails
* @throws AssertionError if condition is false
*/
function assert(condition: any, message?: string): asserts condition;
/**
* Validate and normalize email address
* @param email - Email address to validate
* @returns Normalized email or null if invalid
*/
function normalizeEmail(email: string): string | null;
/**
* Validate URL format
* @param url - URL string to validate
* @returns Boolean indicating if URL is valid
*/
function isValidUrl(url: string): boolean;Utilities for managing node display options and UI configurations.
/**
* Update display options for node properties
* @param displayOptions - Current display options
* @param properties - Properties to update options for
* @returns Updated display options
*/
function updateDisplayOptions(
displayOptions: IDisplayOptions,
properties: INodeProperties[]
): IDisplayOptions;
interface IDisplayOptions {
show?: { [key: string]: any[] };
hide?: { [key: string]: any[] };
}
/**
* Check if property should be displayed based on conditions
* @param property - Node property definition
* @param currentValues - Current parameter values
* @returns Boolean indicating if property should be shown
*/
function shouldDisplayProperty(
property: INodeProperties,
currentValues: INodeParameters
): boolean;Helper functions for common data transformations and formatting.
/**
* Flatten nested object into dot notation
* @param obj - Object to flatten
* @param prefix - Key prefix (optional)
* @returns Flattened object
*/
function flattenObject(obj: object, prefix?: string): IDataObject;
/**
* Unflatten dot notation object back to nested structure
* @param obj - Flattened object
* @returns Nested object structure
*/
function unflattenObject(obj: IDataObject): object;
/**
* Convert object keys to camelCase
* @param obj - Object to convert
* @returns Object with camelCase keys
*/
function camelCaseKeys(obj: object): object;
/**
* Convert object keys to snake_case
* @param obj - Object to convert
* @returns Object with snake_case keys
*/
function snakeCaseKeys(obj: object): object;
/**
* Pick specified properties from object
* @param obj - Source object
* @param keys - Keys to pick
* @returns Object with only specified keys
*/
function pick<T extends object, K extends keyof T>(
obj: T,
keys: K[]
): Pick<T, K>;
/**
* Omit specified properties from object
* @param obj - Source object
* @param keys - Keys to omit
* @returns Object without specified keys
*/
function omit<T extends object, K extends keyof T>(
obj: T,
keys: K[]
): Omit<T, K>;Utility functions for array manipulation and processing.
/**
* Chunk array into smaller arrays of specified size
* @param array - Array to chunk
* @param size - Chunk size
* @returns Array of chunks
*/
function chunk<T>(array: T[], size: number): T[][];
/**
* Remove duplicate values from array
* @param array - Array to deduplicate
* @param keyFn - Optional key function for complex objects
* @returns Array with unique values
*/
function unique<T>(array: T[], keyFn?: (item: T) => any): T[];
/**
* Flatten nested arrays
* @param array - Array to flatten
* @param depth - Maximum depth to flatten (default: 1)
* @returns Flattened array
*/
function flatten<T>(array: any[], depth?: number): T[];
/**
* Group array elements by key function
* @param array - Array to group
* @param keyFn - Function to determine grouping key
* @returns Object with grouped elements
*/
function groupBy<T, K extends string | number | symbol>(
array: T[],
keyFn: (item: T) => K
): Record<K, T[]>;Usage Examples:
import {
deepCopy,
isObjectEmpty,
jsonParse,
sleep,
randomString,
assert,
updateDisplayOptions,
flattenObject,
chunk,
unique
} from "n8n-workflow";
// Object manipulation
const originalData = {
user: { name: "John", details: { age: 30, city: "NYC" } },
items: [1, 2, 3]
};
const copied = deepCopy(originalData);
console.log('Deep copy created');
const isEmpty = isObjectEmpty({});
console.log('Empty object check:', isEmpty); // true
// Safe JSON operations
const jsonData = jsonParse('{"name": "John", "age": 30}', {});
console.log('Parsed JSON:', jsonData);
const invalidJson = jsonParse('invalid json', { error: 'parsing failed' });
console.log('Invalid JSON fallback:', invalidJson);
// Async utilities
async function asyncExample() {
console.log('Starting operation...');
await sleep(1000); // Wait 1 second
console.log('Operation completed');
// With abort signal
const controller = new AbortController();
setTimeout(() => controller.abort(), 500);
try {
await sleepWithAbort(1000, controller.signal);
} catch (error) {
console.log('Sleep was aborted');
}
}
// String and random utilities
const randomId = randomString(16);
console.log('Random ID:', randomId);
const randomNumber = randomInt(1, 100);
console.log('Random number between 1-100:', randomNumber);
// Assertion
try {
assert(typeof randomNumber === 'number', 'Random number should be numeric');
console.log('Assertion passed');
} catch (error) {
console.log('Assertion failed:', error.message);
}
// Display options
const displayOptions = updateDisplayOptions(
{ show: { operation: ['create', 'update'] } },
[
{ displayName: 'Name', name: 'name', type: 'string' },
{ displayName: 'Email', name: 'email', type: 'string' }
]
);
// Data transformation
const nestedObject = {
user: {
profile: {
name: 'John',
contact: {
email: 'john@example.com'
}
}
}
};
const flattened = flattenObject(nestedObject);
console.log('Flattened:', flattened);
// Result: { 'user.profile.name': 'John', 'user.profile.contact.email': '...' }
// Array utilities
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunks = chunk(numbers, 3);
console.log('Chunked array:', chunks); // [[1,2,3], [4,5,6], [7,8,9]]
const duplicates = [1, 2, 2, 3, 3, 3, 4];
const uniqueValues = unique(duplicates);
console.log('Unique values:', uniqueValues); // [1, 2, 3, 4]
// Complex object operations
const userProfiles = [
{ id: 1, name: 'John', department: 'IT' },
{ id: 2, name: 'Jane', department: 'HR' },
{ id: 3, name: 'Bob', department: 'IT' }
];
const uniqueUsers = unique(userProfiles, user => user.department);
console.log('Unique by department:', uniqueUsers);
// Circular reference handling
const circular: any = { name: 'test' };
circular.self = circular;
const cleaned = removeCircularRefs(circular);
console.log('Cleaned object:', cleaned);
const replaced = replaceCircularReferences(circular);
console.log('Replaced circular refs:', replaced);