Skip to content

Helpers ​

Introduction ​

@plinthjs/support is the foundation package that every other Plinth package builds on. Besides collections, it contains the small utilities you reach for constantly: array and string helpers, number formatting, a pipeline, dot-path accessors, a message bag for errors, a URI builder, deterministic sleeping, timing, identifiers and a handful of mixins. You can use all of it in your own code.

bash
pnpm add @plinthjs/support

Everything is a named export from the package root:

ts
import { Arr, Num, Str, collect, dataGet, pipeline } from '@plinthjs/support'

Value helpers ​

Dot-path access ​

dataGet() reads a nested value from objects, arrays and maps using a dot path, and returns a default when the path is missing. A * segment fans out over every item of an array.

ts
import { dataGet, dataSet } from '@plinthjs/support'

const data = { users: [{ name: 'a' }, { name: 'b' }] }

dataGet(data, 'users.0.name') // => 'a'
dataGet(data, 'users.*.name') // => ['a', 'b']
dataGet(data, 'users.5.name', 'unknown') // => 'unknown'
dataGet({}, 'a.b', () => 'computed default') // a function default is called lazily

dataSet() writes a value at a dot path, creating the intermediate objects. The last argument controls whether an existing value is overwritten (it is by default).

ts
const target: Record<string, unknown> = {}

dataSet(target, 'a.b', 1)
dataSet(target, 'a.b', 2, false) // do not overwrite
target // => { a: { b: 1 } }

A * segment fans out: dataSet(data, 'users.*.active', true) sets active on every item of users (items that are not objects are skipped, and with overwrite = false existing values are kept). With nothing to fan over it does nothing; it never creates a literal * key.

value, tap and uniqueId ​

value() returns its argument, or calls it first if it is a function. It is how options such as "a value or a function that returns one" are resolved.

ts
import { tap, uniqueId, value } from '@plinthjs/support'

value(5) // => 5
value(() => 6) // => 6
value((n: number) => n + 1, 1) // => 2   (extra arguments are passed to the function)

tap<Record<string, number>>({ a: 1 }, (o) => {
  o['b'] = 2
}) // => { a: 1, b: 2 }   (runs the callback, returns the original)

uniqueId('row_') // => 'row_1'
uniqueId() // => '2'   (a process-wide counter, not a UUID)

blank and filled ​

blank() is true for null, undefined, whitespace-only strings, empty arrays, empty maps and sets, and empty plain objects. Numbers, including 0, and booleans, including false, are never blank. filled() is the opposite.

ts
import { blank, filled, whenBlank } from '@plinthjs/support'

blank('') // => true
blank('  ') // => true
blank([]) // => true
blank({}) // => true
blank(0) // => false
blank(false) // => false
filled('x') // => true

whenBlank('', 'fallback') // => 'fallback'
whenBlank('x', 'fallback') // => 'x'

Arrays ​

Arr is a set of functions for plain arrays and objects. Most mirror a collection method but return plain values, which is convenient in code that does not need a chain.

ts
import { Arr } from '@plinthjs/support'

Arr.wrap(1) // => [1]
Arr.wrap([1]) // => [1]
Arr.wrap(null) // => []

Arr.first([1, 2, 3], (n) => n > 1) // => 2
Arr.last([1, 2, 3]) // => 3
Arr.flatten([1, [2, [3]]], 1) // => [1, 2, [3]]
Arr.collapse([[1], [2]]) // => [1, 2]
Arr.chunk([1, 2, 3], 2) // => [[1, 2], [3]]
Arr.where([1, 2, 3], (n) => n > 1) // => [2, 3]
Arr.whereNotNull([1, null, 2]) // => [1, 2]
Arr.unique([{ id: 1 }, { id: 1 }], 'id') // => [{ id: 1 }]

Pick or omit keys from an object, and reshape lists of objects:

ts
Arr.only({ a: 1, b: 2, c: 3 }, ['a', 'c']) // => { a: 1, c: 3 }
Arr.except({ a: 1, b: 2 }, ['a']) // => { b: 2 }

const rows = [
  { k: 'x', a: 1 },
  { k: 'y', a: 2 },
]
Arr.pluck(rows, 'a') // => [1, 2]
Arr.pluck(rows, 'a', 'k') // => { x: 1, y: 2 }
Arr.keyBy(rows, 'k') // => { x: { k: 'x', a: 1 }, y: { k: 'y', a: 2 } }
Arr.groupBy(rows, 'k') // => { x: [...], y: [...] }

Arr.get(), Arr.set() and Arr.has() work with dot paths. Arr.accessible() tells you whether a value can be indexed like an array or object, and Arr.shuffle() returns a shuffled copy and takes an optional random function.

ts
Arr.get({ a: { b: [{ c: 1 }] } }, 'a.b.0.c') // => 1
Arr.get({}, 'x.y', 'default') // => 'default'
Arr.has({ a: { b: 1 } }, 'a.b') // => true

const target = {}
Arr.set(target, 'a.b.c', 1) // target => { a: { b: { c: 1 } } }

Strings ​

Str holds string functions. Each takes the string as the first argument, except the replace functions, which put the subject last.

Case and naming ​

ts
import { Str } from '@plinthjs/support'

Str.camel('foo_bar baz') // => 'fooBarBaz'
Str.studly('foo-bar') // => 'FooBar'
Str.snake('fooBar') // => 'foo_bar'
Str.kebab('fooBar') // => 'foo-bar'
Str.title('hello world') // => 'Hello World'
Str.headline('hello_world-foo') // => 'Hello World Foo'
Str.ucfirst('abc') // => 'Abc'
Str.lcfirst('Abc') // => 'abc'
Str.slug('Hello World!') // => 'hello-world'
Str.slug('A B', '_') // => 'a_b'

Pluralizing ​

plural() and singular() use simple English rules plus a table of irregular and uncountable words. They handle regular endings such as category to categories; the table covers child/children, person/people, man/men, woman/women, tooth/teeth, foot/feet, mouse/mice, goose/geese and ox/oxen (compounds such as grandchild follow), and leaves sheep, fish, series, species, news, data, equipment, information, rice and money unchanged. It is not a full inflector, so check other irregular words you depend on.

ts
Str.plural('category') // => 'categories'
Str.plural('apple', 1) // => 'apple'   (a count of 1 keeps the singular)
Str.singular('apples') // => 'apple'
Str.pluralStudly('UserProfile', 2) // => 'UserProfiles'

Searching and slicing ​

ts
Str.contains('hello', 'ell') // => true
Str.contains('hello', ['x', 'ell']) // => true   (any of)
Str.containsAll('hello', ['h', 'z']) // => false
Str.startsWith('hello', ['he', 'x']) // => true
Str.endsWith('hello', 'lo') // => true

Str.before('a@b.c', '@') // => 'a'
Str.after('a@b.c', '@') // => 'b.c'
Str.beforeLast('a.b.c', '.') // => 'a.b'
Str.afterLast('a.b.c', '.') // => 'c'
Str.between('[x]', '[', ']') // => 'x'

Str.substr('hello', 1, 3) // => 'ell'
Str.take('hello', 2) // => 'he'
Str.charAt('abc', 1) // => 'b'
Str.position('abc', 'c') // => 2   (false when not found)
Str.substrCount('aXaXa', 'X') // => 2
Str.wordCount('a b c') // => 3

Changing and trimming ​

ts
Str.limit('The quick brown fox', 10) // => 'The quick...'
Str.limit('The quick brown fox', 10, ' (more)') // => 'The quick (more)'
Str.words('one two three four', 2) // => 'one two...'
Str.start('path', '/') // => '/path'   (adds the prefix only if missing)
Str.finish('dir', '/') // => 'dir/'
Str.wrap('a', '"') // => '"a"'
Str.unwrap('"a"', '"') // => 'a'
Str.padLeft('5', 3, '0') // => '005'
Str.padRight('5', 3, '-') // => '5--'
Str.squish('  a   b ') // => 'a b'
Str.trim('--a--', '-') // => 'a'
Str.deduplicate('a//b///c', '/') // => 'a/b/c'
Str.remove('l', 'hello') // => 'heo'
Str.chopStart('prefix-x', 'prefix-') // => 'x'
Str.chopEnd('x.ts', '.ts') // => 'x'
Str.reverse('abc') // => 'cba'
Str.wordWrap('The quick brown fox', 10, '\n') // => 'The quick\nbrown fox'
Str.ascii('Café') // => 'Cafe'
Str.numbers('a1b2') // => '12'

mask() hides part of a string, which is useful for showing an email or a card number safely. A negative index counts from the end.

ts
Str.mask('anil@example.com', '*', 3) // => 'ani*************'
Str.mask('1234567890', '*', -4) // => '123456****'
Str.mask('1234567890', '*', 2, 3) // => '12***67890'

Replacing ​

The replace functions take the search and replacement first and the subject last.

ts
Str.replaceFirst('a', 'b', 'aaa') // => 'baa'
Str.replaceLast('a', 'b', 'aaa') // => 'aab'
Str.replaceArray('?', ['1', '2'], 'a ? b ?') // => 'a 1 b 2'
Str.swap({ a: 'x', b: 'y' }, 'a b') // => 'x y'
Str.substrReplace('Hello', ' World', 5, 0) // => 'Hello World'

Matching and checking ​

ts
Str.is('foo*', 'foobar') // => true   (a wildcard pattern)
Str.isMatch(/^a/, 'abc') // => true
Str.match(/\d+/, 'ab12') // => '12'
Str.matchAll(/\d/g, 'a1b2') // => ['1', '2']
Str.isAscii('abc') // => true
Str.isJson('{"a":1}') // => true
Str.isUrl('https://x.com') // => true
Str.random(8) // a random 8 character string

Fluent strings ​

Str.of() starts a chain. Each step returns a Stringable, and .value (or toString()) gives you the string back.

ts
Str.of('  Hello World  ').trim().slug().append('-x').prepend('p-').upper().value
// => 'P-HELLO-WORLD-X'

Str.of('abcdefghij').limit(5).toString() // => 'abcde...'
Str.of('abc').contains('b') // => true
Str.of('').isEmpty() // => true
`${Str.of('x')}` // => 'x'

when(condition, callback) applies a step conditionally, and pipe(callback) hands the Stringable to a function and returns its result.

ts
Str.of('a').when(true, (s) => s.upper()).value // => 'A'
Str.of('abc').pipe((s) => s.value.length) // => 3

The chain has fluent versions of nearly every Str function: the case converters, limit, before, after, start, finish, replace, trim, ltrim, rtrim, substr, take, wrapWith, unwrap, squish, deduplicate, swap, ascii, numbers and more, plus the checks contains, isMatch, isAscii, isJson, isUrl, wordCount and position that end the chain with a plain value.

Identifiers ​

ts
import { isUlid, isUuid, orderedUuid, ulid, uuid } from '@plinthjs/support'

uuid() // a random UUID v4
orderedUuid() // a UUID v7: sorts by creation time
ulid() // a 26 character, time-sortable id

isUuid(uuid()) // => true
isUlid(ulid()) // => true
isUuid('nope') // => false

Str.uuid(), Str.orderedUuid(), Str.ulid(), Str.isUuid() and Str.isUlid() are the same functions under Str. orderedUuid() and ulid() generated in the same millisecond still increase, so they are safe as sortable primary keys.

Numbers ​

Num formats numbers with Intl, so the locale argument takes a BCP 47 tag such as 'de-DE'.

ts
import { Num } from '@plinthjs/support'

Num.format(1234567.891) // => '1,234,567.891'
Num.format(1234.5, { maximumFractionDigits: 0 }) // => '1,235'
Num.currency(12.5) // => '$12.50'
Num.currency(12.5, 'EUR', 'de-DE') // => '12,50 €'
Num.percentage(12.345, 1) // => '12.3%'
Num.ordinal(23) // => '23rd'
Num.ordinal(11) // => '11th'
Num.fileSize(1024 * 1024 * 5) // => '5 MB'
Num.abbreviate(1_250_000) // => '1.3M'
Num.forHumans(1_500_000) // => '2 million'
Num.spell(42) // => 'forty-two'
Num.clamp(15, 0, 10) // => 10
Num.pairs(25, 10) // => [[0, 10], [11, 21], [22, 25]]   (ranges for batching)
Num.parseInt('1,234') // => 1234
Num.parseFloat('1,234.5') // => 1234.5

Pipelines ​

A pipeline passes a value through a list of steps. Each step receives the value and a next function, and calls next with the (possibly changed) value to continue. Steps and the destination may be async.

ts
import { pipeline } from '@plinthjs/support'

const result = await pipeline<number>()
  .send(1)
  .through([(n, next) => next(n + 1), (n, next) => next(n * 10)])
  .then((n) => `result: ${n}`)
// => 'result: 20'

A step that returns without calling next short-circuits the pipeline and its return value becomes the result. Use pipe() to add one step at a time and thenReturn() when there is no destination.

ts
await pipeline<number>()
  .send(1)
  .pipe((n) => n * 100) // stops here, never calls next
  .pipe((n, next) => next(n + 1))
  .thenReturn() // => 100

await pipeline<string>()
  .send('a')
  .pipe(async (s, next) => next(s + 'b'))
  .pipe((s, next) => next(s.toUpperCase()))
  .thenReturn() // => 'AB'

This is the same shape as the middleware chain.

Fluent attribute bags ​

Fluent holds a bag of attributes with typed getters. It is a pleasant way to read loosely typed input such as query strings or JSON bodies.

ts
import { Fluent } from '@plinthjs/support'

const input = new Fluent<unknown>({
  name: 'Ada',
  age: '36',
  admin: 'true',
  tags: ['a', 'b'],
  meta: { x: 1 },
})

input.get('name') // => 'Ada'
input.get('missing', 'default') // => 'default'
input.string('age') // => '36'
input.integer('age') // => 36
input.boolean('admin') // => true
input.array('tags') // => ['a', 'b']
input.scope('meta').all() // => { x: 1 }
input.all(['name']) // => { name: 'Ada' }
input.collect('tags').count() // => 2
input.set('k', 1).fill({ more: 2 })
input.isEmpty() // => false

Fluent.make(attributes) is a shortcut for the constructor, and a Fluent is iterable over [key, value] pairs and serialises with JSON.stringify.

Validated input ​

ValidatedInput wraps the data that survived validation and offers read helpers over it. It is what validated() style APIs hand back.

ts
import { ValidatedInput } from '@plinthjs/support'

const input = new ValidatedInput({ name: 'Ada', address: { city: 'X', zip: '1' }, age: 3 })

input.all() // the whole object
input.only(['name', 'age']) // => { name: 'Ada', age: 3 }
input.except('age') // => { name: 'Ada', address: { city: 'X', zip: '1' } }
input.except('address.zip') // dot paths work: => { name: 'Ada', address: { city: 'X' }, age: 3 }
input.has('address.city') // => true
input.missing('nope') // => true
input.keys() // => ['name', 'address', 'age']
input.input('address.city') // => 'X'
input.input('nope', 'default') // => 'default'
input.merge({ x: 1 }).all() // a new ValidatedInput with the extra key
input.collect('address').all() // => [['city', 'X'], ['zip', '1']]

See Validation for where this comes from.

Messages and errors ​

MessageBag ​

A MessageBag collects messages under keys. Validation errors are the typical use.

ts
import { MessageBag } from '@plinthjs/support'

const errors = new MessageBag({ email: ['Required', 'Invalid'] })

errors.add('name', 'Name is required').add('name', 'Name is required') // duplicates are ignored

errors.first('email') // => 'Required'
errors.get('email') // => ['Required', 'Invalid']
errors.all() // => ['Required', 'Invalid', 'Name is required']
errors.has('name') // => true
errors.has(['name', 'x']) // => false   (every key must have a message)
errors.hasAny(['x', 'name']) // => true
errors.missing('x') // => true
errors.count() // => 3
errors.keys() // => ['email', 'name']
errors.isEmpty() // => false
errors.toJSON() // => { email: [...], name: [...] }

addIf(condition, key, message) adds only when the condition is true. merge() adds the messages of another bag or plain object. forget(key) removes a key.

A format string customises how messages come out. :message stands for the message text:

ts
errors.first('name', ':message!') // => 'Name is required!'

errors.setFormat('<li>:message</li>')
errors.all() // => ['<li>Required</li>', '<li>Invalid</li>', '<li>Name is required</li>']

ViewErrorBag ​

A ViewErrorBag holds several named MessageBag instances, so a page with more than one form can keep their errors apart. Methods like first(), has() and all() read the default bag.

ts
import { MessageBag, ViewErrorBag } from '@plinthjs/support'

const bags = new ViewErrorBag()
  .put('default', new MessageBag({ email: ['bad'] }))
  .put('login', new MessageBag({ pw: ['short'] }))

bags.any() // => true
bags.first('email') // => 'bad'
bags.getBag('login').first('pw') // => 'short'
bags.hasBag('login') // => true
bags.getBag('unknown').any() // => false   (an empty bag, never undefined)

URIs ​

Uri.of() parses a URL into an immutable object. Every with method returns a new Uri, so you can derive variants safely.

ts
import { Uri } from '@plinthjs/support'

const uri = Uri.of('https://user:pw@example.com:8080/posts/1?page=2&tag=a#top')

uri.scheme() // => 'https'
uri.user() // => 'user'
uri.host() // => 'example.com'
uri.port() // => 8080
uri.path() // => 'posts/1'
uri.pathSegments().all() // => ['posts', '1']
uri.fragment() // => 'top'
uri.query().integer('page') // => 2
uri.query().has('tag') // => true

The query accessor offers all(), get(), has(), missing(), integer() and boolean(). A key that repeats (a=1&a=2) or uses the a[] form comes back as an array in all() and get(); a key that appears once stays a string.

Build new URLs by changing parts:

ts
Uri.of('https://example.com/a').withPath('/b').withQuery({ x: 1 }).withFragment('f').toString()
// => 'https://example.com/b?x=1#f'

Uri.of('https://e.com?a=1&b=2').withQuery({ a: 9 }).toString() // => 'https://e.com?a=9&b=2'   (merges)
Uri.of('https://e.com?a=1&b=2').replaceQuery({ c: 3 }).toString() // => 'https://e.com?c=3'
Uri.of('https://e.com?a=1&b=2').withoutQuery('a').toString() // => 'https://e.com?b=2'
Uri.of('/rel?x=1').withHost('h.com').withScheme('https').toString() // => 'https://h.com/rel?x=1'

Array values in withQuery() are written as y[]=a&y[]=b. Also available are withUser(), withPort(), withoutFragment(), decode(), isEmpty() and isNotEmpty(). For URL generation inside the application, see URL Generation.

Embedding data in JavaScript ​

Js.from() encodes a value as a JavaScript expression that is safe to place inside an inline script. Characters that could break out of a script block, such as <, >, & and quotes, are escaped, and undefined becomes null.

ts
import { Js } from '@plinthjs/support'

Js.from({ a: 1 }).toString() // => JSON.parse('{\u0022a\u0022:1}')   (the quotes are written as escapes)
Js.from([1, 2]).toString() // => JSON.parse('[1,2]')
Js.from('hi').toString() // => 'hi'   (including the single quotes)
Js.from(null).toString() // => null

Use the result as the right-hand side of an assignment in a server-rendered page.

Sleeping ​

Sleep waits for a duration and can be faked in tests, so code that pauses does not slow your suite down.

ts
import { Sleep } from '@plinthjs/support'

await Sleep.for(500).milliseconds()
await Sleep.for(2).seconds()
await Sleep.for(1).minute()
await Sleep.sleep(1) // seconds
await Sleep.usleep(1500) // microseconds
await Sleep.until(Date.now() + 1000) // until a timestamp or Date

Sleep.for(n) offers milliseconds(), seconds(), minutes() and microseconds(), with singular spellings. In a test, call Sleep.fake() to skip the waiting and record the requested durations, then assert on them and restore the real timer.

ts
Sleep.fake()

await Sleep.for(500).milliseconds()
await Sleep.for(2).seconds()

Sleep.assertSequence([500, 2000])
Sleep.assertSleptTimes(2)
Sleep.assertSlept((ms) => ms === 500)

Sleep.restore()

Sleep.assertNeverSlept() asserts that nothing slept at all.

Sleep.useTimer() installs a custom timer function in place of the default one.

Benchmarking ​

Benchmark.measure() runs a function and returns the average time in milliseconds. Pass a count to repeat it, or an object of named functions to compare them.

ts
import { Benchmark } from '@plinthjs/support'

await Benchmark.measure(() => work()) // => 12.4   (milliseconds)
await Benchmark.measure(() => work(), 10) // average over 10 runs
await Benchmark.measure({ loop: () => withLoop(), map: () => withMap() }, 5)
// => { loop: 3.1, map: 2.8 }

Benchmark.value() returns the function's result together with its duration:

ts
const [users, milliseconds] = await Benchmark.value(() => loadUsers())

Constant-time responses ​

Timebox guarantees that a callback takes at least a minimum time, whether it succeeds or fails. That hides timing differences, for example between "unknown user" and "wrong password". The duration is given in microseconds.

ts
import { Timebox } from '@plinthjs/support'

const user = await new Timebox().call(async () => attemptLogin(email, password), 200_000) // at least 200 ms

An exception from the callback is rethrown after the padding. If you want to skip the padding in some cases, call returnEarly() on the timebox that is passed to your callback:

ts
await new Timebox().call((timebox) => {
  timebox.returnEarly()
  return 'fast'
}, 500_000)

The padding goes through Sleep, so Sleep.fake() makes Timebox instant in tests.

Random chances ​

Chance runs a callback with some probability. Chance.odds(1, 100) is a one in one hundred chance. Use it for sampling, such as pruning old data on a small fraction of requests.

ts
import { Chance } from '@plinthjs/support'

Chance.odds(1, 100)
  .winner(() => pruneOldRecords())
  .loser(() => undefined)
  .choose()

choose() returns what the winning or losing callback returned. choose(5) draws five times and returns an array. With one argument, Chance.odds(0.25) is read as a probability between 0 and 1.

To make draws deterministic in tests, force them:

ts
Chance.alwaysWin(() => {
  // every draw in here wins; the previous setting is restored afterwards, even if this throws
})

Chance.alwaysLose() // without a callback, stays forced until you reset it
Chance.fix([true, false]) // the next draws win, then lose
Chance.reset() // back to real randomness (same as determineResultsNormally())

Mixins ​

Three functions build base classes that add behaviour to your own classes. Each takes an optional base class to extend, so they compose.

ts
import { Conditionable, Macroable, Tappable } from '@plinthjs/support'

Tappable adds tap(callback), which passes the instance to a callback and returns the instance.

ts
class Box extends Tappable() {
  items: string[] = []
  add(item: string): this {
    this.items.push(item)
    return this
  }
}

new Box().tap((box) => box.add('a')).items // => ['a']

Conditionable adds when() and unless(). Each takes a condition (a value or a function that receives the instance), a callback to run when it applies, and an optional callback for the other case.

ts
class Builder extends Conditionable(Tappable()) {
  clauses: string[] = []
  add(clause: string): this {
    this.clauses.push(clause)
    return this
  }
}

new Builder().when(true, (b) => b.add('a')).unless(true, (b) => b.add('b')).clauses // => ['a']

Macroable adds static macro(name, fn), mixin(methods) and hasMacro(name), which attach methods to the class at runtime. Plugins and packages use this to extend a class they do not own.

ts
class Repo extends Macroable() {}

Repo.macro('shout', function (this: Repo, message: string) {
  return message.toUpperCase()
})
Repo.mixin({
  whisper(message: string) {
    return message.toLowerCase()
  },
})

Repo.hasMacro('shout') // => true
;(new Repo() as unknown as { shout(m: string): string }).shout('hi') // => 'HI'

Macro methods are added at runtime, so TypeScript does not know about them. Declare their types with a type assertion or an interface merge where you call them.

Released under the MIT License.