lib/include.js

const path = require('node:path');
const createId = require('./createId.js');

/**
 * @module pete/lib/include
 */
module.exports = include;

/**
 * Require
 *
 * @external require
 * @see {@link https://nodejs.org/api/modules.html#modules_require_id}
 */

/**
 * Tries to return whatever was returned from `require` or NULL (if module could not be loaded).
 * If `id` is not a string, it will be returned without calling `require` for anything.
 *
 * @example
 * var factory = include('./local/module') || include('global-module');
 *
 * @alias module:pete/lib/include
 * @see {@link external:require}
 * @param {string} id   module name or path (just like for {@link external:require})
 * @return {any}
 */
function include (id) {
	if (typeof id !== 'string') {
		return id;
	}

	try {
		// This is so we can use '/' as separator in our code, but then run it on Windows too.
		id = id.replace('/', path.sep);

		if (id.indexOf(path.sep) < 0 || path.isAbsolute(id)) {
			return require(id); // eslint-disable-line global-require
		}

		var p = createId(include);
		return require(path.resolve(path.dirname(p), id)); // eslint-disable-line global-require
	}
	catch (e) {
		if (e.code !== 'MODULE_NOT_FOUND') {
			console.error(e);
		}
		return null;
	}
}