Socket
Socket
Sign inDemoInstall

@poppinss/utils

Package Overview
Dependencies
Maintainers
2
Versions
89
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@poppinss/utils - npm Package Compare versions

Comparing version 5.0.0 to 6.0.0-0

build/lodash/main.cjs

26

build/index.d.ts

@@ -1,10 +0,16 @@

export * as lodash from './src/lodash';
export { slash } from './src/slash';
export { flatten } from './src/flatten';
export { Exception } from './src/Exception';
export { safeParse } from './src/safeParse';
export { esmRequire } from './src/esmRequire';
export { esmResolver } from './src/esmResolver';
export { safeStringify } from './src/safeStringify';
export { defineStaticProperty } from './src/defineStaticProperty';
export { ManagerConfigValidator } from './src/ManagerConfigValidator';
/// <reference types="node" resolution-mode="require"/>
export { base64 } from './src/base64.js';
export { compose } from './src/compose.js';
export { defineStaticProperty } from './src/define_static_property.js';
export { Exception } from './src/exception.js';
export { flatten } from './src/flatten.js';
export { fsImportAll } from './src/fs_import_all.js';
export { fsReadAll } from './src/fs_read_all.js';
export { isScriptFile } from './src/is_script_file.js';
export { MessageBuilder } from './src/message_builder.js';
export { naturalSort } from './src/natural_sort.js';
export { ObjectBuilder } from './src/object_builder.js';
export { safeEqual } from './src/safe_equal.js';
export { slash } from './src/slash.js';
export declare function getDirname(url: string | URL): string;
export declare function getFilename(url: string | URL): string;

@@ -1,53 +0,21 @@

"use strict";
/*
* @poppinss/utils
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ManagerConfigValidator = exports.defineStaticProperty = exports.safeStringify = exports.esmResolver = exports.esmRequire = exports.safeParse = exports.Exception = exports.flatten = exports.slash = exports.lodash = void 0;
exports.lodash = __importStar(require("./src/lodash"));
var slash_1 = require("./src/slash");
Object.defineProperty(exports, "slash", { enumerable: true, get: function () { return slash_1.slash; } });
var flatten_1 = require("./src/flatten");
Object.defineProperty(exports, "flatten", { enumerable: true, get: function () { return flatten_1.flatten; } });
var Exception_1 = require("./src/Exception");
Object.defineProperty(exports, "Exception", { enumerable: true, get: function () { return Exception_1.Exception; } });
var safeParse_1 = require("./src/safeParse");
Object.defineProperty(exports, "safeParse", { enumerable: true, get: function () { return safeParse_1.safeParse; } });
var esmRequire_1 = require("./src/esmRequire");
Object.defineProperty(exports, "esmRequire", { enumerable: true, get: function () { return esmRequire_1.esmRequire; } });
var esmResolver_1 = require("./src/esmResolver");
Object.defineProperty(exports, "esmResolver", { enumerable: true, get: function () { return esmResolver_1.esmResolver; } });
var safeStringify_1 = require("./src/safeStringify");
Object.defineProperty(exports, "safeStringify", { enumerable: true, get: function () { return safeStringify_1.safeStringify; } });
var defineStaticProperty_1 = require("./src/defineStaticProperty");
Object.defineProperty(exports, "defineStaticProperty", { enumerable: true, get: function () { return defineStaticProperty_1.defineStaticProperty; } });
var ManagerConfigValidator_1 = require("./src/ManagerConfigValidator");
Object.defineProperty(exports, "ManagerConfigValidator", { enumerable: true, get: function () { return ManagerConfigValidator_1.ManagerConfigValidator; } });
import { fileURLToPath } from 'node:url';
import { dirname as pathDirname } from 'node:path';
export { base64 } from './src/base64.js';
export { compose } from './src/compose.js';
export { defineStaticProperty } from './src/define_static_property.js';
export { Exception } from './src/exception.js';
export { flatten } from './src/flatten.js';
export { fsImportAll } from './src/fs_import_all.js';
export { fsReadAll } from './src/fs_read_all.js';
export { isScriptFile } from './src/is_script_file.js';
export { MessageBuilder } from './src/message_builder.js';
export { naturalSort } from './src/natural_sort.js';
export { ObjectBuilder } from './src/object_builder.js';
export { safeEqual } from './src/safe_equal.js';
export { slash } from './src/slash.js';
export function getDirname(url) {
return pathDirname(getFilename(url));
}
export function getFilename(url) {
return fileURLToPath(url);
}

@@ -1,1 +0,1 @@

export { flattie as flatten } from 'flattie';
export declare function flatten<X = Record<string, any>, Y = unknown>(input: Y, glue?: string, keepNullish?: boolean): X;

@@ -1,13 +0,4 @@

"use strict";
/*
* @poppinss/utils
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.flatten = void 0;
var flattie_1 = require("flattie");
Object.defineProperty(exports, "flatten", { enumerable: true, get: function () { return flattie_1.flattie; } });
import { flattie } from 'flattie';
export function flatten(input, glue, keepNullish) {
return flattie(input, glue, keepNullish);
}

@@ -1,5 +0,1 @@

/**
* Convert windows path to unix.
* Copied from https://github.com/sindresorhus/slash as the package is ESM only
*/
export declare function slash(filePath: string): string;
export { default as slash } from 'slash';

@@ -1,24 +0,1 @@

"use strict";
/*
* @poppinss/utils
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.slash = void 0;
/**
* Convert windows path to unix.
* Copied from https://github.com/sindresorhus/slash as the package is ESM only
*/
function slash(filePath) {
const isExtendedLengthPath = /^\\\\\?\\/.test(filePath);
const hasNonAscii = /[^\u0000-\u0080]+/.test(filePath); // eslint-disable-line no-control-regex
if (isExtendedLengthPath || hasNonAscii) {
return filePath;
}
return filePath.replace(/\\/g, '/');
}
exports.slash = slash;
export { default as slash } from 'slash';
{
"name": "@poppinss/utils",
"version": "5.0.0",
"version": "6.0.0-0",
"description": "Handy utilities for repetitive work",
"main": "build/index.js",
"type": "module",
"files": [
"build/src",
"lodash",
"build/lodash",
"build/index.d.ts",
"build/index.js",
"types",
"build/helpers.d.ts",
"build/helpers.js"
"build/index.js"
],
"exports": {
".": "./build/index.js",
"./lodash": {
"types": "./lodash/lodash.types.d.ts",
"node": "./build/lodash/main.cjs"
},
"./string": "./build/src/string/main.js",
"./json": "./build/src/json/main.js",
"./types": "./build/src/types.js"
},
"scripts": {
"mrm": "mrm --preset=@adonisjs/mrm-preset",
"pretest": "npm run lint",
"test": "node .bin/test.js",
"clean": "del build",
"test": "npm run build:lodash && npm run vscode:test",
"build:lodash": "lodash include=\"pick,omit,has,get,set,unset,mergeWith,merge,size,clone,cloneDeep,toPath\" --production && move-file ./lodash.custom.min.js build/lodash/main.cjs",
"vscode:test": "node --loader=ts-node/esm bin/test.ts",
"clean": "del-cli build",
"compile": "npm run lint && npm run clean && tsc",
"build": "npm run compile",
"commit": "git-cz",
"release": "np --message=\"chore(release): %s\"",
"build": "npm run compile && npm run build:lodash",
"release": "np",
"version": "npm run build",
"prepublishOnly": "npm run build && cd build && node bin/test.js",
"lint": "eslint . --ext=.ts",
"format": "prettier --write .",
"prepublishOnly": "npm run build",
"lint": "eslint . --ext=.ts",
"sync-labels": "github-label-sync --labels ./node_modules/@adonisjs/mrm-preset/gh-labels.json poppinss/utils"
"sync-labels": "github-label-sync --labels .github/labels.json poppinss/utils"
},
"keywords": [
"utils"
"toolkit",
"utilities"
],

@@ -35,65 +46,42 @@ "author": "virk,poppinss",

"devDependencies": {
"@adonisjs/mrm-preset": "^5.0.3",
"@adonisjs/require-ts": "^2.0.11",
"@poppinss/dev-utils": "^2.0.3",
"@types/fs-readdir-recursive": "^1.0.0",
"@types/lodash": "^4.14.181",
"@types/ms": "^0.7.31",
"@types/node": "^17.0.23",
"@types/pluralize": "0.0.29",
"@types/require-all": "^3.0.3",
"del-cli": "^4.0.1",
"doctoc": "^2.1.0",
"eslint": "^8.13.0",
"@commitlint/cli": "^17.1.2",
"@commitlint/config-conventional": "^17.1.0",
"@japa/assert": "^1.3.6",
"@japa/expect-type": "^1.0.1",
"@japa/run-failed-tests": "^1.1.0",
"@japa/runner": "^2.2.1",
"@japa/spec-reporter": "^1.3.1",
"@swc/core": "^1.3.3",
"@types/fs-extra": "^9.0.13",
"@types/node": "^18.7.19",
"del-cli": "^5.0.0",
"eslint": "^8.24.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-adonis": "^2.1.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-adonis": "^3.0.2",
"eslint-plugin-prettier": "^4.2.1",
"fs-extra": "^10.1.0",
"github-label-sync": "^2.2.0",
"husky": "^7.0.4",
"japa": "^4.0.0",
"mrm": "^4.0.0",
"np": "^7.6.1",
"prettier": "^2.6.2",
"typescript": "^4.6.3"
"husky": "^8.0.1",
"lodash": "^4.17.21",
"lodash-cli": "^4.17.5",
"move-file-cli": "^3.0.0",
"np": "^7.6.2",
"prettier": "^2.7.1",
"ts-node": "^10.9.1",
"typescript": "^4.8.3"
},
"nyc": {
"exclude": [
"test"
],
"extension": [
".ts"
]
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
},
"np": {
"contents": ".",
"anyBranch": false
},
"dependencies": {
"@poppinss/file-generator": "^1.0.2",
"@lukeed/ms": "^2.0.0",
"@types/bytes": "^3.1.1",
"@types/he": "^1.1.2",
"@types/pluralize": "^0.0.29",
"bytes": "^3.1.2",
"change-case": "^4.1.2",
"cuid": "^2.1.8",
"case-anything": "^2.1.10",
"flattie": "^1.1.0",
"fs-readdir-recursive": "^1.1.0",
"he": "^1.2.0",
"kind-of": "^6.0.3",
"lodash": "^4.17.21",
"ms": "^2.1.3",
"pluralize": "^8.0.0",
"require-all": "^3.0.0",
"resolve-from": "^5.0.0",
"safe-stable-stringify": "^2.4.0",
"secure-json-parse": "^2.5.0",
"slash": "^4.0.0",
"slugify": "^1.6.5",
"truncatise": "0.0.8"
"truncatise": "^0.0.8"
},
"directories": {
"doc": "docs",
"test": "test"
},
"repository": {

@@ -110,7 +98,5 @@ "type": "git",

"plugin:adonis/typescriptPackage",
"prettier",
"prettier"
],
"plugins": [
"prettier",
"prettier"

@@ -140,15 +126,17 @@ ],

},
"mrmConfig": {
"core": false,
"license": "MIT",
"services": [
"github-actions"
],
"minNodeVersion": "16.13.1",
"probotApps": [
"stale",
"lock"
],
"runGhActionsOnWindows": true
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
},
"publishConfig": {
"access": "public",
"tag": "next"
},
"np": {
"message": "chore(release): %s",
"tag": "next",
"branch": "main",
"anyBranch": false
}
}

@@ -1,181 +0,41 @@

<div align="center"><img src="https://res.cloudinary.com/adonisjs/image/upload/q_100/v1557762307/poppinss_iftxlt.jpg" width="600px"></div>
# @poppinss/utils
# Utils
> A toolkit of utilities used across all the AdonisJS, Edge, and Japa packages
> Collection of reusable scripts used by AdonisJS core team
[![gh-workflow-image]][gh-workflow-url] [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url] [![synk-image]][synk-url]
This module exports a collection of re-usable utilties to avoid re-writing the same code in every other package. We also include a handful of Lodash utilities, which are used across the AdonisJS packages eco-system.
## Why this package exists?
<details>
<summary>
<strong>Version 3.0 breaking changes</strong>
</summary>
The version 3.0 re-format the exports to expose an "helpers" subpath to be used within the AdonisJS apps as well.
The idea is to separate helpers that we need to share with AdonisJS core inside its own module, accessible as `‌@poppinss/utils/build/helpers`.
### Inside helpers subpath
Following modules are now moved to a subpath.
- `MessageBuilder`
- `base64`
- `compose`
- `fsReadAll`
- `interpolate`
- `requireAll`
- `resolveDir`
- `resolveFrom`
```ts
// Earlier
import {
MessageBuilder,
base64,
compose,
fsReadAll,
interpolate,
requireAll,
resolveDir,
resolveFrom,
safeEqual
} from '@poppinss/utils'
Many of my open source projects (including AdonisJS) use many single-purpose utility packages from npm. Over the years, I have faced the following challenges when using these packages.
// After version 3.0
import {
MessageBuilder,
base64,
compose,
fsReadAll,
interpolate,
requireAll,
resolveDir,
resolveFrom,
safeEqual
} from '@poppinss/utils/build/helpers'
- It takes a lot of time to find a perfect package for the use case. The package should be well maintained, have good test coverage, and not accumulate debt by supporting some old versions of Node.js.
- Some packages are great, but they end up pulling a lot of unnecessary dependencies like [(requiring TypeScript as a prod dependency)](https://github.com/blakeembrey/change-case/issues/281)
- Sometimes I end up using different packages for the same utility (because, I cannot remember what I used last time in that other package). So I want to spend time once choosing the one I need and then bundle it inside `@poppinss/utils`.
- Some authors introduce breaking changes too often (not a criticism). Therefore, I prefer wrapping their packages with my external API only to absorb breaking changes in one place.
- Rest are some handwritten utilities to fit my needs
````
> **Note**: If you are creating an AdonisJS package, I highly recommend using this package since it is already part of the user's project dependencies.
### randomString
> **Warning**: This package is not for general use (outside the AdonisJS ecosystem). I will not add new helpers or remove any to cater to a broader audience.
The `randomString` is now part of the `string` helpers.
## Other packages to use
A note to self and others to consider the following packages.
```ts
// Earlier
import { randomString } from '@poppinss/utils'
randomString(32)
| Package | Description |
|---------|-------------|
| [he](https://www.npmjs.com/package/he) | For escaping HTML entities and encoding unicode symbols. Has zero dependencies |
| [@sindresorhus/is](https://www.npmjs.com/package/@sindresorhus/is) | For advanced type checking. Has zero dependencies |
// After version 3.0
import { string } from '@poppinss/utils/build/helpers'
string.generateRandom(32)
````
## Package size
Even though I do not care much about the package size (most of work is consumed on server side), I am mindful around the utilities and ensure not end up using really big packages for smaller use-cases.
### lodash
| | |
|------------------|-----------------|
| Source code size | `272K` (approx) |
| Dependencies size | `432K` (approx) |
The following lodash functions have been removed with new alternatives.
- `snakeCase`
- `camelCase`
- `startCase`
```ts
// Earlier
import { lodash } from '@poppinss/utils'
lodash.snakeCase()
lodash.camelCase()
lodash.startCase()
// After version 3.0
import { string } from '@poppinss/utils/build/helpers'
string.snakeCase()
string.camelCase()
string.titleCase()
```
</details>
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of contents
- [Installation](#installation)
- [Exception](#exception)
- [esmRequire](#esmrequire)
- [esmResolver](#esmresolver)
- [Lodash utilities](#lodash-utilities)
- [Exported methods](#exported-methods)
- [Safe stringify](#safe-stringify)
- [Safe parse](#safe-parse)
- [defineStaticProperty](#definestaticproperty)
- [flatten](#flatten)
- [Helpers](#helpers)
- [fsReadAll](#fsreadall)
- [requireAll](#requireall)
- [resolveFrom](#resolvefrom)
- [resolveDir](#resolvedir)
- [interpolate](#interpolate)
- [Base 64 Encode/Decode](#base-64-encodedecode)
- [encode](#encode)
- [decode](#decode)
- [urlEncode](#urlencode)
- [urlDecode](#urldecode)
- [Safe equal](#safe-equal)
- [Message Builder](#message-builder)
- [compose](#compose)
- [Mixins gotchas](#mixins-gotchas)
- [string](#string)
- [camelCase](#camelcase)
- [snakeCase](#snakecase)
- [dashCase](#dashcase)
- [pascalCase](#pascalcase)
- [capitalCase](#capitalcase)
- [sentenceCase](#sentencecase)
- [dotCase](#dotcase)
- [noCase](#nocase)
- [titleCase](#titlecase)
- [pluralize](#pluralize)
- [truncate](#truncate)
- [excerpt](#excerpt)
- [condenseWhitespace](#condensewhitespace)
- [escapeHTML](#escapehtml)
- [encodeSymbols](#encodesymbols)
- [toSentence](#tosentence)
- [prettyBytes](#prettybytes)
- [toBytes](#tobytes)
- [prettyMs](#prettyms)
- [toMs](#toms)
- [ordinalize](#ordinalize)
- [generateRandom](#generaterandom)
- [isEmpty](#isempty)
- [Types](#types)
- [lookup](#lookup)
- [isNull](#isnull)
- [isBoolean](#isboolean)
- [isBuffer](#isbuffer)
- [isNumber](#isnumber)
- [isString](#isstring)
- [isArguments](#isarguments)
- [isObject](#isobject)
- [isDate](#isdate)
- [isArray](#isarray)
- [isRegexp](#isregexp)
- [isError](#iserror)
- [isFunction](#isfunction)
- [isClass](#isclass)
- [isInteger](#isinteger)
- [isFloat](#isfloat)
- [isDecimal](#isdecimal)
- [ObjectBuilder](#objectbuilder)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
## Installation
Install the package from npm registry as follows:
Install the package from the npm registry as follows:

@@ -185,1079 +45,1007 @@ ```sh

# yarn
# Yarn lovers
yarn add @poppinss/utils
```
and then use it as follows:
## Exported modules
Following are the exported modules. Only the generic helpers are shipped from the main path. The rest of the helpers are grouped inside sub-modules.
```ts
import { requireAll } from '@poppinss/utils'
requireAll(__dirname)
```
// string sub-module
import string from '@poppinss/utils/string'
## Exception
// json sub-module
import json from '@poppinss/utils/json'
A custom exception class that extends the `Error` class to add support for defining `status` and `error codes`.
// lodash sub-module
import lodash from '@poppinss/utils/lodash'
```ts
import { Exception } from '@poppinss/utils'
throw new Exception('Something went wrong', 500, 'E_RUNTIME_EXCEPTION')
throw new Exception('Route not found', 404, 'E_ROUTE_NOT_FOUND')
// main module
import { base64, Exception, fsReadAll } from '@poppinss/utils'
```
## esmRequire
### String helpers
Utility to require script files wihtout worrying about `CommonJs` and `ESM` exports. This is how it works.
A collection of helpers to perform operations on/related to a string value.
- Returns the exported value for `module.exports`.
- Returns the default value is an ESM module has `export default`.
- Returns all exports if is an ESM module and doesn't have `export default`.
**foo.js**
```ts
module.exports = {
greeting: 'Hello world',
}
import string from '@poppinss/utils/string'
```
**foo.default.js**
#### excerpt
```ts
export default {
greeting: 'Hello world',
}
```
Generate an excerpt from a string value. If the input value contains HTML tags, we will remove them from the excerpt.
**foo.esm.js**
```ts
export const greeting = {
greeting: 'hello world',
}
```
const html = `<p>AdonisJS is a Node.js framework, and hence it requires Node.js to be installed on your computer. To be precise, we need at least the latest release of <code>Node.js v14</code>.</p>`
```ts
import { esmRequire } from '@poppinss/utils'
esmRequire('./foo.js') // { greeting: 'hello world' }
esmRequire('./foo.default.js') // { greeting: 'hello world' }
esmRequire('./foo.esm.js') // { greeting: { greeting: 'hello world' } }
console.log(string.excerpt(html, 70))
// AdonisJS is a Node.js framework, and hence it requires Node.js to be i...
```
## esmResolver
| Argument | Type | Description |
|---------|------|---------------|
| `sentence` | string | The value for which to generate excerpt |
| `charactersLimit` | string | The number of characters to keep |
| `options.completeWords` | boolean | When set to `true`, the truncation will happen only after complete words. This option might go over the defined characters limit
| `options.suffix` | string | The value to append after the truncated string. Defaults to three dots `...` |
The `esmResolver` method works similar to `esmRequire`. However, instead of requiring the file, it accepts the object and returns the exported as per the same logic defined above.
#### truncate
Truncate a string value to a certain length. The method is the same as the `excerpt` method but does not remove any HTML tags. It is a great fit when you are truncating a non-HTML string.
```ts
import { esmRequire } from '@poppinss/utils'
const text = `AdonisJS is a Node.js framework, and hence it requires Node.js to be installed on your computer. To be precise, we need at least the latest release of Node.js 14.`
esmResolver({ greeting: 'hello world' }) // { greeting: 'hello world' }
esmResolver({
default: { greeting: 'hello world' },
__esModule: true,
}) // { greeting: 'hello world' }
esmResolver({
greeting: { greeting: 'hello world' },
__esModule: true,
}) // { greeting: { greeting: 'hello world' } }
console.log(string.truncate(text, 70))
// AdonisJS is a Node.js framework, and hence it requires Node.js to be i...
```
## Lodash utilities
| Argument | Type | Description |
|---------|------|---------------|
| `sentence` | string | The value to truncate |
| `charactersLimit` | string | The number of characters to keep |
| `options.completeWords` | boolean | When set to `true`, the truncation will happen only after complete words. This option might go over the defined characters limit
| `options.suffix` | string | The value to append after the truncated string. Defaults to three dots `...` |
Lodash itself is a bulky library and most of the times, we don't need all the functions from it.
#### slug
Generate slug for a string value. The method is exported directly from the [slugify](https://www.npmjs.com/package/slugify) package.
Also, all of the lodash functions are published as individual modules on npm. However, most of those individual packages are outdated and using them is not an option.
Please check the package documentation for [available options](https://www.npmjs.com/package/slugify#options).
Instead, we decided to pick some individual utilities that we need inside AdonisJS ecosystem and export them from the lodash package, as each function is exposed in its own separate file.
```ts
import { lodash } from '@poppinss/utils'
lodash.get({ name: 'virk' }, 'name') // virk
console.log(string.slug('hello ♥ world'))
// hello-love-world
```
### Exported methods
You can add custom replacements for Unicode values as follows.
Following is the list of exported helpers.
```ts
string.slug.extend({ '☢': 'radioactive' })
- [pick](https://lodash.com/docs/latest#pick)
- [omit](https://lodash.com/docs/latest#omit)
- [has](https://lodash.com/docs/latest#has)
- [get](https://lodash.com/docs/latest#get)
- [set](https://lodash.com/docs/latest#set)
- [unset](https://lodash.com/docs/latest#unset)
- [mergeWith](https://lodash.com/docs/latest#mergeWith)
- [merge](https://lodash.com/docs/latest#merge)
- [size](https://lodash.com/docs/latest#size)
- [clone](https://lodash.com/docs/latest#clone)
- [cloneDeep](https://lodash.com/docs/latest#cloneDeep)
console.log(string.slug('unicode ♥ is ☢'))
// unicode-love-is-radioactive
```
## Safe stringify
#### interpolate
Interpolate variables inside a string. The variables must be inside double curly braces.
Similar to `JSON.stringify`, but also handles Circular references by removing them.
```ts
import { safeStringify } from '@poppinss/utils'
string.interpolate(
'hello {{ user.username }}',
{ user: { username: 'virk' } }
)
const o = { b: 1, a: 0 }
o.o = o
console.log(safeStringify(o))
// { "b":1,"a":0 }
console.log(JSON.stringify(o))
// TypeError: Converting circular structure to JSON
// hello virk
```
## Safe parse
You can also replace array values by mentioning the array index.
Similar to `JSON.parse`, but protects against [Prototype Poisoning](https://medium.com/intrinsic/javascript-prototype-poisoning-vulnerabilities-in-the-wild-7bc15347c96)
```ts
import { safeParse } from '@poppinss/utils'
string.interpolate(
'hello {{ users.0 }}',
{ users: ['virk'] }
)
const input = '{ "user": { "__proto__": { "isAdmin": true } } }'
JSON.parse(input)
// { user: { __proto__: { isAdmin: true } } }
safeParse(input)
// { user: {} }
// hello virk
```
## defineStaticProperty
You can escape the curly braces by prefixing them with `\\`.
Explicitly define static properties on a class by checking for `hasOwnProperty`. In case of inheritance, the properties from the parent class are cloned vs following the prototypal inheritance.
We use/need this copy from parent class behavior a lot in AdonisJS. Here's an example of Lucid models
You create an application wide base model
```ts
class AppModel extends BaseModel {
@column.datetime()
public createdAt: DateTime
}
```
string.interpolate('hello \\{{ users.0 }}', {})
AdonisJS will create the `$columnDefinitions` property on the `AppModel` class, that holds all the columns
```ts
AppModel.$columnDefinitions // { createdAt: { columName: created_at } }
// hello {{ users.0 }}
```
Now, lets create another model inheriting the `AppModel`
#### plural
Convert a word to its plural form. The method is exported directly from the [pluralize](https://www.npmjs.com/package/pluralize) package.
```ts
class User extends AppModel {
@column()
public id: number
}
string.plural('test')
// tests
```
As per the Javascript prototypal inheritance. The `User` model will not contain the columns from the `AppModel`, because we just re-defined the `$columnDefinitions` property. However, we don't want this behavior and instead want to copy the columns from the `AppModel` and then add new columns to it.
#### singular
Convert a word to its singular form. The method is exported directly from the [pluralize](https://www.npmjs.com/package/pluralize) package.
Voila! Use the `defineStaticProperty` helper from this class.
```ts
class LucidBaseModel {
static boot() {
defineStaticProperty(this, LucidBaseModel, {
propertyName: '$columnDefinitions',
defaultValue: {},
strategy: 'inherit',
})
}
}
string.singular('tests')
// test
```
The `defineStaticProperty` takes a total of three arguments.
#### pluralize
This method combines the `singular` and `plural` methods and uses one or the other based on the count. For example:
- The first argument is always `this`.
- The second argument is the root level base class. This will usually be the class exported by your package or module.
- The third argument takes the `propertyName`, `defaultValue (in case, there is nothing to copy)`, and the `strategy`.
- The `inherit` strategy will copy the properties from the base class.
- The `define` strategy will always use the `defaultValue` to define the property on the class. In other words, there is no copy behavior, but prototypal inheritance chain is also breaked by explicitly re-defining the property.
## flatten
Flatten an object/array. The method wraps the [flattie](https://github.com/lukeed/flattie) package.
```ts
import { flatten } from '@poppinss/utils'
string.pluralize('box', 1) // box
string.pluralize('box', 2) // boxes
string.pluralize('box', 0) // boxes
flatten({
a: 'hi',
b: {
a: null,
b: ['foo', '', null, 'bar'],
d: 'hello',
e: {
a: 'yo',
b: undefined,
c: 'sup',
d: 0,
f: [
{ foo: 123, bar: 123 },
{ foo: 465, bar: 456 },
]
}
},
c: 'world'
});
// {
// 'a': 'hi',
// 'b.b.0': 'foo',
// 'b.b.1': '',
// 'b.b.3': 'bar',
// 'b.d': 'hello',
// 'b.e.a': 'yo',
// 'b.e.c': 'sup',
// 'b.e.d': 0,
// 'b.e.f.0.foo': 123,
// 'b.e.f.0.bar': 123,
// 'b.e.f.1.foo': 465,
// 'b.e.f.1.bar': 456,
// 'c': 'world'
// }
string.pluralize('boxes', 1) // box
string.pluralize('boxes', 2) // boxes
string.pluralize('boxes', 0) // boxes
```
## Helpers
The `addPluralRule`, `addSingularRule`, `addIrregularRule`, and `addUncountableRule` methods exposed by the pluralize package can be called as follows.
The helpers module is also available in AdonisJS applications as follows:
```ts
import { fsReadAll, string, types } from '@ioc:Adonis/Core/Helpers'
string.pluralize.addUncountableRule('paper')
string.pluralize.addSingularRule(/singles$/i, 'singular')
```
The `@poppinss/utils` exposes this module as follows
#### isPlural
Find if a word is already in plural form. The method is exported directly from the [pluralize](https://www.npmjs.com/package/pluralize) package.
```ts
import { fsReadAll, string, types } from '@poppinss/utils/build/helpers'
string.isPlural('tests') // true
```
### fsReadAll
#### isSingular
Find if a word is already in a singular form. The method is exported directly from the [pluralize](https://www.npmjs.com/package/pluralize) package.
A utility to recursively read all script files for a given directory. This method is equivalent to
`readdir + recursive + filter (.js, .json, .ts)`.
```ts
import { fsReadAll } from '@poppinss/utils/build/helpers'
const files = fsReadAll(__dirname) // array of strings
string.isSingular('test') // true
```
You can also define your custom filter function. The filter function must return `true` for files to be included.
#### camelCase
Convert a string value to camelcase.
```ts
const files = fsReadAll(__dirname, (file) => {
return file.endsWith('.foo.js')
})
string.camelCase('user_name') // userName
```
### requireAll
Following are some of the conversion examples.
Same as `fsReadAll`, but instead require the files. Helpful when you want to load all the config files inside a directory on app boot.
| Input | Output |
|------|---------|
| 'test' | 'test' |
| 'test string' | 'testString' |
| 'Test String' | 'testString' |
| 'TestV2' | 'testV2' |
| '_foo_bar_' | 'fooBar' |
| 'version 1.2.10' | 'version1210' |
| 'version 1.21.0' | 'version1210' |
```ts
import { requireAll } from '@poppinss/utils/build/helpers'
const config = requireAll(join(__dirname, 'config'))
#### capitalCase
Convert a string value to a capital case.
{
file1: {}, // exported object
file2: {} // exported object
}
```
The method also accepts the following options
```ts
requireAll(join(__dirname, 'config'), recursive, optional, filter)
string.capitalCase('helloWorld') // Hello World
```
- `recursive` Load all files recursively. Defaults to true.
- `optional` Do not raise exception when the root directory is missing. Defaults to false.
- `filter` Cherry pick files to require. By default, all JavaScript, TypeScript and JSON files are required.
Following are some of the conversion examples.
### resolveFrom
| Input | Output |
|------|---------|
| 'test' | 'Test' |
| 'test string' | 'Test String' |
| 'Test String' | 'Test String' |
| 'TestV2' | 'Test V 2' |
| 'version 1.2.10' | 'Version 1.2.10' |
| 'version 1.21.0' | 'Version 1.21.0' |
Works similar to `require.resolve`, however it handles the absolute paths properly.
#### dashCase
Convert a string value to a dash case.
```ts
import { resolveFrom } from '@poppinss/utils/build/helpers'
resolveFrom(__dirname, 'npm-package') // returns path to package "main" file
resolveFrom(__dirname, './foo.js') // returns path to `foo.js` (if exists)
resolveFrom(__dirname, join(__dirname, './foo.js')) // returns path to `foo.js` (if exists)
string.dashCase('helloWorld') // hello-world
```
### resolveDir
Optionally, you can capitalize the first letter of each word.
The `require.resolve` or `resolveFrom` method can only resolve paths to a given file and not the directory. For example: If you pass path to a directory, then it will search for `index.js` inside it and in case of a package, it will be search for `main` entry point.
On the other hand, the `resolveDir` method can also resolve path to directories using following resolution.
- Absolute paths are returned as it is.
- Relative paths starting with `./` or `.\` are resolved using `path.join`.
- Path to packages inside `node_modules` are resolved as follows: - Uses `require.resolve` to resolve the `package.json` file. - Then replace the `package-name` with the absolute resolved package path.
```ts
import { resolveDir } from '@poppinss/utils/build/helpers'
string.dashCase('helloWorld', { capitalize: true }) // Hello-World
```
resolveDir(__dirname, './database/migrations')
// __dirname + /database/migrations
Following are some of the conversion examples.
resolveDir(__dirname, 'some-package/database/migrations')
// {path-to-package}/database/migrations
| Input | Output |
|--------|--------|
| 'test' | 'test' |
| 'test string' | 'test-string' |
| 'Test String' | 'test-string' |
| 'Test V2' | 'test-v2' |
| 'TestV2' | 'test-v-2' |
| 'version 1.2.10' | 'version-1210' |
| 'version 1.21.0' | 'version-1210' |
resolveDir(__dirname, '@some/package/database/migrations')
// {path-to-package}/database/migrations
```
#### dotCase
Convert a string value to a dot case.
### interpolate
A small utility function to interpolate values inside a string.
```ts
import { interpolate } from '@poppinss/utils/build/helpers'
interpolate('hello {{ username }}', {
username: 'virk',
})
interpolate('hello {{ users.0.username }}', {
users: [{ username: 'virk' }],
})
string.dotCase('helloWorld') // hello.World
```
If value is missing, it will be replaced with an `'undefined'` string.
Optionally, you can also convert the first letter of all the words to lowercase.
Use the `\` to escape a mustache block from getting evaluated.
```ts
import { interpolate } from '@poppinss/utils/build/helpers'
interpolate('\\{{ username }} expression evaluates to {{ username }}', {
username: 'virk',
})
// Output: {{ username }} expression evaluates to virk
string.dotCase('helloWorld', { lowerCase: true }) // hello.world
```
### Base 64 Encode/Decode
Following are some of the conversion examples.
Following helpers for base64 encoding/decoding also exists.
| Input | Output |
|--------|--------|
| 'test' | 'test' |
| 'test string' | 'test.string' |
| 'Test String' | 'Test.String' |
| 'dot.case' | 'dot.case' |
| 'path/case' | 'path.case' |
| 'TestV2' | 'Test.V.2' |
| 'version 1.2.10' | 'version.1210' |
| 'version 1.21.0' | 'version.1210' |
#### encode
#### noCase
Remove all sorts of casing from a string value.
```ts
import { base64 } from '@poppinss/utils/build/helpers'
base64.encode('hello world')
base64.encode(Buffer.from('hello world', 'binary'))
string.noCase('helloWorld') // hello world
```
#### decode
Following are some of the conversion examples.
| Input | Output |
|--------|--------|
| 'test' | 'test' |
| 'TEST' | 'test' |
| 'testString' | 'test string' |
| 'testString123' | 'test string123' |
| 'testString_1_2_3' | 'test string 1 2 3' |
| 'ID123String' | 'id123 string' |
| 'foo bar123' | 'foo bar123' |
| 'a1bStar' | 'a1b star' |
| 'CONSTANT_CASE ' | 'constant case' |
| 'CONST123_FOO' | 'const123 foo' |
| 'FOO_bar' | 'foo bar' |
| 'XMLHttpRequest' | 'xml http request' |
| 'IQueryAArgs' | 'i query a args' |
| 'dot.case' | 'dot case' |
| 'path/case' | 'path case' |
| 'snake_case' | 'snake case' |
| 'snake_case123' | 'snake case123' |
| 'snake_case_123' | 'snake case 123' |
| '"quotes"' | 'quotes' |
| 'version 0.45.0' | 'version 0 45 0' |
| 'version 0..78..9' | 'version 0 78 9' |
| 'version 4_99/4' | 'version 4 99 4' |
| ' test ' | 'test' |
| 'something_2014_other' | 'something 2014 other' |
| 'amazon s3 data' | 'amazon s3 data' |
| 'foo_13_bar' | 'foo 13 bar' |
#### pascalCase
Convert a string value to pascal case. Great for generating JavaScript class names.
```ts
import { base64 } from '@poppinss/utils/build/helpers'
base64.decode(base64.encode('hello world'))
base64.decode(base64.encode(Buffer.from('hello world', 'binary')), 'binary')
string.pascalCase('user team') // UserTeam
```
#### urlEncode
Following are some of the conversion examples.
Same as `encode`, but safe for URLS and Filenames
| Input | Output |
|--------|--------|
| 'test' | 'Test' |
| 'test string' | 'TestString' |
| 'Test String' | 'TestString' |
| 'TestV2' | 'TestV2' |
| 'version 1.2.10' | 'Version1210' |
| 'version 1.21.0' | 'Version1210' |
#### urlDecode
#### sentenceCase
Convert a value to a sentence.
Same as `decode`, but decodes the `urlEncode` output values
### Safe equal
Compares two values by avoid [timing attack](https://en.wikipedia.org/wiki/Timing_attack). Accepts any input that can be passed to `Buffer.from`
```ts
import { safeValue } from '@poppinss/utils/build/helpers'
if (safeValue('foo', 'foo')) {
}
string.sentenceCase('getting-started-with-adonisjs')
// Getting started with adonisjs
```
### Message Builder
Following are some of the conversion examples.
Message builder provides a sane API for stringifying objects similar to `JSON.stringify` but has a few advantages.
| Input | Output |
|--------|--------|
| 'test' | 'Test' |
| 'test string' | 'Test string' |
| 'Test String' | 'Test string' |
| 'TestV2' | 'Test v2' |
| 'version 1.2.10' | 'Version 1 2 10' |
| 'version 1.21.0' | 'Version 1 21 0' |
- It is safe from JSON poisoning vulnerability.
- You can define expiry and purpose for the encoding. The `verify` method will respect these values.
#### snakeCase
Convert value to snake case.
The message builder alone may seem useless, since anyone can decode the object and change its expiry or purpose. However, you can generate an hash of the stringified object and verify the tampering by validating the hash. This is what AdonisJS does for cookies.
```ts
import { MessageBuilder } from '@poppinss/utils/build/helpers'
const builder = new MessageBuilder()
const encoded = builder.build({ username: 'virk' }, '1 hour', 'login')
string.snakeCase('user team') // user_team
```
Now verify it
Following are some of the conversion examples.
```ts
builder.verify(encoded) // returns null, no purpose defined
builder.verify(encoded, 'register') // returns null, purpose mismatch.
builder.verify(encoded, 'login') // return { username: 'virk' }
```
| Input | Output |
|--------|--------|
| '_id' | 'id' |
| 'test' | 'test' |
| 'test string' | 'test_string' |
| 'Test String' | 'test_string' |
| 'Test V2' | 'test_v2' |
| 'TestV2' | 'test_v_2' |
| 'version 1.2.10' | 'version_1210' |
| 'version 1.21.0' | 'version_1210' |
### compose
#### titleCase
Convert a string value to title case.
Javascript doesn't have a concept of inherting multiple classes together and neither does Typescript. However, the [official documentation](https://www.typescriptlang.org/docs/handbook/mixins.html) of Typescript does talks about the concept of mixins.
As per the Typescript docs, you can create and apply mixins as follows.
```ts
type Constructor = new (...args: any[]) => any
string.titleCase('small word ends on')
// Small Word Ends On
```
const UserWithEmail = <T extends Constructor>(superclass: T) => {
return class extends superclass {
public email: string
}
}
Following are some of the conversion examples.
const UserWithPassword = <T extends Constructor>(superclass: T) => {
return class extends superclass {
public password: string
}
}
| Input | Output |
|--------|--------|
| 'one. two.' | 'One. Two.' |
| 'a small word starts' | 'A Small Word Starts' |
| 'small word ends on' | 'Small Word Ends On' |
| 'we keep NASA capitalized' | 'We Keep NASA Capitalized' |
| 'pass camelCase through' | 'Pass camelCase Through' |
| 'follow step-by-step instructions' | 'Follow Step-by-Step Instructions' |
| 'this vs. that' | 'This vs. That' |
| 'this vs that' | 'This vs That' |
| 'newcastle upon tyne' | 'Newcastle upon Tyne' |
| 'newcastle \*upon\* tyne' | 'Newcastle \*upon\* Tyne' |
class BaseModel {}
class User extends UserWithPassword(UserWithEmail(BaseModel)) {}
```
#### random
Generate a cryptographically secure random string of a given length. The output value is URL safe base64 encoded string.
Mixins are close to a perfect way of inherting multiple classes. I recommend reading [this article](https://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/) for same.
However, the syntax of applying multiple mixins is kind of ugly, as you have to apply **mixins over mixins**, creating a nested hierarchy as shown below.
```ts
UserWithAttributes(UserWithAge(UserWithPassword(UserWithEmail(BaseModel))))
string.random(32)
// 8mejfWWbXbry8Rh7u8MW3o-6dxd80Thk
```
The `compose` method is a small utility to improve the syntax a bit.
#### toSentence
Convert an array of words to a comma-separated sentence.
```ts
import { compose } from '@poppinss/utils/build/helpers'
class User extends compose(
BaseModel,
UserWithPassword,
UserWithEmail,
UserWithAge,
UserWithAttributes
) {}
string.toSentence(['routes', 'controllers', 'middleware'])
// routes, controllers, and middleware
```
#### Mixins gotchas
You can replace the `and` with an `or` by specifying the `options.lastSeparator` property.
Typescript has an [open issue](https://github.com/microsoft/TypeScript/issues/37142) related to the constructor arguments of the mixin class or the base class.
Typescript expects all classes used in the mixin chain to have a constructor with only one argument of `...args: any[]`. For example: The following code will work fine at runtime, but the **typescript compiler complains about it**.
```ts
class BaseModel {
constructor(name: string) {}
}
const UserWithEmail = <T extends typeof BaseModel>(superclass: T) => {
return class extends superclass {
// ERROR: A mixin class must have a constructor with a single rest parameter of type 'any[]'.ts(2545)
public email: string
}
}
class User extends compose(BaseModel, UserWithEmail) {}
string.toSentence(['routes', 'controllers', 'middleware'], {
lastSeparator: ', or '
})
```
You can work around this by overriding the constructor of the base class.
In the following example, the two words are combined using the `and` separator, not the comma (usually advocated in English). However, you can use a custom separator for a pair of words.
```ts
import { NormalizeConstructor, compose } from '@poppinss/utils/build/helpers'
string.toSentence(['routes', 'controllers'])
// routes and controllers
const UserWithEmail = <T extends NormalizeConstructor<typeof BaseModel>>(superclass: T) => {
return class extends superclass {
public email: string
}
}
string.toSentence(['routes', 'controllers'], {
pairSeparator: ', and '
})
// routes, and controllers
```
### string
#### condenseWhitespace
Remove multiple whitespaces from a string to a single whitespace.
The `string` module includes a bunch of helper methods to work with strings.
#### camelCase
Convert a string to its `camelCase` version.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.condenseWhitespace('hello world')
// hello world
string.camelCase('hello-world') // helloWorld
string.condenseWhitespace(' hello world ')
// hello world
```
#### snakeCase
#### ordinal
Get the ordinal letter for a given number.
Convert a string to its `snake_case` version.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.ordinal(1) // 1st
string.ordinal(2) // '2nd'
string.ordinal(3) // '3rd'
string.ordinal(4) // '4th'
string.snakeCase('helloWorld') // hello_world
string.ordinal(23) // '23rd'
string.ordinal(24) // '24th'
```
#### dashCase
#### seconds.(parse/format)
Parse a string-based time expression to seconds.
Convert a string to its `dash-case` version. Optionally, you can also capitalize the first letter of each segment.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.dashCase('helloWorld') // hello-world
string.dashCase('helloWorld', { capitalize: true }) // Hello-World
string.seconds.parse('10h') // 36000
string.seconds.parse('1 day') // 86400
```
#### pascalCase
Passing a numeric value to the `parse` method is returned as it is, assuming the value is already in seconds.
Convert a string to its `PascalCase` version.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.pascalCase('helloWorld') // HelloWorld
string.seconds.parse(180) // 180
```
#### capitalCase
You can format seconds to a pretty string using the `format` method.
Capitalize a string
```ts
import { string } from '@poppinss/utils/build/helpers'
string.capitalCase('helloWorld') // Hello World
string.seconds.format(36000) // 10h
string.seconds.format(36000, true) // 10 hours
```
#### sentenceCase
#### milliseconds.(parse/format)
Parse a string-based time expression to milliseconds.
Convert string to a sentence
```ts
import { string } from '@poppinss/utils/build/helpers'
string.sentenceCase('hello-world') // Hello world
string.milliseconds.parse('1 h') // 3.6e6
string.milliseconds.parse('1 day') // 8.64e7
```
#### dotCase
Passing a numeric value to the `parse` method is returned as it is, assuming the value is already in milliseconds.
Convert string to its `dot.case` version.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.dotCase('hello-world') // hello.world
string.milliseconds.parse(180) // 180
```
#### noCase
Using the `format` method, you can format milliseconds to a pretty string.
Remove all sorts of casing
```ts
import { string } from '@poppinss/utils/build/helpers'
string.noCase('hello-world') // hello world
string.noCase('hello_world') // hello world
string.noCase('helloWorld') // hello world
string.seconds.format(3.6e6) // 1h
string.seconds.format(3.6e6, true) // 1 hour
```
#### titleCase
#### bytes.(parse/format)
Parse a string-based unit expression to bytes.
Convert a sentence to title case
```ts
import { string } from '@poppinss/utils/build/helpers'
string.titleCase('Here is a fox') // Here Is a fox
string.bytes.parse('1KB') // 1024
string.bytes.parse('1MB') // 1048576
```
#### pluralize
Passing a numeric value to the `parse` method is returned as it is, assuming the value is already in bytes.
Pluralize a word.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.pluralize('box') // boxes
string.pluralize('i') // we
string.bytes.parse(1024) // 1024
```
You can also define your own irregular rules using the `string.defineIrregularRule` method.
Using the `format` method, you can format bytes to a pretty string. The method is exported directly from the [bytes](https://www.npmjs.com/package/bytes) package. Please reference the package README for available options.
- The first argument is the singular variation
- The second argument is the plural variation
```ts
import { string } from '@poppinss/utils/build/helpers'
string.defineIrregularRule('auth', 'auth')
string.plural('auth') // auth
string.bytes.format(1048576) // 1MB
string.bytes.format(1024 * 1024 * 1000) // 1000MB
string.bytes.format(1024 * 1024 * 1000, { thousandsSeparator: ',' }) // 1,000MB
```
You can also define your own uncountable rules using the `string.defineUncountableRule` method.
### JSON helpers
Following are the helpers we use to `stringify` and `parse` JSON.
```ts
import { string } from '@poppinss/utils/build/helpers'
#### safeParse
The native implementation of `JSON.parse` opens up the possibility for [prototype poisoning](https://medium.com/intrinsic-blog/javascript-prototype-poisoning-vulnerabilities-in-the-wild-7bc15347c96). The `safeParse` method removes the `__proto__` and the `constructor.prototype` properties from the JSON string at the time of parsing it.
string.defineUncountableRule('login')
string.plural('login') // home
```
The method is a wrapper over [secure-json-parse](https://github.com/fastify/secure-json-parse) package.
#### truncate
#### safeStringify
The native implementation of `JSON.stringify` cannot handle circular references or language-specific data types like `BigInt`.
Truncate a string after a given number of characters
Therefore, we use the [safe-stable-stringify](https://github.com/BridgeAR/safe-stable-stringify) package under the hood to overcome the limitations of native implementation.
```ts
import { string } from '@poppinss/utils/build/helpers'
import { safeStringify } from '@poppinss/utils/json'
string.truncate('This is a very long, maybe not that long title', 12) // This is a ve...
```
const value = {
b: 2,
c: BigInt(10),
}
By default, the string is truncated exactly after the given characters. However, you can instruct the method to wait for the words to complete.
// Circular reference
value.a = value
```ts
string.truncate('This is a very long, maybe not that long title', 12, {
completeWords: true,
}) // This is a very...
safeStringify(value)
// '{"b":2,"c":10}'
```
Also, it is possible to customize the suffix.
- The circular references are removed from the final JSON string.
- The BigInt values are converted to a string.
```ts
string.truncate('This is a very long, maybe not that long title', 12, {
completeWords: true,
suffix: ' <a href="/1"> Read more </a>',
}) // This is a very <a href="/1"> Read more </a>
```
The `safeStringify` API is the same as the `JSON.stringify` method.
#### excerpt
- You can pass a replacer function as the second parameter.
- And number of spaces as the third parameter.
The `excerpt` method is same as the `truncate` method. However, it strips the HTML from the string.
### Lodash helpers
Lodash is quite a big library, and we do not use all its helper methods. Therefore we create a custom build using the lodash CLI and bundle only the once we need.
```ts
import { string } from '@poppinss/utils/build/helpers'
> **Why not use something else**: All other helpers I have used are not as accurate or well implemented as lodash.
string.excerpt('<p>This is a <strong>very long</strong>, maybe not that long title</p>', 12) // This is a very...
```
- pick
- omit
- has
- get
- set
- unset
- mergeWith
- merge
- size
- clone
- cloneDeep
- toPath
#### condenseWhitespace
You can use the methods as follows.
Condense whitespaces from a given string. The method removes the whitespace from the `left`, `right` and multiple whitespace in between the words.
```ts
import { string } from '@poppinss/utils/build/helpers'
import lodash from '@poppinss/utils/lodash'
string.condenseWhitespace(' hello world ')
// hello world
lodash.pick(collection, keys)
```
#### escapeHTML
### All other helpers
The following helpers are exported from the package main module.
Escape HTML from the string
```ts
import { string } from '@poppinss/utils/build/helpers'
string.escapeHTML('<p> foo © bar </p>')
// &lt;p&gt; foo © bar &lt;/p&gt;
import { base64, compose } from '@poppinss/utils'
```
Additonally, you can also encode non-ascii symbols
#### base64
Utility methods to base64 encode and decode values.
```ts
import { string } from '@poppinss/utils/build/helpers'
import { base64 } from '@poppinss/utils'
string.escapeHTML('<p> foo © bar </p>', {
encodeSymbols: true,
})
// &lt;p&gt; foo &#xA9; bar &lt;/p&gt;
base64.encode('hello world')
// aGVsbG8gd29ybGQ=
```
#### encodeSymbols
Similar to the `encode` method, you can use the `urlEncode` to generate a base64 string safe to pass in a URL.
Encode symbols. Checkout [he](https://npm.im/he) for available options
The `urlEncode` method performs the following replacements.
- Replace `+` with `-`.
- Replace `/` with `_`.
- And remove the `=` sign from the end of the string.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.encodeSymbols('foo © bar')
// foo &#xA9; bar
base64.urlEncode('hello world')
// aGVsbG8gd29ybGQ
```
#### toSentence
You can use the `decode` and the `urlDecode` methods to decode a previously encoded base64 string.
Join an array of words with a separator.
```ts
import { string } from '@poppinss/utils/build/helpers'
base64.decode(base64.encode('hello world'))
// hello world
string.toSentence(['route', 'middleware', 'controller']) // route, middleware, and controller
string.toSentence(['route', 'middleware']) // route and middleware
base64.urlDecode(base64.urlEncode('hello world'))
// hello world
```
You can also customize
The `decode` and the `urlDecode` methods return `null` when the input value is an invalid base64 string. You can turn on the `strict` mode to raise an exception instead.
- `separator`: The value between two words except the last one
- `pairSeparator`: The value between the first and the last word. Used, only when there are two words
- `lastSeparator`: The value between the second last and the last word. Used, only when there are more than two words
```ts
string.toSentence(['route', 'middleware', 'controller'], {
separator: '/ ',
lastSeparator: '/or ',
}) // route/ middleware/or controller
base64.decode('hello world') // null
base64.decode('hello world', 'utf-8', true) // raises exception
```
#### prettyBytes
#### compose
The `compose` helper allows you to use TypeScript class mixins with a cleaner API. Following is an example of mixins usage without the compose helper.
Convert bytes value to a human readable string. For options, recommend the [bytes](https://www.npmjs.com/package/bytes) package.
```ts
import { string } from '@poppinss/utils/build/helpers'
string.prettyBytes(1024) // 1KB
string.prettyBytes(1024, { unitSeparator: ' ' }) // 1 KB
class User extends UserWithAttributes(
UserWithAge(
UserWithPassword(
UserWithEmail(BaseModel)
)
)
) {}
```
#### toBytes
Following is an example with the `compose` helper.
Convert human readable string to bytes. This method is the opposite of the `prettyBytes` method.
- There is no nesting.
- The order of mixins is from left to right. Whereas earlier, it was inside out.
```ts
import { string } from '@poppinss/utils/build/helpers'
import { compose } from '@poppinss/utils'
string.toBytes('1KB') // 1024
class User extends compose(
BaseModel,
UserWithEmail,
UserWithPassword,
UserWithAge,
UserWithAttributes
) {}
```
#### prettyMs
#### defineStaticProperty
The `defineStaticProperty` method allows you to define static properties on a class with different reference strategies.
Convert time in milliseconds to a human readable string
If you use class inheritance alongside static properties, then either, you will share properties by reference, or you will define them directly on the parent class.
In the following example, we are not inherting `columns` from the `AppModel`. Instead, we define a new set of columns on the `UserModel`.
```ts
import { string } from '@poppinss/utils/build/helpers'
class AppModel {
static columns = ['id']
}
string.prettyMs(60000) // 1min
string.prettyMs(60000, { long: true }) // 1 minute
class UserModel extends AppModel {
static columns = ['username']
}
```
#### toMs
In the following example, we are inherting `columns` from the `AppModel`. However, the mutations (array.push) from the `UserModel` will reflect on the `AppModel` as well.
Convert human readable string to milliseconds. This method is the opposite of the `prettyMs` method.
```ts
import { string } from '@poppinss/utils/build/helpers'
class AppModel {
static columns = ['id']
}
string.toMs('1min') // 60000
class UserModel extends AppModel {}
UserModel.columns.push('username')
```
#### ordinalize
The ideal behavior is to deep clone the `columns` array and then push new values to it.
Ordinalize a string or a number value
```ts
import { string } from '@poppinss/utils/build/helpers'
import lodash from '@poppinss/utils/lodash'
string.ordinalize(1) // 1st
string.ordinalize(99) // 99th
class AppModel {
static columns = ['id']
}
const inheritedColumns = lodash.cloneDeep(AppModel.columns)
class UserModel extends AppModel {
static columns = inheritedColumns.push('username')
}
```
#### generateRandom
The `defineStaticProperty` method abstracts the logic to clone and also performs some interal checks to see if the value is already defined as an `ownProperty` or not.
Generate a cryptographically strong random string
```ts
import { string } from '@poppinss/utils/build/helpers'
class UserModel extends AppModel {
}
string.generateRandom(32)
defineStaticProperty(UserModel, 'columns', {
strategy: 'inherit',
initialValue: [],
})
```
#### isEmpty
- The `inherit` strategy clones the value from the parent class.
- The `define` strategy always re-defines the property, discarding any values on the parent class.
- The `strategy` value can be function to perform a custom clone operations.
Find if a value is empty. Also checks for empty strings with all whitespace
#### Exception
A custom exception class with support for defining the error status, error code, and help description. This class aims to standardize exceptions within your projects.
```ts
import { string } from '@poppinss/utils/build/helpers'
import { Exception } from '@poppinss/utils'
string.isEmpty('') // true
string.isEmpty(' ') // true
class ResourceNotFound extends Exception {
static code = 'E_RESOURCE_NOT_FOUND'
static status = 404
static message = 'Unable to find resource'
}
throw new ResourceNotFound()
```
### Types
Following is an example of creating a dynamic message with interpolation.
The types module allows distinguishing between different Javascript datatypes. The `typeof` returns the same type for many different values. For example:
```ts
typeof {} // object
typeof [] // object
typeof null // object
```
import { Exception } from '@poppinss/utils'
import string from '@poppinss/utils/string'
WHAT??? Yes, coz everything is an object in Javascript. To have better control, you can make use of the `types.lookup` method.
class ResourceNotFound extends Exception {
static code = 'E_RESOURCE_NOT_FOUND'
static status = 404
static message = 'Unable to find resource with id {{ id }}'
}
#### lookup
throw new ResourceNotFound(
interpolate(ResourceNotFound.message, { id: 1 })
)
```
Returns a more accurate type for a given value.
#### flatten
Create a flat object from a nested object/array. The nested keys are combined with a dot-notation (`.`). The method is exported from the [flattie](https://www.npmjs.com/package/flattie) package.
```ts
import { types } from '@poppinss/utils/build/helpers'
import { flatten } from '@poppinss/utils'
types.lookup({}) // object
types.lookup([]) // array
types.lookup(Object.create(null)) // object
types.lookup(null) // null
types.lookup(function () {}) // function
types.lookup(class Foo {}) // class
types.lookup(new Map()) // map
flatten({
a: 'hi',
b: {
a: null,
b: ['foo', '', null, 'bar'],
d: 'hello',
e: {
a: 'yo',
b: undefined,
c: 'sup',
d: 0,
f: [
{ foo: 123, bar: 123 },
{ foo: 465, bar: 456 },
]
}
},
c: 'world'
})
// {
// 'a': 'hi',
// 'b.b.0': 'foo',
// 'b.b.1': '',
// 'b.b.3': 'bar',
// 'b.d': 'hello',
// 'b.e.a': 'yo',
// 'b.e.c': 'sup',
// 'b.e.d': 0,
// 'b.e.f.0.foo': 123,
// 'b.e.f.0.bar': 123,
// 'b.e.f.1.foo': 465,
// 'b.e.f.1.bar': 456,
// 'c': 'world'
// }
```
#### isNull
#### fsReadAll
Get a list of all the files from a directory. The method recursively fetches files from the main and the sub-folders. The dotfiles are ignored implicitly.
Find if the given value is null
```ts
import { types } from '@poppinss/utils/build/helpers'
import { fsReadAll } from '@poppinss/utils'
types.isNull(null)) // true
const files = await fsReadAll(
new URL('./config', import.meta.url),
{ pathType: 'url' }
)
await Promise.all(files.map((file) => import(file)))
```
#### isBoolean
You can also pass the options along with the directory path as the second argument.
Find if the given value is a boolean
```ts
import { types } from '@poppinss/utils/build/helpers'
type Options = {
ignoreMissingRoot?: boolean
filter?: (filePath: string, index: number) => boolean
sort?: (current: string, next: string) => number
pathType?: 'relative' | 'unixRelative' | 'absolute' | 'unixAbsolute' | 'url'
}
types.isBoolean(true)) // true
const options: Partial<Options> = {}
await fsReadAll(location, options)
```
#### isBuffer
| Argument | Type | Description |
|---------|------|---------------|
| `ignoreMissingRoot` | boolean | By default, an exception is raised when the root directory is missing. Setting `ignoreMissingRoot` to true will not result in an error and an empty array is returned back. |
| `filter` | method | Define a filter to ignore certain paths. The method is called on the final list of files. |
| `sort` | method | Define a custom method to sort file paths. By default, the files are sorted using natural sort. |
| `pathType` | enum | Define how to return the collected paths. By default, OS-specific relative paths are returned. If you want to import the collected files, you must set the `pathType = 'url'` |
Find if the given value is a buffer
#### fsImportAll
The `fsImportAll` method imports all the files recursively from a given directory and set the exported value from each module on an object.
```ts
import { types } from '@poppinss/utils/build/helpers'
import { fsImportAll } from '@poppinss/utils'
types.isBuffer(new Buffer())) // true
const collection = await fsImportAll(new URL('./config', import.meta.url))
console.log(collection)
```
#### isNumber
- Collection is an object with a tree of key-value pair.
- The key is the nested object created from the file path.
- Value is the exported values from the module. If a module exports both the `default` and `named` values, then only the default values are used.
Find if the given value is a number
The second param is the options to customize the import behavior.
```ts
import { types } from '@poppinss/utils/build/helpers'
| Argument | Type | Description |
|---------|------|---------------|
| `ignoreMissingRoot` | boolean | By default, an exception is raised when the root directory is missing. Setting `ignoreMissingRoot` to true will not result in an error and an empty object is returned back. |
| `filter` | method | Define a filter to ignore certain paths. By default only files ending with `.js`, `.ts`, `.json`, `.cjs`, and `.mjs` are imported. |
| `sort` | method | Define a custom method to sort file paths. By default, the files are sorted using natural sort. |
| `transformKeys` | method | Define a callback method to transform the keys for the final object. The method receives an array of nested keys and must return an array back. |
types.isNumber(100)) // true
```
#### isScriptFile
A filter to know if the file path ends with `.js`, `.json`, `.cjs`, `.mjs` or `.ts`. In the case of `.ts` files, the `.d.ts` returns false.
#### isString
```ts
import { isScriptFile } from '@poppinss/utils'
Find if the given value is a string
isScriptFile('foo.js') // true
isScriptFile('foo/bar.cjs') // true
isScriptFile('foo/bar.mjs') // true
isScriptFile('foo.json') // true
```ts
import { types } from '@poppinss/utils/build/helpers'
types.isString('hello')) // true
isScriptFile('foo/bar.ts') // true
isScriptFile('foo/bar.d.ts') // false
```
#### isArguments
The goal of this method is to use it as a filter with the `fsReadAll` method.
Find if the given value is an arguments object
```ts
import { types } from '@poppinss/utils/build/helpers'
import { fsReadAll, isScriptFile } from '@poppinss/utils'
function foo() {
types.isArguments(arguments)) // true
}
```
const dir = new URL('./config', import.meta.url)
const options = { pathType: 'url', filter: isScriptFile }
#### isObject
const files = await fsReadAll(dir, options)
Find if the given value is a plain object
await Promise.all(files.map((file) => {
if (file.endsWith('.json')) {
return import(file, { assert: { type: 'json' } })
}
```ts
import { types } from '@poppinss/utils/build/helpers'
types.isObject({})) // true
return import(file)
}))
```
#### isDate
#### naturalSort
A sorting function to use natural sort for ordering an array.
Find if the given value is a date object
```ts
import { types } from '@poppinss/utils/build/helpers'
import { naturalSort } from '@poppinss/utils'
types.isDate(new Date())) // true
const values = ['1_foo_bar', '12_foo_bar'].sort()
// Default sorting: ['12_foo_bar', '1_foo_bar']
const values = ['1_foo_bar', '12_foo_bar'].sort(naturalSort)
// Default sorting: ['1_foo_bar', '12_foo_bar']
```
#### isArray
#### safeEqual
Check if two buffer or string values are the same. This method does not leak any timing information and prevents [timing attack](https://javascript.plainenglish.io/what-are-timing-attacks-and-how-to-prevent-them-using-nodejs-158cc7e2d70c).
Find if the given value is an array
Under the hood, this method uses Node.js [crypto.timeSafeEqual](https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b) method, with support for comparing string values. *(crypto.timeSafeEqual does not support string comparison)*
```ts
import { types } from '@poppinss/utils/build/helpers'
import { safeEqual } from '@poppinss/utils'
types.isArray([1, 2, 3])) // true
```
/**
* The trusted value, it might be saved inside the db
*/
const trustedValue = 'hello world'
#### isRegexp
/**
* Untrusted user input
*/
const userInput = 'hello'
Find if the given value is an regular expression
```ts
import { types } from '@poppinss/utils/build/helpers'
types.isRegexp(/[a-z]+/)) // true
if (safeEqual(trustedValue, userInput)) {
// both are same
} else {
// value mis-match
}
```
#### isError
#### slash
Convert OS-specific file paths to Unix file paths. The method is exported directly from the [slash](https://npm.im/slash) package.
Find if the given value is an instance of the error object
```ts
import { types } from '@poppinss/utils/build/helpers'
import { Exception } from '@poppinss/utils'
types.isError(new Error('foo'))) // true
types.isError(new Exception('foo'))) // true
import { slash } from '@poppinss/utils'
slash('foo\\bar') // foo/bar
```
#### isFunction
#### MessageBuilder
Message builder is a convenience layer to stringify JavaScript values with an expiry date and a purpose. For example:
Find if the given value is a function
```ts
import { types } from '@poppinss/utils/build/helpers'
import { MessageBuilder } from '@poppinss/utils'
types.isFunction(function foo() {})) // true
const builder = new MessageBuilder()
const encoded = builder.build(
{
token: string.random(32),
},
'1 hour',
'email_verification'
)
/**
* {
* "message": {
* "token":"GZhbeG5TvgA-7JCg5y4wOBB1qHIRtX6q"
* },
* "purpose":"email_verification",
* "expiryDate":"2022-10-03T04:07:13.860Z"
* }
*/
```
#### isClass
Once you have the JSON string with the expiry and the purpose, you can encrypt it (to prevent tampering) and share it with the client.
Find if the given value is a class constructor. Uses regex to distinguish between a function and a class.
During the email verification, you can decrypt the key and then ask the `MessageBuilder` to verify the payload.
```ts
import { types } from '@poppinss/utils/build/helpers'
const decoded = builder.verify(value, 'email_verification')
if (!decoded) {
return 'Invalid token'
}
class User {}
types.isClass(User) // true
types.isFunction(User) // true
console.log(decoded.token)
```
#### isInteger
Now let's imagine someone presents the same token to reset their account password. In the following example, the validation will fail since the purpose of the original token is not the same as the purpose set during the `verify` method call.
Find if the given value is an integer.
```ts
import { types } from '@poppinss/utils/build/helpers'
types.isInteger(22.0) // true
types.isInteger(22) // true
types.isInteger(-1) // true
types.isInteger(-1.0) // true
types.isInteger(22.1) // false
types.isInteger(0.3) // false
types.isInteger(-0.3) // false
const decoded = builder.verify(value, 'reset_password')
```
#### isFloat
#### ObjectBuilder
The `ObjectBuilder` is a convenience class to create an object with dynamic properties. Consider the following example, where we wrap our code inside conditionals before adding the property `b` to the `startingObject`.
Find if the given value is an float number.
```ts
import { types } from '@poppinss/utils/build/helpers'
const startingObject = {
a: 1
// Add "b", if it exists
...(b ? { b } : {})
}
types.isFloat(22.1) // true
types.isFloat(-22.1) // true
types.isFloat(0.3) // true
types.isFloat(-0.3) // true
types.isFloat(22.0) // false
types.isFloat(-22.0) // false
types.isFloat(-22) // false
// OR
if (b) {
startingObject.b = b
}
```
#### isDecimal
Instead of writing conditionals, your can consider using the Object builder fluent API.
Find if the given value has a decimal. The value can be a string or a number. The number values are casted to a string by calling the `toString()` method on the value itself.
The string conversion is peformed to test the value against a regex. Since, there is no way to natively find a decimal value in Javascript.
```ts
import { types } from '@poppinss/utils/build/helpers'
const builder = new ObjectBuilder({ a: 1 })
types.isDecimal('22.10') // true
types.isDecimal(22.1) // true
// Add property if the value is not undefined.
builder.add('b', b)
types.isDecimal('-22.10') // true
types.isDecimal(-22.1) // true
types.isDecimal('.3') // true
types.isDecimal(0.3) // true
types.isDecimal('-.3') // true
types.isDecimal(-0.3) // true
types.isDecimal('22.00') // true
types.isDecimal(22.0) // false (gets converted to 22)
types.isDecimal('-22.00') // true
types.isDecimal(-22.0) // false (gets converted to -22)
types.isDecimal('22') // false
types.isDecimal(22) // false
types.isDecimal('0.0000000000001') // true
types.isDecimal(0.0000000000001) // false (gets converted to 1e-13)
// Get the plain object back
const plainObject = builder.toObject()
```
### ObjectBuilder
By default, only the `undefined` values are ignored. However, you can also ignore `null` values.
A very simple class to conditionally builder an object. Quite often, I create a new object from an existing one and wants to avoid writing undefined values to it. For example
```ts
const obj = {
...(user.username ? { username: user.username } : {}),
...(user.id ? { id: user.id } : {}),
...(user.createdAt ? { createdAt: user.createdAt.toString() } : {}),
}
const ignoreNullValues = true
const builder = new ObjectBuilder({ a: 1 }, ignoreNullValues)
```
Not only the above code is harder to write. It is performance issues as well, since we are destructuring too many objects.
Following are the available methods on the `ObjectBuilder` class.
To address this use case, you can make use of the `ObjectBuilder` class as follows
```ts
import { ObjectBuilder } from '@poppinss/utils/build/helpers'
builder.remove(key)
builder.has(key)
builder.get(key)
builder.add(key)
const obj = new ObjectBuilder()
.add('username', user.username)
.add('id', user.id)
.add('createdAt', user.createdAt && user.createdAt.toString()).value // returns the underlying object
builder.toObject() // get plain object
```
The `add` method ignores the value if its `undefined`. So it never gets added to the object at all. You can also ignore `null` properties by passing a boolean flag to the constructor.
#### dirname/filename
ES modules does not have magic variables `__filename` and `__dirname`. You can use these helpers to get the current directory and filenames as follows.
```ts
new ObjectBuilder(true) // ignore null as well
import { getDirname, getFilename } from '@poppinss/utils'
const dirname = getDirname(import.meta.url)
const filename = getFilename(import.meta.url)
```

@@ -1264,0 +1052,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc