import { type ChildProcessPromise } from 'promisify-child-process'; import type { CommandResult, PackageManager } from '@alcalzone/pak'; import type { ExecOptions } from 'node:child_process'; type DockerInformation = { /** If it is a Docker installation */ isDocker: boolean; /** If it is the official Docker image */ isOfficial: true; /** Semver string for official Docker image */ officialVersion: string; } | { /** If it is a Docker installation */ isDocker: boolean; /** If it is the official Docker image */ isOfficial: false; }; export interface HostInfo { /** Converted OS for human readability */ Platform: NodeJS.Platform | 'docker' | 'Windows' | 'OSX'; /** The underlying OS */ os: NodeJS.Platform; /** Information about the docker installation */ dockerInformation?: DockerInformation; /** Host architecture */ Architecture: string; /** Number of CPUs */ CPUs: number | null; /** CPU speed */ Speed: number | null; /** CPU model */ Model: string | null; /** Total RAM of host */ RAM: number; /** System uptime in seconds */ 'System uptime': number; /** Node.JS version */ 'Node.js': string; /** Current time to compare to local time */ time: number; /** Timezone offset to compare to local time */ timeOffset: number; /** Number of available adapters */ 'adapters count': number; /** NPM version */ NPM: string; } interface FormatAliasValueOptions { /** Common attribute of a source object */ sourceCommon?: Partial; /** Common attribute of a target object */ targetCommon?: Partial; /** State to format */ state: ioBroker.State | null | undefined; /** Logger used for logging */ logger: any; /** Prefix for log messages */ logNamespace: string; /** Id of the source object, used for logging */ sourceId?: string; /** Id of the target object, used for logging */ targetId?: string; } export interface DockerImageInformation { /** The official version like v10.0.0 */ version: string; /** Time of last image update */ lastUpdated: string; /** If the version is newer than the one currently running */ isNew: boolean; } export declare enum ERRORS { ERROR_NOT_FOUND = "Not exists", ERROR_EMPTY_OBJECT = "null object", ERROR_NO_OBJECT = "no object", ERROR_DB_CLOSED = "DB closed" } /** All characters that may not appear in an object ID. */ export declare const FORBIDDEN_CHARS: RegExp; /** * recursively copy values from an old object to new one * * @param oldObj source object * @param newObj destination object * @param originalObj optional object for read __no_change__ values * @param isNonEdit optional indicator if copy is in nonEdit part */ export declare function copyAttributes(oldObj: Record, newObj: Record, originalObj?: Record, isNonEdit?: boolean): void; /** * Checks the flag nonEdit and restores non-changeable values if required * * @param oldObject source object * @param newObject destination object */ export declare function checkNonEditable(oldObject: ioBroker.SettableObject | null, newObject: ioBroker.SettableObject): boolean; /** * Checks if a version is up-to-date, throws error on invalid version strings * * @param repoVersion version in repository * @param installedVersion the current installed version */ export declare function upToDate(repoVersion: string, installedVersion: string): boolean; export declare function decryptPhrase(password: string, data: any, callback: (decrypted?: null | string) => void): void; /** * Checks if multiple host objects exists, without using object views * * @param objects the objects db * @returns true if only one host object exists */ export declare function isSingleHost(objects: any): Promise; /** * Checks if at least one host is running in a Multihost environment * * @param objects the objects db * @param states the states db * @returns true if one or more hosts running else false */ export declare function isHostRunning(objects: any, states: any): Promise; /** * Checks if ioBroker is installed in a dev environment */ export declare function isDevInstallation(): boolean; /** In dev installations with uppercase B to match GitHub repo name - try to get rid of it in the long run */ type AppName = 'iobroker' | 'ioBroker'; export declare const appNameLowerCase = "iobroker"; export declare const appName: AppName; /** * Find all own IPs (ipv4 and ipv6) * * The result is cached for 10 seconds. */ export declare function findIPs(): string[]; /** * Fetch the image information of the newest available (official) ioBroker Docker image from DockerHub */ export declare function getNewestDockerImageVersion(): Promise; /** * Get information of a Docker installation */ export declare function getDockerInformation(): DockerInformation; /** * Controller UI upgrade is not supported on Windows and MacOS */ export declare function isControllerUiUpgradeSupported(): boolean; /** * Checks if we are running inside a docker container */ export declare function isDocker(): boolean; /** * Generates a new uuid if non-existing * * @param objects - objects DB * @returns uuid if successfully created/updated */ export declare function createUuid(objects: any): Promise; /** * Download file to tmp or return file name directly * * @param urlOrPath * @param fileName * @param callback */ export declare function getFile(urlOrPath: string, fileName: string, callback: (file?: string) => void): Promise; export declare function getJson(urlOrPath: string, agent: string, callback: (sources?: Record | null, urlOrPath?: string | null) => void): Promise; /** * Return content of the json file. Download it or read directly * * @param urlOrPath URL where the json file could be found * @param agent optional agent identifier like "Windows Chrome 12.56" * @returns json object */ export declare function getJsonAsync(urlOrPath: string, agent?: string): Promise | null>; interface Multilingual { en: string; de?: string; ru?: string; pt?: string; nl?: string; fr?: string; it?: string; es?: string; pl?: string; uk?: string; 'zh-cn'?: string; } export interface AdapterInformation { /** this flag is only true for the js-controller */ controller: boolean; /** adapter version */ version: string; /** path to icon of the adapter */ icon: string; /** path to local icon of the adater */ localIcon?: string; /** title of the adapter */ title: string; /** title of the adapter in multiple languages */ titleLang: Multilingual; /** description of the adapter in multiple languages */ desc: Multilingual; /** platform of the adapter */ platform: 'Javascript/Node.js'; /** keywords of the adapter */ keywords: string[]; /** path to the readme file */ readme: string; /** The installed adapter version, not existing on controller */ runningVersion?: string; /** type of the adapter */ type: string; /** license of the adapter */ license: string; /** url to license information */ licenseUrl?: string; } /** * Get a list of all installed adapters and controller version on this host * * @param hostRunningVersion Version of the running js-controller, will be included in the returned information if provided * @returns object containing information about installed host */ export declare function getInstalledInfo(hostRunningVersion?: string): Record; /** * Get a list of all adapters and controller in some repository file or in /conf/source-dist.json * * @param urlOrPath URL starting with http:// or https:// or local file link * @param additionalInfo destination object * @param callback function (err, sources, actualHash) { } */ export declare function getRepositoryFile(urlOrPath: string, additionalInfo: Record, callback: (err?: Error | null, sources?: Record, actualHash?: string | number) => void): void; /** Result of getRepositoryFileAsync */ export interface RepositoryFile { /** The repository JSON content */ json: ioBroker.RepositoryJson; /** Whether the repository has changed compared to the provided hash */ changed: boolean; /** The actual hash of the repository */ hash: string; } /** * Read on repository * * @param url URL starting with http:// or https:// or local file link * @param hash actual hash * @param force Force repository update despite on hash * @param _actualRepo Actual repository JSON content */ export declare function getRepositoryFileAsync(url: string, hash?: string, force?: boolean, _actualRepo?: ioBroker.RepositoryJson | null): Promise; /** * Sends the given object to the diagnosis server * * @param obj - diagnosis object */ export declare function sendDiagInfo(obj: Record): Promise; /** * Finds the adapter directory of a given adapter * * @param adapter name of the adapter, e.g., hm-rpc * @returns path to adapter directory or null if no directory found */ export declare function getAdapterDir(adapter: string): string | null; /** * Returns the hostname of this host */ export declare function getHostName(): string; export interface InstallNodeModuleOptions { unsafePerm?: boolean; debug?: boolean; cwd?: string; } /** * * Figure out which package manager is in charge, but with a fallback to npm. * * @param cwd Which directory to work in. If none is given, this defaults to ioBroker's root directory. */ export declare function detectPackageManagerWithFallback(cwd?: string): Promise; /** * Installs a node module using npm or a similar package manager * * @param npmUrl Which node module to install * @param options Options for the installation */ export declare function installNodeModule(npmUrl: string, options?: InstallNodeModuleOptions): Promise; export interface UninstallNodeModuleOptions { debug?: boolean; cwd?: string; } /** * Uninstalls a node module using npm or a similar package manager * * @param packageName Which node module to uninstall * @param options Options for the installation */ export declare function uninstallNodeModule(packageName: string, options?: UninstallNodeModuleOptions): Promise; export interface RebuildNodeModulesOptions { debug?: boolean; cwd?: string; module?: string; } /** * Rebuilds all native node_modules that are dependencies of the project in the current working directory / project root. * If `options.cwd` is given, the directory must contain a lockfile. * * @param options Options for the rebuild */ export declare function rebuildNodeModules(options?: RebuildNodeModulesOptions): Promise; export interface GetDiskInfoResponse { 'Disk size': number; 'Disk free': number; } /** * Read disk free space */ export declare function getDiskInfo(): Promise; export interface CertificateInfo { certificateFilename: string | null; /** the certificate itself */ certificate: string; /** serial number */ serialNumber: string; /** type of signature as text like "RSA" */ signature: string; /** bits used for encryption key like 2048 */ keyLength: number; /** issuer of the certificate */ issuer: Record; /** subject that is signed */ subject: Record; /** server name this certificate belong to */ dnsNames: { type: number; value: string; }[]; /** this certificate can be used for the following purposes */ keyUsage: Record; /** usable or client, server or ... */ extKeyUsage: Record; /** certificate validity start datetime */ validityNotBefore: Date; /** certificate validity end datetime */ validityNotAfter: Date; } /** * Returns information about a certificate * * @param cert * @returns certificate information object */ export declare function getCertificateInfo(cert: string): null | CertificateInfo; export interface DefaultCertificates { defaultPrivate: string; defaultPublic: string; } /** Maximum time after which cert has to expire - 365 days in ms */ export declare const MAX_CERT_VALIDITY: number; /** * Returns default SSL certificates (private and public) * * * The following info will be returned: * - defaultPrivate: private RSA key * - defaultPublic: public certificate * *

 *            const certificates = tools.generateDefaultCertificates();
 *        
*/ export declare function generateDefaultCertificates(): DefaultCertificates; /** * Collects information about host and available adapters * * Following info will be collected: * - available adapters * - node.js --version * - npm --version * * @param objects db */ export declare function getHostInfo(objects: any): Promise; /** * Finds the controller root directory * * @returns absolute path to controller dir without ending slash */ export declare function getControllerDir(): string; /** * Get the root dir of the ioBroker installation */ export declare function getRootDir(): string; /** Returns whether the current process is executed via dev-server */ export declare function isDevServerInstallation(): boolean; /** * All paths are returned always relative to /node_modules/' + appName + '.js-controller * the result has always "/" as last symbol */ export declare function getDefaultDataDir(): string; /** * Returns the path of the config file */ export declare function getConfigFileName(): string; /** * Promisifies a function which returns an error as the first argument in its callback * * @param fn The function to promisify * @param context (optional) The context (value of `this` to bind the function to) * @param returnArgNames (optional) If the callback contains multiple arguments, * you can combine them into one object by passing the names as an array. * Otherwise, the Promise will resolve with an array */ export declare function promisify(fn: (...args: any[]) => void, context?: any, returnArgNames?: string[]): (...args: any[]) => Promise; /** * Promisifies a function which does not provide an error as the first argument in its callback * * @param fn The function to promisify * @param context (optional) The context (value of `this` to bind the function to) * @param returnArgNames (optional) If the callback contains multiple arguments, * you can combine them into one object by passing the names as an array. * Otherwise, the Promise will resolve with an array */ export declare function promisifyNoError(fn: (...args: any[]) => void, context?: any, returnArgNames?: string[]): (...args: any[]) => Promise; export declare function setQualityForInstance(objects: any, states: any, namespace: string, q: number): Promise; /** * Converts ioB pattern into regex. * * @param pattern - Regex string to use it in new RegExp(pattern) */ export declare function pattern2RegEx(pattern: string): string; /** * Checks if a pattern is valid * * @param pattern * @pattern pattern to check for validity */ export declare function isValidPattern(pattern: string): boolean; /** * Appends the stack trace generated by `captureStackTrace` to the given string * * @param str - The string to append the stack trace to */ export declare function appendStackTrace(str: string): string; /** * encrypts a value by a given key via AES-192-CBC * * @param key - Secret key * @param value - value to decrypt */ export declare function encrypt(key: string, value: string): string; /** * encrypts a value by a given key via AES-192-CBC * * @param key - Secret key * @param value - value to decrypt */ export declare function decrypt(key: string, value: string): string; /** * Tests whether the given variable is a real object and not an Array * * @param it The variable to test * @returns true if it is Record */ export declare function isObject(it: unknown): it is Record; /** * Tests whether the given variable is really an Array * * @param it The variable to test */ export declare function isArray(it: unknown): it is any[]; /** * Measure the Node.js event loop lag and repeatedly call the provided callback function with the updated results * * @param ms The number of milliseconds for monitoring * @param cb Callback function to call for each new value */ export declare function measureEventLoopLag(ms: number, cb: (eventLoopLag?: number) => void): void; /** * This function convert state values by read and write of aliases. Function is synchronous. * On errors, null is returned instead * * @param options */ export declare function formatAliasValue(options: FormatAliasValueOptions): ioBroker.State | null; /** * remove given id from all enums * * @param objects object to access objects db * @param id the object id which will be deleted from enums * @param allEnums objects with all enums to use - if not provided all enums will be queried * @returns Promise All objects are tried to be updated - reject will happen as soon as one fails with the error of the first fail */ export declare function removeIdFromAllEnums(objects: any, id: string, allEnums?: Record): Promise; /** * Parses dependencies to standardized object of form * * @param dependencies dependencies array or single dependency * @returns parsedDeps parsed dependencies */ export declare function parseDependencies(dependencies: string[] | Record[] | string | Record | undefined): Record; /** * Validates types of `obj.common` properties and `object.type`, if invalid types are used, an error is thrown. * If attributes of `obj.common` are not provided, no error is thrown. obj.type has to be there and has to be valid. * * @param obj an object which will be validated * @param extend (optional) if true checks allow more optional cases for extendObject calls * @throws Error if a property has the wrong type or `obj.type` is non-existing */ export declare function validateGeneralObjectProperties(obj: any, extend?: boolean): void; /** * get all instances of all adapters in the list * * @param adapters list of adapter names to get instances for * @param objects class redis objects * @returns array of IDs */ export declare function getAllInstances(adapters: string[], objects: any): Promise; /** * Get all existing enums * * @param objects - objects db * @returns Promise */ export declare function getAllEnums(objects: any): Promise>; /** * get async all instances of one adapter * * @param adapter name of the adapter * @param objects objects DB * @param withObjects return objects instead of only ids */ export declare function getInstances(adapter: string, objects: any, withObjects: TWithObjects): Promise; /** * Executes a command asynchronously. On success, the promise resolves with stdout and stderr. * On error, the promise rejects with the exit code or signal, as well as stdout and stderr. * * @param command The command to execute * @param execOptions The options for child_process.exec * @returns child process promise */ export declare function execAsync(command: string, execOptions?: ExecOptions): ChildProcessPromise; /** * Takes input from one stream and writes it to another as soon as a complete line was read. * * @param input The stream to read from * @param output The stream to write into */ export declare function pipeLinewise(input: NodeJS.ReadableStream, output: NodeJS.WritableStream): void; /** * Checks if an adapter is an ESM module or CJS * * @param adapter name of the adapter like hm-rpc */ export declare function isAdapterEsmModule(adapter: string): Promise; /** * Find the adapter main file as full path * * @param adapter - adapter name of the adapter, e.g., hm-rpc * @returns full file name */ export declare function resolveAdapterMainFile(adapter: string): Promise; /** * Returns the default nodeArgs required to execute the main file, e.g., transpile hooks for TypeScript * * @param mainFile * @returns default node args for cli */ export declare function getDefaultNodeArgs(mainFile: string): string[]; /** * Returns the default paths used to resolve modules using `require.resolve()` * * @param callerModule The module that wants to resolve another module */ export declare function getDefaultRequireResolvePaths(callerModule: NodeModule): string[]; /** * Tests if the given URL matches the format /[#] * * @param url The URL to parse */ export declare function isShortGithubUrl(url: string): boolean; export interface ParsedGithubUrl { user: string; repo: string; commit?: string; } /** * Tries to parse a URL in the format /[#] into its separate parts * * @param url The URL to parse */ export declare function parseShortGithubUrl(url: string): ParsedGithubUrl | null; /** * Tests if the given pathname matches the format //[.git][//[.zip|.gz]] * * @param pathname The pathname part of a GitHub URL */ export declare function isGithubPathname(pathname: string): boolean; /** * Tries to a GitHub pathname format //[.git][//[.zip|.gz|.tar.gz]] into its separate parts * * @param pathname The pathname part of a GitHub URL */ export declare function parseGithubPathname(pathname: string): ParsedGithubUrl | null; /** * Removes properties which are given by preserve * * @param preserve - object which has true entries (or array of selected attributes) for all attributes that should be removed from currObj * @param oldObj - old object * @param newObj - new object */ export declare function removePreservedProperties(preserve: Record, oldObj: Record, newObj: Record): void; /** * Returns the array of system.adapter..* objects which are created for every instance * * @param namespace - adapter namespace + id, e.g., hm-rpc.0 */ export declare function getInstanceIndicatorObjects(namespace: string): ioBroker.StateObject[]; export type InternalLogger = Omit; export declare function getLogger(log: any): InternalLogger; /** * Set capabilities of the given executable on Linux systems * * @param execPath - path to the executable for node you can determine it via process.execPath * @param capabilities - capabilities to set, e.g. ['cap_net_admin', 'cap_net_bind_service'] * @param modeEffective - add effective mode * @param modePermitted - add permitted mode * @param modeInherited - add inherited mode */ export declare function setExecutableCapabilities(execPath: string, capabilities: string[], modeEffective?: boolean, modePermitted?: boolean, modeInherited?: boolean): Promise; /** * Reads the licenses from iobroker.net * Reads the licenses from iobroker.net and if no login/password provided stores it in `system.licenses` * * @param objects Object store instance * @param login Login for ioBroker.net * @param password Decoded password for ioBroker.net * @returns array of all licenses stored on iobroker.net */ export declare function updateLicenses(objects: any, login: string, password: string): Promise; export interface GZipFileOptions { deleteInput?: boolean; } /** * Compresses an input file using GZip and writes it somewhere else * * @param inputFilename The filename of the input file that should be gzipped * @param outputFilename The filename of the output file where the gzipped content should be written to * @param options Options for the compression */ export declare function compressFileGZip(inputFilename: string, outputFilename: string, options?: GZipFileOptions): Promise; export interface DataDirValidation { /** if data directory is valid */ valid: boolean; /** absolute path it resolves too */ path: string; /** reason of rejection */ reason: string; } /** * Validate if the dir, is a valid dataDir * Data dirs in node_modules are not allowed, note that dataDirs are relative to js-controller dir or absolute * * @param dataDir dataDir to check */ export declare function validateDataDir(dataDir: string): DataDirValidation; /** * If an array is passed it will be stringified, else the parameter is returned * * @param maybeArr parameter which will be stringified if it is an array */ export declare function maybeArrayToString(maybeArr: T): T extends any[] ? string : T; /** * Checks if given ip address is matching ipv4 or ipv6 localhost * * @param ip ipv4 or ipv6 address */ export declare function isLocalAddress(ip: string): boolean; /** * Checks if given ip address is matching ipv4 or ipv6 "listen all" address * * @param ip ipv4 or ipv6 address */ export declare function isListenAllAddress(ip: string): boolean; /** * Retrieve the localhost address according to the configured DNS resolution strategy */ export declare function getLocalAddress(): '127.0.0.1' | '::1'; /** * Get the ip to listen to all addresses according to configured DNS resolution strategy */ export declare function getListenAllAddress(): '0.0.0.0' | '::'; /** * Ensure that DNS is resolved according to ioBroker config */ export declare function ensureDNSOrder(): void; /** * Determine if ioBroker is installed as systemd service */ export declare function isIoBrokerInstalledAsSystemd(): Promise; /** * Get a new host object * * @param oldObj the previous host object */ export declare function getHostObject(oldObj?: ioBroker.HostObject | null): ioBroker.HostObject; /** * Get file name of the pids file * * @returns file name of the pids file */ export declare function getPidsFileName(): string; /** * Get all ioBroker process ids * * @returns process ids or empty array if no process running */ export declare function getPids(): Promise; /** * Check if given string is a valid loglevel * * @param level level to validate */ export declare function isLogLevel(level: string): level is ioBroker.LogLevel; /** * Get the controller pid * * @returns pid if running else undefined */ export declare function getControllerPid(): Promise; export * from '../../lib/common/maybeCallback.js'; //# sourceMappingURL=tools.d.ts.map