Bajo

The Core. The main engine. The one and only plugin that control app's boot process and making sure all other plugins working smoothly.

Constructor

new Bajo(app, app)

Parameters:
NameTypeDescription
appObject
appObject

App instance reference. Usefull to call app method inside a plugin

Members

applets :Array

Storage for applets

Type:
  • Array

config :Object

Config object. See Config Object for details

Type:
  • Object

configHandlers :Array

Storage for config handlers. By default there are only two handlers available: .js and .json.

Use plugin to add more type - e.g: bajo-config lets you to use .yaml and .toml

Type:
  • Array

pluginPkgs :Array

List of all loaded plugin's package names

Type:
  • Array

runAt :Date

Date/time when your app start

Type:
  • Date

(static, constant) mainNs :string

Your main namespace. And yes, you suppose to NOT CHANGE this

Type:
  • string
Default Value
  • 'main'

Methods

breakNsPath(name, checkNsopt) → {TNsPath}

Break name to its namespace & path infos

Parameters:
NameTypeAttributesDefaultDescription
namestring

Name to break

checkNsboolean<optional>
true

If true (default), namespace will be checked for its validity

Returns:
Type: 
TNsPath

(async) buildCollections(options) → {Array}

Method to transform an array or object from config into an array of collection safely.

Emitted hooks:

  1. {ns}:beforeBuildCollection (container) - called before collection is built
  2. {ns}:afterBuildCollection (container, items) - called after collection is built
Parameters:
NameTypeDescription
optionsObject

Options

Properties
NameTypeAttributesDefaultDescription
nsstring<optional>

Namespace. If not provided, defaults to bajo

handlerfunction<optional>

Handler to call while building the collection item

dupChecksArray<optional>
[]

Array of keys to check for duplicates

containerstring

Key used as container name

useDefaultNameboolean<optional>
true

If true (default) and name key is not provided, returned collection will be named default

Returns:

The collection

Type: 
Array

(async) callHandler(name, …argsopt) → {any}

Calling any plugin's method by its name. Name format: ns:methodName.

  • If name is a string, the corresponding plugin's method will be called with passed args as its parameters
  • If name is a plugin instance, this will be used as the scope instead. The first args is now the handler name and the rest are its parameters
  • If name is a function, this function will be run under scope with the remaining args
  • If name is an object and has handler key in it, this function handler will be instead
Parameters:
NameTypeAttributesDescription
namestring | Object | function

Method's name, function handler, plain object or plugin instance

argsany<optional>
<repeatable>

One or more arguments passed as parameter to the handler

Returns:

Returned value

Type: 
any

(async) eachPlugins(handler, optionsopt) → {any}

This function iterates through all loaded plugins and call the provided handler scoped as the running plugin. And an object with the following key serves as its parameter:

  • file: file matched the glob pattern
  • dir: plugin's base directory
Parameters:
NameTypeAttributesDefaultDescription
handlerfunction

Function handler. Can be an async function. Scoped to the running plugin

optionsstring | Object<optional>
{}

Options. If a string is provided, it serves as the glob pattern, otherwise:

Properties
NameTypeAttributesDefaultDescription
globstring | Array<optional>

Glob pattern. If provided,

useBajoboolean<optional>
false

If true, add bajo to the running plugins too

prefixstring<optional>
''

Prepend glob pattern with prefix

noUnderscoreboolean<optional>
true

If true (default), matched file with name starts with underscore is ignored

returnItemsany<optional>

If true, each value of returned handler call will be saved as an object with running plugin name as its keys

Returns:
Type: 
any

findDeep(item, paths) → {string}

Find item deep in paths

Parameters:
NameTypeDescription
itemstring

Item to find

pathsArray

Array of path to look for

Returns:
Type: 
string

format(value, typeopt, optionsopt) → {string}

Format value

Parameters:
NameTypeAttributesDefaultDescription
valueany

Value to format

typestring<optional>

Data type to use. See TData for acceptable values. If not provided, return the untouched value

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
emptyValuestring<optional>
''

Empty value to use if function resulted empty. Defaults to the one from your config

withUnitboolean<optional>
true

Return with its unit appended

langstring<optional>

Format value according to this language. Defaults to the one you set in config

latitudestring<optional>

If Bajo Spatial is loaded and data type is a double or float, then format it as latitude in degree, minute, second

longitudestring<optional>

If Bajo Spatial is loaded and data type is a double or float, then format it as longitude in degree, minute, second

Returns:

Formatted value

Type: 
string

formatByType(type, value, dataTypeopt, optionsopt) → {Array|string}

Format value by type

Parameters:
NameTypeAttributesDefaultDescription
typestring

Format type. See TFormat for acceptable values

valueany

Value to format

dataTypestring<optional>

Value's data type. See TData for acceptable values

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
withUnitboolean<optional>
true

Return with its unit appended

langstring<optional>

Format value according to this language. Defaults to the one you set in config

Returns:

Return string if withUnit is true. Otherwise is an array of [value, unit, separator]

Type: 
Array | string

freeze(obj, shallowopt)

Freeze object

Parameters:
NameTypeAttributesDefaultDescription
objObject

Object

shallowboolean<optional>
false

If true (default), deep freeze object

generateId(optionsopt) → {string|Object}

Generate unique random characters that can be used as ID. Use nanoid under the hood

Parameters:
NameTypeAttributesDefaultDescription
optionsboolean | string | Object<optional>
{}

Options. If set to true or alpha, it will generate alphaphet only characters. If set to int, it will generate integer only characters. Otherwise:

Properties
NameTypeAttributesDefaultDescription
patternstring<optional>

Character pattern to use. Defaults to all available alphanumeric characters

lengthnumber<optional>
13

Length of resulted characters

casestring<optional>

If set to lower to use lower cased pattern only. For upper cased pattern, set it to upper

returnInstanceboolean<optional>

Set to true to return nanoid instance instead of string

Returns:

Return string or instance of nanoid

Type: 
string | Object

getGlobalModuleDir(pkgNameopt, silentopt) → {string}

Get NPM global module directory

Parameters:
NameTypeAttributesDefaultDescription
pkgNamestring<optional>

If provided, return this package global directory. Otherwise the npm global module directory

silentboolean<optional>
true

Set to false to throw exception in case of error. Otherwise silently returns undefined

Returns:
Type: 
string

getMethod(name, thrownopt) → {function}

Get class method by name

Parameters:
NameTypeAttributesDefaultDescription
namestring

Name in format ns:methodName

thrownboolean<optional>
true

If true (default), throw exceptiom in case of error

Returns:

Class method

Type: 
function

getModuleDir(pkgName, base) → {string}

Get module directory, locally and globally

Parameters:
NameTypeDescription
pkgNamestring

Package name to find

base*

Provide base name if pkgName is a module under base's package name

Returns:

Return absolute package directory

Type: 
string

getPlugin(name, silentopt) → {Object}

Get plugin by name

Parameters:
NameTypeAttributesDescription
namestring

Plugin name/namespace or alias

silentboolean<optional>

If true, silently return undefined even on error

Returns:

Plugin object

Type: 
Object

getPluginDataDir(name, ensureDiropt) → {string}

Get plugin data directory

Parameters:
NameTypeAttributesDefaultDescription
namestring

Plugin name (namespace) or alias

ensureDirboolean<optional>
true

Set true (default) to ensure directory is existed

Returns:
Type: 
string

getPluginFile(file) → {string}

Resolve file path from:

  • local/absolute file
  • ns based path (myPlugin:/path/to/file.txt)
Parameters:
NameTypeDescription
filestring

File path, see above for supported types

Returns:

Resolved file path

Type: 
string

getUnitFormat(optionsopt) → {TObjectFormat}

Get unit format

Parameters:
NameTypeAttributesDefaultDescription
optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDescription
langstring<optional>

Language to use. Defaults to the one you set in config

unitSysstring<optional>

Unit system to use. Defaults to language's unit system or metric if unspecified

Returns:
  • Returned value
Type: 
TObjectFormat

(async) importModule(file, optionsopt) → {function|Object}

Import file/module from any loaded plugins

Your plugin structure:

|- src
|  |- lib
|  |  |- my-module.js
|- index.js
|- package.json

Inside your app/plugin:

const { importModule } = this.app.bajo
const myModule = await importModule('myPlugin:/src/lib/my-module.js')
Parameters:
NameTypeAttributesDefaultDescription
filestring

File in format ns:<ns based file path>

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
asDefaultImportboolean<optional>
true

If true (default), return default imported module

asHandlerboolean<optional>

If true, return as a handler

noCacheboolean<optional>

If true, always import as a fresh copy

Returns:
Type: 
function | Object

(async) importPkg(…pkgs) → {Object|Array}

Import one or more package belongs to a plugin

Example: you want to import packages delay and chalk from bajo namespace and use it inside your app/plugin

const { importPkg } from this.app.bajo
const [delay, chalk] = await importPkg('bajo:delay', 'bajo:chalk')

await delay(1000)
...
Parameters:
NameTypeAttributesDescription
pkgsany<repeatable>

One or more packages in format ns:packageName

Returns:

Depends on how many parameters are provided, it should return the named package or an array of packages

Type: 
Object | Array

(async) isEmptyDir(dir, filterFn) → {boolean}

Check whether directory is empty or not. More info please check here.

Parameters:
NameTypeDescription
dirstring

Directory to check. Can be a ns based directory too!

filterFnfunction

Filter function to filter out files that cause false positives.

Returns:
Type: 
boolean

isLogInRange(level) → {boolean}

Check whether log level is within log's app current level

Parameters:
NameTypeDescription
levelstring

Level to check. See TLogLevels for more

Returns:
Type: 
boolean

isValidApp(dir, returnPkgopt) → {boolean|Object}

Check whether directory is a valid Bajo app

Parameters:
NameTypeAttributesDescription
dirstring

Directory to check

returnPkgboolean<optional>

Set true to return its package.json content

Returns:
Type: 
boolean | Object

isValidPlugin(dir, returnPkgopt) → {boolean|Object}

Check whether directory is a valid Bajo plugin

Parameters:
NameTypeAttributesDescription
dirstring

Directory to check

returnPkgboolean<optional>

Set true to return its package.json content

Returns:
Type: 
boolean | Object

numUnit(valueopt, defUnitopt) → {string}

Return its numeric portion of a value

Parameters:
NameTypeAttributesDefaultDescription
valuestring<optional>
''

Value to get its numeric portion

defUnitstring<optional>
''

Default unit if value doesn't have one

Returns:
Type: 
string

parseDt(dt) → {Object}

Parse datetime string as Javascript object. Please visit dayjs for valid formats and more infos

Parameters:
NameTypeDescription
dtstring

Datetime string

Returns:

Javascript object

Type: 
Object

parseDur(dur) → {number}

Parse duration to its millisecond value. Use ms under the hood

Parameters:
NameTypeDescription
durnumber | string

If string is given, parse this to its millisecond value. Otherwise return as is

Returns:
Type: 
number

parseObject(input, optionsopt) → {Object}

Parse an object and optionally normalize its values recursively. Use https://github.com/ladjs/dotenv-parse-variables to parse values, so please have a visit to know how it works

If options.parseValue is true, any key ends with Dur and Dt will also be parsed as millisecond and Javascript datetime accordingly

Parameters:
NameTypeAttributesDefaultDescription
inputObject | string

If string is given, parse it first using JSON.parse

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
silentboolean<optional>
true

If true (default), exception are not thrown and silently ignored

parseValueboolean<optional>
false

If true, values will be parsed & normalized

langstring<optional>

If provided, use this language instead of the one in config

Returns:
Type: 
Object

(async) readConfig(file, optionsopt) → {Object}

Read and parse file as config object. Supported types: .js and .json. More supports can be added using plugin. bajo-config gives you additional supports for .yml, .yaml and .toml file

If file extension is .*, it will be auto detected and parsed accordingly

Parameters:
NameTypeAttributesDefaultDescription
filestring

File to read and parse

optionsObject<optional>
{}

Options

Properties
NameTypeAttributesDefaultDescription
ignoreErrorboolean<optional>

Any exception will be silently discarded

nsstring<optional>

If given, use this as the scope

patternstring<optional>

If given and auto detection is on (extension is .*), it will be used for instead the default one

globOptionsObject<optional>
{}

fast-glob options

defValueObject<optional>
{}

Default value to use if value returned empty

optsObject<optional>
{}

Parser setting

Returns:
Type: 
Object

readJson(file, thrownNotFoundopt) → {Object}

Read and parse json file

Parameters:
NameTypeAttributesDefaultDescription
filestring

File to read

thrownNotFoundboolean<optional>
false

If true, silently ignore if file is not found

Returns:
Type: 
Object

resolvePath(file, asFileUrlopt) → {string}

Resolve file name to filesystem's path. Windows path separator \ is normalized to Unix's /

Parameters:
NameTypeAttributesDefaultDescription
filestring

File to resolve

asFileUrlboolean<optional>
false

Return as file URL format file:///<name>

Returns:
Type: 
string

(async) runHook(hookName, …argsopt) → {Array}

Run named hook

Parameters:
NameTypeAttributesDescription
hookNamestring

ns based hook name

argsany<optional>
<repeatable>

Argument passed to the hook function

Returns:

Array of hook execution results

Type: 
Array

(async) saveAsDownload(file, item, printSavedopt) → {string}

Save item as file in Bajo's download directory. That is a directory inside your Bajo plugin's data directory.

If file exists already, file will automatically be renamed incrementally.

Parameters:
NameTypeAttributesDefaultDescription
filestring

File name

itemObject

Item to save

printSavedboolean<optional>
true

Print info on screen

Returns:

Full file path

Type: 
string