1.0.5 • Published 4 years ago

serve-markdown-it-lib v1.0.5

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

serve-markdown-it-lib

NPM Version Build Status Downloads Stats

Shared utility library for sermit

Installation

npm badge

yarn add serve-markdown-it-lib

Developing

yarn gen-readme // update README.md
yarn docs // update DOCUMENTATION.md
yarn test // lint & mocha
yarn update-deps // bump all deps

Release History

See CHANGELOG.md for more information.

License

Distributed under the MIT license. See LICENSE.md for more information.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

API Reference

The standalone JSDoc reference can be found in DOCUMENTATION.md

Modules

Classes

Functions

Typedefs

serve-markdown-it-lib

Shared utility library for the serve-markdown-it utility and supported templates, plugins, and other extensions. Provides general utilities (@see requireDynamicModule), and methods to render template (@see serve-markdown-it-template-default) assets and SCSS stylesheets.

See: serve-markdown-it
License: MIT

PathDoesNotExistError ⇐ Error

Error thrown when a path does not exist.

Kind: global class
Extends: Error
Todo

  • colorize stack trace if color enabled.

new PathDoesNotExistError(path, fsError, color, message, stack)

Create a new PathDoesNotExistError object.

ParamTypeDescription
pathstringpath that does not exist.
fsErrorstring | Errororiginal native error or native message.
colorbooleanenables colorized message.
messagestringerror message override
stackArray.<string>stack trace override

Example

const err = new PathDoesNotExistError('/some/path')

console.log(`non-existent path: ${err.path}`)
console.log(`non-existent path parts: ${err.parts}`)
console.log(`non-existent path dir name: ${err.dirname}`)
console.log(`non-existent path base name: ${err.basename}`)
console.log(`non-existent path extension: ${err.extname}`)

console.error(err.stack)

pathDoesNotExistError.path ⇒ string

Get the non-existent path.

Kind: instance property of PathDoesNotExistError
Returns: string - path - path supplied to error.

pathDoesNotExistError.parts ⇒ Array.<string>

Get the non-existent path parts.

Kind: instance property of PathDoesNotExistError
Returns: Array.<string> - pathParts - path split by system path seperator.

pathDoesNotExistError.color ⇒ boolean

Get the color setting.

Kind: instance property of PathDoesNotExistError
Returns: boolean - color - indicates if the error message will be colorized

pathDoesNotExistError.fsError ⇒ Error

Get the original FS error object.

Kind: instance property of PathDoesNotExistError
Returns: Error - fsError

PathDoesNotExistError.message(path, fsError, color) ⇒ string

Generate a messsage for PathDoesNotExistError.

Kind: static method of PathDoesNotExistError
Returns: string - message - error message

ParamTypeDefaultDescription
pathstringpath that does not exist.
fsErrorstring | Errororiginal native error or native message.
colorbooleantruecolorizes message.

Example

const message = PathDoesNotExistError.genMessage('/some/path')

console.log(message)

renderAssets(params) ⇒ Promise

Renders a map of { [dest]: src } path pairs representing static assets, either files or folders.

Kind: global function
Returns: Promise - p

ParamTypeDescription
paramsobjectparams.
params.assetsobjectasset dest paths key'ed by src path. Source paths starting with ~ are assumed module paths, and loaded via requireDynamicModule.
params.srcPathstringabsolute path to asset src folder.
params.buildPathstringabsolute path to asset build folder.
params.requirePathstringpath to directory containing node_modules; used to resolve module assets, not passed to require.resolve!
params.quietbooleanif false, progress is logged to the. console.
params.drybooleanif true, progress is logged but not files are modified.

Example (rendering assets to `public/`)

renderAssets({
  dry: true,
  quiet: false,
  requirePath: path.join(__dirname, '../'),
  buildPath: path.join(__dirname, '../public'),
  srcPath: path.join(__dirname, '../res/assets'),
  assets: {
    fonts: 'fonts', // asset folder
    'css/highlightjs': '~highlight.js/styles' // module folder
  }
})

renderStyles(params) ⇒ Promise

Renders a map of { [dest]: src } path pairs representing SCSS stylesheets.

Kind: global function
Returns: Promise - p - resolves to array of rendered CSS stylesheets

ParamTypeDescription
paramsobjectparams.
params.stylesobjectscss stylesheet dest paths key'ed by src path.
params.includePathsArray.<string>array of absolute include paths to resolve @import statements.
params.srcPathstringabsolute path to scss src folder.
params.buildPathstringabsolute path to scss build folder.
params.quietbooleanif false, progress is logged to the. console.
params.drybooleanif true, progress is logged but not files are modified.

Example (rendering styles to `public/css`)

renderStyles({
  dry: true,
  quiet: false,
  requirePath: path.join(__dirname, '../'),
  buildPath: path.join(__dirname, '../public/css'),
  srcPath: path.join(__dirname, '../res/styles'),
  styles: {
   'index.css': 'index.scss'
  }
})

explodePath(params) ⇒ Array.<strings>

Generates an array of paths from '/' up to the provided path.

Kind: global function
Returns: Array.<strings> - paths

ParamTypeDefaultDescription
paramsobjectparams
params.fromPathstringpath to explode.
params.directorybooleanindicates basePath is a directory; if not provided, the path is checked to resolve directory/file.
params.prefixstring"''"prefix for all generated paths.
params.suffixstring"''"suffix for all generated paths.
params.pathsArray.<Array>[]target array to append generated paths too

Example

await explodePath(__dirname, { prefix: '/', suffix: 'node_modules' })
const module = require.resolve(moduleName, { paths: searchPaths })

fsStat(path, returnError) ⇒ Promise

Safe wrapper for fs.stat with returns null or Error on failure instead of throwing.

Kind: global function
Returns: Promise - p - resolves to Stats, null, or Error object on failure.

ParamTypeDefaultDescription
pathstringpath to pass to fs.stat
returnErrorbooleanfalseif true, Error object is returned on failure instead of null.

Example

const _isNull = require('lodash/isNull')
const _isError = require('lodash/isError')

info = await statPath('/some/path')

if (_isNull(info)) {
  console.log('path does not exist')
} else {
  console.log('path stats: ', JSON.stringify(info))
}

info = await statPath('/some/path', true)

if (_isError(info)) {
  console.error(info.stack)
} else {
  console.log('path stats: ', JSON.stringify(info))
}

getGitIgnore(config) ⇒ ignore

Attempts to load any .gitignore file in the configured content root and returns a configured instance of ignore.

Kind: global function
Returns: ignore - ignore

ParamTypeDescription
configConfigconfiguration data, with basePath set.

Example (load `.gitignore` and filter paths)

const nodes = {}
const ig = await getGitIgnore(config)
const allNodes = await fs.readdir(srcPath, { withFileTypes: true })

allNodes
  .filter(n => n.isFile() || n.isDirectory())
  .forEach((n) => { nodes[n.name] = n })

const visibleNodes = excludeGitIgnore
  ? ig.filter(_keys(nodes)).map(n => nodes[n])
  : _keys(nodes).map(n => nodes[n])

// do something with visibleNodes array...

getLogger(scope) ⇒ Signale

Creates a new scoped signale logger instance.

Kind: global function
Returns: Signale - l

ParamTypeDescription
scopestringscope

Example

const l = getLogger('template:render-md')

getRelativePath(absPath, config) ⇒ string

Converts the provided absolute path to a path relative to the configured content root, with a / prefix for linking in rendered HTML.

Kind: global function
Returns: string - relPath

ParamTypeDescription
absPathstringabsolute path
configConfigconfig

Example

const { state } = config
const { template } = state
const { genRawSrcMarkdown } = template
const relPath = getRelativePath('/home/user/markdown-it/README.md', config)

await genRawSrcMarkdown({ relPath, ...genData })

logModuleResolved(moduleName, modulePath, params)

Logs successful module resolution.

Kind: global function

ParamTypeDefaultDescription
moduleNamestringname of module.
modulePathstringpath to module.
paramsobject{}optional params
params.loggerSignalesignale logger instance, defaults to plain unscoped logger.
params.lTypestring"'debug'"signale logger type to use.
params.loadedbooleanindicates if module was loaded or only the path was resolved.
params.colorbooleanenables colorized output.

Example (log module resolution)

logModuleResolved('serve-markdown-it', process.cwd(), { color: false })

resolveGlobal(moduleName, params) ⇒ string | null

Safe wrapper around external:resolve-global that returns null on failure instead of throwing.

Kind: global function
Returns: string | null - globalModulePath

ParamTypeDescription
moduleNamestringmodule to resolve globally.
paramsobjectoptional params
params.prefixstringresolved path prefix
params.suffixstringresolved path suffix

Example

const modulePath = resolveGlobal('serve-markdown-it')

requireModule(moduleName, config, load) ⇒ object | function | string

Attempts to resolve a module by name from the configured basePath, searching every directory up from it, along with the local node_modules folder. Call with load false to get the module path.

If the module cannot be resolved by walking the path, an attempt is made to load it from the global module path.

Kind: global function
Returns: object | function | string - module
Throws:

  • Error fails if the module is not resolved.
ParamTypeDefaultDescription
moduleNamestringname of module passed to require.resolve.
configConfigconfiguration, with basePath set.
loadbooleantrueif false, the resolved module path is returned instead of the loaded module.

Example (load `markdown-it` anchor plugin)

const parserPlugin = requireModule('markdown-it-anchor', config)

resolveModule(moduleName, paths) ⇒ null | string

Safe wrapper around require.resolve that retuns null on failure instead of throwing an error.

Kind: global function
Returns: null | string - modulePath - null on failure.

ParamTypeDefaultDescription
moduleNamestringname of module to resolve path to.
pathsnull | Array.<string>[]paths to attempt resolve from; passed through _uniq.

Example (resolve from cwd)

const modulePath = resolveModule('serve-markdown-it-lib', [process.cwd()])

if (_isEmpty(modulePath)) {
  return
}

const module = require(modulePath)

readAsset(config, assetPath) ⇒ AssetData

Attempts to read a template asset from disk.

Kind: global function
Returns: AssetData - data

ParamTypeDescription
configConfigconfiguration, with basePath set.
assetPathstringrelative to template public folder.

Example (read and serve template asset)

const serveAsset = async (ctx, url, config) => {
  try {
    const { type, src } = await readAsset(config, url)

    ctx.body = src
    ctx.type = type
    ctx.renderType = 'asset'

    return true
  } catch (e) {
    return false
  }
}

AssetData : object

Kind: global typedef
Properties

NameTypeDescription
srcBufferasset contents
typestringmime type, defaults to 'text/plain' if not resolved.