| name | rattail |
| description | Guides use of the rattail front-end toolchain: utilities (array, object, string, math, DOM, file, function, collection, integrated), CLI (rt: clean, api, hook, release, changelog, commit-lint, lockfile-check), axle HTTP client (rattail/axle), ruler-factory validation (rattail/ruler-factory), and vite-plus lint/fmt configuration (rattail/vite-plus). |
| license | MIT |
Rattail
A Vite+ oriented, AI Agent friendly front-end toolchain from rattail. All utilities, integrations, and CLI are published under one rattail package.
IMPORTANT: For each API, open the corresponding references/<name>.md (see tables below). Those files mirror the VitePress docs (usage, arguments, return), link to the official English and Chinese pages on rattail.varletjs.org, and include the corresponding src/**/*.ts excerpt as type declarations.
CLI (rt)
Binary name: rt (registered via package.json → dist/cli/bin.mjs). Built with Commander. Unifies release, changelog, commit-lint, API generation, hook management, cleanup, and lockfile checking into a single CLI.
Configuration: All CLI commands read from the rattail key inside vite.config.ts (loaded via unconfig). See references/cli/configuration.md.
Commands
Quick start
import { defineConfig } from 'rattail/vite-plus'
export default defineConfig({
rattail: {
clean: ['dist', 'coverage'],
hook: {
'commit-msg': ['rt commit-lint $1'],
},
api: {
input: './schema.yaml',
output: './src/apis/generated',
preset: 'axle',
},
release: {
},
changelog: {
},
},
})
Programmatic usage
All CLI commands are also available as functions:
import { clean, api, hook, release, changelog, commitLint, lockfileCheck } from 'rattail/cli'
Core functions
Import from rattail:
import { isString, debounce, cloneDeep } from 'rattail'
General
| Function | Description |
|---|
isString | Determine whether the input value is a string. |
isNumber | Determine whether the input value is a number. |
isNumeric | Determine whether the input value is a number or a numeric string. |
isBoolean | Determine whether the input value is a boolean. |
isTruthy | Determine whether the input value is truthy. |
isPrimitive | Determine whether the input value is a primitive. |
isPlainObject | Determine whether the input value is a plain object. |
isObject | Determine whether the input value is an object (excluding null). |
isArray | Determine whether the input value is an array. |
isNullish | Determine whether the input value is null or undefined. |
isPromise | Determine whether the input value is a Promise. |
isRegExp | Determine whether the input value is a RegExp. |
isFunction | Determine whether the input value is a function. |
isDate | Determine whether the input value is a Date. |
isSet | Determine whether the input value is a Set. |
isMap | Determine whether the input value is a Map. |
isSymbol | Determine whether the input value is a symbol. |
isWeakMap | Determine whether the input value is a WeakMap. |
isWeakSet | Determine whether the input value is a WeakSet. |
isBlob | Determine whether the input value is a Blob. |
isFile | Determine whether the input value is a File. |
isArrayBuffer | Determine whether the input value is a ArrayBuffer. |
isTypedArray | Determine whether the input value is a TypedArray. |
isDataView | Determine whether the input value is a DataView. |
isError | Determine whether the input value is an Error object. |
isDOMException | Determine whether the input value is a DOMException object. |
isWindow | Determine whether the input value is the global window object. |
isEmpty | Determine whether the input value is empty (undefined, null, an empty string, or an empty array). |
isEmptyPlainObject | Determine whether the input value is a empty (no own enumerable keys and no symbols) plain object. |
isNonEmptyArray | Determine whether the input value is a non-empty array. |
isEqual | Deeply compare two values. |
isEqualWith | Deeply compare two values. Supports passing a comparison method, and returns true if the two values are equal. |
inBrowser | Determine whether the code is running in a browser environment. |
inMobile | Determine whether the code is running in a mobile browser environment. |
hasOwn | Determine whether an object has a specific property as its own (not inherited). |
hasDuplicates | Checks if an array contains duplicate values. |
hasDuplicatesBy | Checks if an array contains duplicate values based on a custom comparison function. |
supportTouch | Determine whether the current environment supports touch events. |
toTypeString | Return the type string of the input value. |
toRawType | Return the raw type of the input value. |
getGlobalThis | Retrieve the global object based on the current environment. |
assert | Throws an error when the input value is not true, the second argument is the error message. |
Number
| Function | Description |
|---|
toNumber | Convert the input value to a number. If the value is null or undefined, it returns 0. |
genNumberKey | Generate a unique numeric key, incrementing with each call. |
randomNumber | Generate a random integer between min and max, inclusive. |
clamp | Clamp a number within the inclusive min and max bounds. |
clampArrayRange | Clamp an index within the bounds of an array's length. |
times | Execute a function a specified number of times and return an array of results. |
delay | Create a promise that resolves after a specified time in milliseconds. |
String
| Function | Description |
|---|
randomString | Generate a random alphanumeric string of a specified length. |
randomColor | Generate a random hexadecimal color string. |
genStringKey | Generate a unique string key by incrementing a numeric value and converting it to a string. |
camelize | Convert a string to camelCase. |
kebabCase | Convert a string to kebab-case. |
pascalCase | Convert a string to PascalCase. |
upperFirst | Capitalize the first letter of a string, leaving the rest unchanged. |
lowerFirst | Lowercase the first letter of the string and keep the rest unchanged. |
slash | Convert all backslashes (\) in a path to forward slashes (/). |
ensurePrefix | Ensure that a prefix exists in the string, and add it if it does not exist. |
ensureSuffix | Ensure that a suffix exists in the string, and add it if it does not exist. |
maskString | Mask part of a string with a specified character, keeping prefix and suffix visible. |
Math
| Function | Description |
|---|
sum | Calculates the sum of values in an array of numbers. |
sumBy | Calculates the sum of values in an array based on a provided function. |
sumHash | Calculate a hash sum for a given value. |
minBy | Find the minimum value in an array based on a function applied to each element. |
maxBy | Find the maximum value in an array based on a function applied to each element. |
mean | Calculate the mean (average) of an array of numbers. |
meanBy | Calculate the mean (average) of an array by applying a function to each element. |
sample | Return a random element from an array. |
round | Return number rounded to precision. |
floor | Return number rounded down to precision. |
ceil | Return number rounded up to precision. |
Object
| Function | Description |
|---|
set | Set a value at a given path in an object, creating nested objects or arrays as needed. |
pick | Pick object properties and construct a new object. |
pickBy | Extract object properties by a predicate function and construct a new object. |
omit | Excludes object properties and constructs a new object. |
omitBy | Excludes object properties by a predicate function and constructs a new object. |
deriveKey | Derive new object keys by a mapping while keeping the original keys. |
mapObject | Maps an object into a new object. |
rekey | Rename object keys by a mapping and construct a new object. |
objectKeys | Get an array of keys from an object, with full TypeScript type support. |
objectEntries | Get an array of key-value pairs from an object, with full TypeScript type support. |
promiseWithResolvers | Returns an object containing a new Promise and two functions to resolve or reject it. |
Array
| Function | Description |
|---|
at | Retrieves the element at a specified index in an array, supporting negative indices. |
chunk | Chunking an array. The passed size indicates the length of the chunk. |
uniq | Creates a duplicate-free version of an array, using the values equality. |
uniqBy | Creates a duplicate-free version of an array, using a custom comparison function. |
difference | Creates an array of values not contained in other given arrays. |
differenceWith | Creates an array of values not contained in other given arrays, with custom comparison. |
intersection | Creates an array of unique values contained in all given arrays. |
intersectionWith | Creates an array of unique values contained in all given arrays, with custom comparison. |
xor | XOR (Exclusive OR) the passed array and return a new array. |
xorWith | XOR (Exclusive OR) the passed array with custom comparison. |
groupBy | Group the elements in a given array by a function's return value as the key. |
find | Finds the first or last element in an array that meets a condition, returning the element and its index. |
shuffle | Randomly shuffles elements within an array. |
removeItem | Removes the first occurrence of a specific item from an array. |
removeItemBy | Removes the first item matching a predicate, mutating the original array. |
removeItemsBy | Removes all items matching a predicate, mutating the original array. |
toggleItem | Adds or removes an item from an array, based on its existence. |
removeArrayBlank | Removes null or undefined values from an array. |
removeArrayEmpty | Removes null, undefined, or empty string ('') values from an array. |
normalizeToArray | Converts a value to an array if it is not already an array. |
Collection
| Function | Description |
|---|
cloneDeep | Create a deep clone of a value. |
cloneDeepWith | Create a deep clone of a value, applying a custom function for cloning. |
merge | Merge two objects recursively. |
mergeWith | Merge two objects recursively, with custom merge logic. |
Function
| Function | Description |
|---|
NOOP | This method returns undefined. |
call | Call a single function or multiple functions and pass arguments to them. |
callOrReturn | Calls a function with args if input is a function, otherwise returns the input directly. |
once | Creates a function that will only execute once. |
debounce | Create a debounce function that delays execution by delay ms after the last call. |
throttle | Create a throttle function that calls fn at most once every delay ms. |
tryCall | Safely call a function and return an [error, result] tuple. |
tryAsyncCall | Safely call an async function and return a Promise<[error, result]> tuple. |
File
| Function | Description |
|---|
toText | Converts a File object to a text string. |
toDataURL | Converts a File object to a Data URL string. |
toArrayBuffer | Converts a File object to an ArrayBuffer. |
Util
| Function | Description |
|---|
motion | Used to implement basic transition animation based on requestAnimationFrame. |
copyText | Copies text to the clipboard. |
download | Trigger browser download, supporting downloading via file url, Blob, File. |
duration | Creates a fluent duration builder that allows chaining time units to calculate total milliseconds or seconds. |
enumOf | Enum utility with TS-friendly types. Built-in fields: value, label, description. |
storage | Enhance localStorage and sessionStorage, support automatic JSON stringify and parse. |
classes | Generates a list of class names based on a given condition. |
createNamespaceFn | Creates a namespace function for BEM-style naming. |
createCacheManager | Creates a simple in-memory cache manager with optional TTL support. |
raf | Creates a Promise-based requestAnimationFrame that resolves on the next frame. |
doubleRaf | Creates a Promise-based double requestAnimationFrame that resolves after two frames. |
requestAnimationFrame | Provides a cross-browser compatible requestAnimationFrame function. |
cancelAnimationFrame | Cancels a requestAnimationFrame request, with a fallback to clearTimeout. |
inViewport | Determines if an element is visible within the viewport. |
preventDefault | Prevents the default action of an event if it is cancelable. |
getStyle | Retrieves computed CSS styles for a given DOM element. |
getRect | Gets the dimensions and position of an element or window as a DOMRect object. |
getScrollTop | Gets the vertical scroll position of an element or window. |
getScrollLeft | Gets the horizontal scroll position of an element or window. |
getParentScroller | Finds the closest scrollable ancestor of an element. |
getAllParentScroller | Retrieves all scrollable ancestor elements of an element. |
prettyJSONObject | Formats a JSON object with indentation for easy readability. |
tryParseJSON | Attempts to parse a JSON string. If parsing fails, returns undefined. |
navigation | Browser-level navigation API for real page jumps. |
Integrated
| Function | Description |
|---|
mitt | Event emitter / pubsub. Integrated with mitt. |
uuid | UUID generation helpers integrated with uuid. |
First-party integration: Axle (rattail/axle)
Progressive HTTP request layer on top of axios for Vue 3 (and plain JS for the core client), re-exported as a first-party integration. Three entry points:
| Entry | Import | Purpose |
|---|
| Core | rattail/axle | createAxle, types, createMatcher, helpers, interceptors |
| Vue | rattail/axle/use | createUseAxle, useValues, useHasLoading, useAverageProgress |
| API builder | rattail/axle/api | createApi — URL-bound load / use helpers |
Upstream: @varlet/axle · README · Chinese README
IMPORTANT: Open references/axle/<topic>.md for detailed API docs, type declarations, and usage examples.
Quick start
import { createAxle } from 'rattail/axle'
const axle = createAxle()
axle.get('/url', { current: 1, pageSize: 10 }, { headers: {} })
Topic references
| Topic | Reference |
|---|
createAxle, AxleInstance, shared axios, headers, runner overview | references/axle/core-client.md |
GET/POST/… runners (getBlob, postUrlEncode, …) | references/axle/request-runners.md |
createUseAxle and composables | references/axle/vue-composition.md |
createApi (load, use, path params) | references/axle/api-factory.md |
matchPattern, createMatcher, interceptors | references/axle/interceptors-and-matcher.md |
withResponse, download | references/axle/helpers.md |
Peer dependency: vue ^3.2 when using rattail/axle/use or rattail/axle/api.
First-party integration: Ruler Factory (rattail/ruler-factory)
Flexible chainable validation rule factory for TypeScript/JavaScript, re-exported as a first-party integration. Supports UI form integration with Varlet, Vant, Naive UI, Element Plus.
import { rulerFactory } from 'rattail/ruler-factory'
Upstream: ruler-factory · README · Chinese README
IMPORTANT: Before chaining rules, read the reference for rulerFactory and your UI's generator pattern, then open the specific references/ruler-factory/<name>.md for the method or type you use.
Quick start
import { rulerFactory } from 'rattail/ruler-factory'
const r = rulerFactory((validator) => {
return (value) => {
const e = validator(value)
return e ? e.message : true
}
})
r().string('Not a string').required('Required').min(2, 'Too short').done()
API index
Package
| Symbol | Description |
|---|
rulerFactory | Factory that builds a chainable ruler for your UI rule format. |
Exported types
Type guards
| Symbol | Description |
|---|
string | Assert string type (optional message). |
number | Assert number type. |
array | Assert array type. |
boolean | Assert boolean type. |
object | Assert plain object type. |
symbol | Assert symbol type. |
bigint | Assert bigint type. |
null | Assert value is null. |
undefined | Assert value is undefined. |
true | Assert value is true. |
false | Assert value is false. |
Validators
| Symbol | Description |
|---|
required | Reject empty values (rattail isEmpty). |
min | Min length / numeric min depending on type. |
max | Max length / numeric max depending on type. |
length | Exact length for string or array. |
regex | String matches RegExp. |
startsWith | String starts with prefix. |
endsWith | String ends with suffix. |
includes | Substring or array includes value. |
uppercase | String is all uppercase. |
lowercase | String is all lowercase. |
email | String looks like an email. |
gt | Number/bigint greater than. |
gte | Number/bigint greater or equal. |
lt | Number/bigint less than. |
lte | Number/bigint less or equal. |
positive | Number/bigint > 0. |
negative | Number/bigint < 0. |
uniq | Array has no duplicates. |
uniqBy | Array unique by comparator. |
Predicates
| Symbol | Description |
|---|
is | Custom predicate must pass. |
not | Custom predicate must fail. |
Finish
| Symbol | Description |
|---|
done | Return built rules array. |
Custom
| Symbol | Description |
|---|
addRule | Append custom validator. |
getMessage | Resolve message string/lazy fn. |
Transform
| Symbol | Description |
|---|
trim | Trim strings before validation. |
toLowerCase | Lowercase strings before validation. |
toUpperCase | Uppercase strings before validation. |
transform | Replace transformer with custom fn. |
transformer | Current transform pipeline (internal hook). |
First-party integration: Vite Plus (rattail/vite-plus)
Preset lint (oxlint) and format (oxfmt) configuration for projects using vite-plus, re-exported as a first-party integration.
import { lint, fmt } from 'rattail/vite-plus'
Upstream: @configurajs/vite-plus
Quick start
import { lint } from 'rattail/vite-plus'
export default lint()
import { fmt } from 'rattail/vite-plus'
export default fmt()
API index
| Symbol | Description |
|---|
lint | Creates an OxlintConfig with sensible defaults for TypeScript, Vue 3, and Vitest. |
fmt | Returns a preset oxfmt configuration object with opinionated defaults. |
Exported types
| Symbol | Description |
|---|
LintOptions | Options for lint(): ts, vue, react, vitest, rules, ignores, overrides. |
LintOptionsVue | Vue-specific options (version?: 2 | 3). |
CreateVueConfigOptions | Vue config options used by lint internally. |
OxlintConfig | The oxlint configuration object type. |
OxlintOverride | Override config for specific file patterns. |
DummyRule | Rule severity type (AllowWarnDeny or tuple). |