Introduction
Utility function collection. Provides object deep merge, environment detection, JSON file operations, IP/port utilities, and common helper functions. All sub-module APIs are unified under the ee-core/utils export path.
See also: ps for process state and path utilities | helper (same page)
Import
// ESM
import { extend, is, strictParse, fnDebounce, getPort, publicIpv4 } from 'ee-core/utils';
// CJS
const { extend, is, strictParse, fnDebounce, getPort, publicIpv4 } = require('ee-core/utils');All functions from sub-modules (extend, is, json, pargv, wrap, helper, port, ip) and top-level functions (getPackage, getMAC, machineId, etc.) are available via ee-core/utils.
Top-level Functions
getPackage()
Read and parse package.json from the project root directory.
Returns: unknown — Parsed package.json object.
Example:
const pkg = getPackage();
console.log(pkg.name, pkg.version);getMAC(iface?)
Get the first valid MAC address. Traverses local network interfaces, skipping zero MAC addresses (virtual interfaces).
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
iface | string | No | Specify network interface name; if omitted, all interfaces are traversed |
Returns: string — First valid MAC address.
Throws: If specified interface doesn't exist, has no valid MAC, or no valid MAC globally.
isMAC(macAddress)
Check if input is a valid MAC address format (XX:XX:XX:XX:XX:XX or XX-XX-XX-XX-XX-XX).
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
macAddress | string | Yes | String to check |
Returns: boolean
machineIdSync(original?)
Synchronously get machine unique identifier (hash value).
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
original | boolean | No | Return original value instead of SHA-256 hash. Default: false |
Returns: string — Machine unique identifier.
machineId(original?)
Asynchronously get machine unique identifier (hash value). Suitable for scenarios where blocking the event loop is undesirable.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
original | boolean | No | Return original value instead of SHA-256 hash. Default: false |
Returns: Promise<string> — Machine unique identifier.
getPlatform(delimiter?, isDiffArch?)
Get platform identifier string for build artifact naming and platform detection.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
delimiter | string | No | Separator. Default: '_' |
isDiffArch | boolean | No | Distinguish architecture bitness (Windows only). Default: false |
Returns: string — Platform identifier (e.g. 'windows_64', 'macos_apple', 'linux').
isFileProtocol(protocol)
Check if protocol is file://.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
protocol | string | Yes | Protocol string |
Returns: boolean
isWebProtocol(protocol)
Check if protocol is http:// or https://.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
protocol | string | Yes | Protocol string |
Returns: boolean
isJsProject(baseDir)
Check if the project is a JavaScript project (not TypeScript). Determines by checking if electron/main.js or electron/index.js exists.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
baseDir | string | Yes | Project root directory |
Returns: boolean
extend
Object deep merge utility. Core implementation for framework configuration layer merging.
extend(deep, target, ...sources)
Merge properties from multiple source objects into the target object.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
deep | boolean | ExtendOptions | Yes | Whether to deep merge. true = recursive merge for plain objects |
target | T | Yes | Target object, merge result written here |
sources | Array<Partial<T>> | No | Source objects, merged in order |
Returns: T — Merged target object.
Merge rules:
- Shallow merge (
deep=false): source properties directly overwrite target - Deep merge (
deep=true): plain objects are recursively merged, non-plain-objects overwritten - Skips
__proto__(prevents prototype pollution) - Skips
undefinedvalues - Detects self-references (prevents infinite recursion)
Example:
// Shallow merge
extend(false, { a: 1 }, { a: 2, b: 3 }); // { a: 2, b: 3 }
// Deep merge
extend(true, { a: { x: 1 } }, { a: { y: 2 } }); // { a: { x: 1, y: 2 } }is
Electron runtime environment detection. Exported as a namespace object.
// ESM
import { is } from 'ee-core/utils';
if (is.all(is.main, is.osx)) { /* main process + macOS */ }
// CJS
const { is } = require('ee-core/utils');Detection Functions
| Function | Returns | Description |
|---|---|---|
is.renderer() | boolean | Currently in renderer process (process.type === 'renderer') |
is.main() | boolean | Currently in main process (process.type === 'browser') |
is.osx() | boolean | Operating system is macOS (process.platform === 'darwin') |
is.macOS() | boolean | Alias for osx() |
is.windows() | boolean | Operating system is Windows (process.platform === 'win32') |
is.linux() | boolean | Operating system is Linux |
is.openharmony() | boolean | Operating system is OpenHarmony |
is.x86() | boolean | Processor is x86 (32-bit, process.arch === 'ia32') |
is.x64() | boolean | Processor is x64 (64-bit, process.arch === 'x64') |
is.sandbox() | boolean | Running in macOS sandbox |
is.mas() | boolean | Mac App Store build (process.mas === true) |
is.windowsStore() | boolean | Windows Store build (process.windowsStore === true) |
Combinators
| Function | Signature | Description |
|---|---|---|
is.all(...fn) | (...() => boolean) => boolean | undefined | All conditions true |
is.none(...fn) | (...() => boolean) => boolean | undefined | All conditions false |
is.one(...fn) | (...() => boolean) => boolean | undefined | At least one condition true |
Example:
if (is.all(is.main, is.osx)) {
// Only runs in main process on macOS
}
if (is.none(is.renderer, is.windows)) {
// Not renderer process, not Windows
}json
JSON file read/write utility. Provides synchronous and asynchronous operations.
strictParse(str)
Parse JSON string with validation that result must be an object.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
str | string | Yes | JSON string |
Returns: unknown — Parsed object.
Throws: If result is not an object type.
readSync(filepath)
Synchronously read and parse a JSON file.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | JSON file path |
Returns: unknown — Parsed object.
Throws: If file does not exist.
writeSync(filepath, str, options?)
Synchronously write a JSON file. Auto-creates target directory. Default 2-space indentation.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | Target file path |
str | unknown | Yes | Content to write (objects auto-serialized) |
options | JsonWriteOptions | No | { space?: number, replacer?: Function } |
Returns: void
read(filepath)
Asynchronously read and parse a JSON file.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | JSON file path |
Returns: Promise<unknown> — Parsed object.
write(filepath, str, options?)
Asynchronously write a JSON file. Auto-creates target directory.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | Target file path |
str | unknown | Yes | Content to write |
options | JsonWriteOptions | No | { space?: number, replacer?: Function } |
Returns: Promise<void>
helper
Common utility function collection.
fnDebounce()
Create debounce wrapper factory. Returns a function that applies debounce control to any passed function.
Returns: Debounce wrapper function with signature (fn, delayTime?, isImedite?, args?) => void
Example:
const debounce = fnDebounce();
debounce(myFunction, 300, false, data); // Debounced
debounce(myFunction, 0, true, data); // Immediate (no debounce)getRandomString()
Generate an approximately 10-character random alphanumeric string. Not for security scenarios.
Returns: string (e.g. 'x3k9m2a1b5')
mkdir(filepath, opt?)
Recursively create directory. No error if already exists (mkdir -p equivalent).
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | Directory path |
opt | { mode?: number } | No | Directory permissions |
Returns: void
chmodPath(filepath, mode)
Recursively modify file and directory permissions.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | Target directory path |
mode | number | Yes | Permission value (e.g. 0o755) |
Returns: void
compareVersion(v1, v2)
Compare two semantic version numbers.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
v1 | string | Yes | First version (e.g. '1.2.3') |
v2 | string | Yes | Second version (e.g. '1.3.0') |
Returns: number — 1 if v1 > v2, -1 if v1 < v2, 0 if equal.
stringify(obj, ignore?)
Serialize object to JSON string, excluding specified fields.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
obj | Record<string, unknown> | Yes | Object to serialize |
ignore | string[] | No | Property names to exclude |
Returns: string — Filtered JSON string.
validValue(value)
Check if value is non-null, non-undefined, and non-empty string.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
value | unknown | Yes | Value to check |
Returns: boolean
checkConfig(prop)
Check if a configuration file exists under the project root.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
prop | string | Yes | File path relative to project root |
Returns: boolean
sleep(ms)
Async sleep. Returns a Promise that resolves after the specified milliseconds.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
ms | number | Yes | Sleep time (ms) |
Returns: Promise<void>
systemSleep(ms)
Synchronous blocking sleep. Blocks the current thread. Not suitable for renderer process (will freeze UI).
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
ms | number | Yes | Sleep time (ms), must be >= 0 |
Returns: void
Implementation: Prefer Atomics.wait (zero CPU), fallback to busy-wait loop.
replaceArgsValue(argv, key, value)
Replace a key=value parameter in command line argument array.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
argv | string[] | Yes | Argument array |
key | string | Yes | Parameter key name |
value | string | Yes | New value |
Returns: string[] — Modified argv array.
Example:
replaceArgsValue(['--port=8080', '--env=dev'], 'port', '9090')
// => ['--port=9090', '--env=dev']getValueFromArgv(argv, key)
Get the value of a specified key from command line arguments.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
argv | string[] | Yes | Argument array |
key | string | Yes | Key name |
Returns: unknown — Value or undefined if not found.
fileIsExist(filepath)
Check if a file exists (stat-based).
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
filepath | string | Yes | File path |
Returns: boolean
port
TCP port allocation utility with locking mechanism.
getPort(options?)
Find an available TCP port.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
options | GetPortOptions | No | Port search options |
GetPortOptions:
| Field | Type | Description |
|---|---|---|
port | number | number[] | Preferred port or range. 0 = OS auto-assign |
host | string | Bound host. Unspecified = check all interfaces |
Returns: Promise<number> — Available port number.
Example:
const port = await getPort(); // OS auto-assign
const port = await getPort({ port: 3000 }); // Try 3000, auto-find if occupied
const port = await getPort({ port: [3000, 3001] }); // Try listreleasePortLocks()
Clean up port lock resources (rotation timer + locked port sets). Call during app shutdown.
Returns: void
ip
Public IP address query utility. Supports DNS, HTTPS, and combined query methods.
publicIpv4(options?)
Query public IPv4 address.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
options | IpOptions | No | `{ type?: 'http' |
Returns: Promise<string> & { cancel?: () => void } — IPv4 address with cancel method.
Example:
const p = publicIpv4({ type: 'http', timeout: 5000 });
const ip = await p;
// Or cancel: p.cancel();publicIpv6(options?)
Query public IPv6 address. Same options and return type as publicIpv4.
Returns: Promise<string> & { cancel?: () => void } — IPv6 address with cancel method.
