@open-xchange/rolldown-utils
v1.4.0
Published
A collection of implementation helpers for Rolldown plugins
Maintainers
Keywords
Readme
@open-xchange/rolldown-utils
A collection of implementation helpers for Rolldown plugins.
Installation
npm install -D @open-xchange/rolldown-utils
# or
pnpm add -D @open-xchange/rolldown-utils
# or
yarn add -D @open-xchange/rolldown-utilsUsage
The package re-exports everything from @rolldown/pluginutils (e.g. createFilter, exactRegex, prefixRegex), and adds the helpers described below.
import { Cache, createJsonModule, onceFn } from '@open-xchange/rolldown-utils'Source Modules
Function joinLines
Joins an array of strings with newline characters, and ensures that the result ends with a newline character. A single string is returned unchanged, except for the trailing newline.
joinLines(['const a = 1', 'export default a']) // 'const a = 1\nexport default a\n'
joinLines('export default 42') // 'export default 42\n'
joinLines('export default 42\n') // 'export default 42\n' (unchanged)Function createJsonModule
Creates the source code of an ES module with a default export containing the passed JSON data. Returns a Rolldown SourceDescription with an empty source map, ready to be returned from the plugin hook load.
createJsonModule({ id: 'app', version: '1.2.3' })
// { code: 'export default {"id":"app","version":"1.2.3"};\n', map: { mappings: '' } }Example how to use it in a plugin:
load(id) {
if (id === RESOLVED_VIRTUAL_ID) return createJsonModule(metadata)
}Class Cache
A subclass of the native Map with string keys, and two additional methods for generating entries on demand.
Method update
Sets the value of an entry to the result of the passed update function. The function receives the current value (or undefined for a missing entry) and the key, and returns the new value. Returns the new value.
const counters = new Cache<number>()
counters.update('a', value => (value ?? 0) + 1) // 1
counters.update('a', value => (value ?? 0) + 1) // 2Method upsert
Returns the value of an existing entry. For a missing entry, calls the passed generator function with the key, stores the result, and returns it. The generator function will not be called for existing entries.
const buffers = new Cache<Promise<Buffer>>()
// reads the file once, subsequent calls with the same path return the cached promise
const buffer = await buffers.upsert(path, async () => await readFile(path))File System
Function globFiles
Finds all files matching one or more glob patterns with the native glob function of NodeJS, and returns their absolute paths with forward slashes, sorted alphabetically. Patterns starting with ! exclude matching files and directories. Relative patterns are resolved against the option cwd (default: working directory of the process).
await globFiles('src/**/*.svg', { cwd: config.root })
await globFiles(['src/**/*.ts', '!**/*.test.ts'])Unlike glob packages such as tinyglobby, a pattern matching a directory does not include the files in that directory, symbolic links are not followed, and matching is case-insensitive on Windows and macOS. Like these packages, files and directories starting with a dot are skipped unless the pattern contains the dot.
Arrays and Strings
Function wrapArray
Returns an array as passed, and wraps all other values into a one-element array. Useful for options that accept a single value or an array of values.
wrapArray('a.js') // ['a.js']
wrapArray(['a.js', 'b.js']) // ['a.js', 'b.js'] (same array instance)Function removePrefix
Removes a specific prefix from the beginning of a string. Returns the string unchanged if it does not start with the prefix.
removePrefix('virtual:icons.svg', 'virtual:') // 'icons.svg'
removePrefix('icons.svg', 'virtual:') // 'icons.svg'Function removeSuffix
Removes a specific suffix from the end of a string. Returns the string unchanged if it does not end with the suffix.
removeSuffix('icons.svg?used', '?used') // 'icons.svg'
removeSuffix('icons.svg', '?used') // 'icons.svg'Function getRemainder
Returns the remainder of a string following a specific prefix, or undefined if the string does not start with the prefix. Unlike removePrefix, this makes it possible to detect whether the prefix was present at all.
getRemainder('virtual:icons.svg', 'virtual:') // 'icons.svg'
getRemainder('icons.svg', 'virtual:') // undefinedFunction getHash
Generates a hexadecimal MD5 hash for a string or a Buffer, e.g. for cache keys or content hashes in file names. The optional second parameter truncates the hash to the specified number of characters.
getHash('test') // '098f6bcd4621d373cade4e832627b4f6'
getHash('test', 8) // '098f6bcd'Functions
Function onceFn
Wraps a function so that it is invoked at most once. The first call stores the result, whether a return value or a thrown exception, and all subsequent calls return the stored value or throw the stored exception again. Useful for expensive initializations shared between several plugin hooks.
const readMapping = onceFn(() => parseMappingFile(path))
readMapping() // parses the file
readMapping() // returns the cached result