feature: vor und nachteile

This commit is contained in:
Hikyu
2026-05-31 13:54:31 +02:00
parent 552a947a1c
commit e3dad17446
23270 changed files with 3024794 additions and 200 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+27
View File
@@ -0,0 +1,27 @@
# install-pkg
[![NPM version](https://img.shields.io/npm/v/@antfu/install-pkg?color=a1b858&label=)](https://www.npmjs.com/package/@antfu/install-pkg)
Install package programmatically. Detect package managers automatically (`npm`, `yarn`, `bun` and `pnpm`).
```bash
npm i @antfu/install-pkg
```
```ts
import { installPackage } from '@antfu/install-pkg'
await installPackage('vite', { silent: true })
```
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021 [Anthony Fu](https://github.com/antfu)
+135
View File
@@ -0,0 +1,135 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
detectPackageManager: () => detectPackageManager,
installPackage: () => installPackage,
uninstallPackage: () => uninstallPackage
});
module.exports = __toCommonJS(index_exports);
// src/detect.ts
var import_node_process = __toESM(require("process"), 1);
var import_detect = require("package-manager-detector/detect");
async function detectPackageManager(cwd = import_node_process.default.cwd()) {
const result = await (0, import_detect.detect)({
cwd,
onUnknown(packageManager) {
console.warn("[@antfu/install-pkg] Unknown packageManager:", packageManager);
return void 0;
}
});
return result?.agent || null;
}
// src/install.ts
var import_node_fs = require("fs");
var import_node_path = require("path");
var import_node_process2 = __toESM(require("process"), 1);
var import_tinyexec = require("tinyexec");
async function installPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = (typeof options.additionalArgs === "function" ? options.additionalArgs(agent, detectedAgent) : options.additionalArgs) || [];
if (options.preferOffline) {
if (detectedAgent === "yarn@berry")
args.unshift("--cached");
else
args.unshift("--prefer-offline");
}
if (agent === "pnpm") {
args.unshift(
/**
* Prevent pnpm from removing installed devDeps while `NODE_ENV` is `production`
* @see https://pnpm.io/cli/install#--prod--p
*/
"--prod=false"
);
if ((0, import_node_fs.existsSync)((0, import_node_path.resolve)(options.cwd ?? import_node_process2.default.cwd(), "pnpm-workspace.yaml"))) {
args.unshift("-w");
}
}
return (0, import_tinyexec.x)(
agent,
[
agent === "yarn" ? "add" : "install",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
// src/uninstall.ts
var import_node_fs2 = require("fs");
var import_node_process3 = __toESM(require("process"), 1);
var import_node_path2 = require("path");
var import_tinyexec2 = require("tinyexec");
async function uninstallPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = options.additionalArgs || [];
if (agent === "pnpm" && (0, import_node_fs2.existsSync)((0, import_node_path2.resolve)(options.cwd ?? import_node_process3.default.cwd(), "pnpm-workspace.yaml")))
args.unshift("-w");
return (0, import_tinyexec2.x)(
agent,
[
agent === "yarn" ? "remove" : "uninstall",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
detectPackageManager,
installPackage,
uninstallPackage
});
+27
View File
@@ -0,0 +1,27 @@
import { Agent } from 'package-manager-detector';
export { Agent } from 'package-manager-detector';
import * as tinyexec from 'tinyexec';
type PackageManager = 'pnpm' | 'yarn' | 'npm' | 'bun';
declare function detectPackageManager(cwd?: string): Promise<Agent | null>;
interface InstallPackageOptions {
cwd?: string;
dev?: boolean;
silent?: boolean;
packageManager?: string;
preferOffline?: boolean;
additionalArgs?: string[] | ((agent: string, detectedAgent: string) => string[] | undefined);
}
declare function installPackage(names: string | string[], options?: InstallPackageOptions): Promise<tinyexec.Output>;
interface UninstallPackageOptions {
cwd?: string;
dev?: boolean;
silent?: boolean;
packageManager?: string;
additionalArgs?: string[];
}
declare function uninstallPackage(names: string | string[], options?: UninstallPackageOptions): Promise<tinyexec.Output>;
export { type InstallPackageOptions, type PackageManager, type UninstallPackageOptions, detectPackageManager, installPackage, uninstallPackage };
+27
View File
@@ -0,0 +1,27 @@
import { Agent } from 'package-manager-detector';
export { Agent } from 'package-manager-detector';
import * as tinyexec from 'tinyexec';
type PackageManager = 'pnpm' | 'yarn' | 'npm' | 'bun';
declare function detectPackageManager(cwd?: string): Promise<Agent | null>;
interface InstallPackageOptions {
cwd?: string;
dev?: boolean;
silent?: boolean;
packageManager?: string;
preferOffline?: boolean;
additionalArgs?: string[] | ((agent: string, detectedAgent: string) => string[] | undefined);
}
declare function installPackage(names: string | string[], options?: InstallPackageOptions): Promise<tinyexec.Output>;
interface UninstallPackageOptions {
cwd?: string;
dev?: boolean;
silent?: boolean;
packageManager?: string;
additionalArgs?: string[];
}
declare function uninstallPackage(names: string | string[], options?: UninstallPackageOptions): Promise<tinyexec.Output>;
export { type InstallPackageOptions, type PackageManager, type UninstallPackageOptions, detectPackageManager, installPackage, uninstallPackage };
+96
View File
@@ -0,0 +1,96 @@
// src/detect.ts
import process from "node:process";
import { detect } from "package-manager-detector/detect";
async function detectPackageManager(cwd = process.cwd()) {
const result = await detect({
cwd,
onUnknown(packageManager) {
console.warn("[@antfu/install-pkg] Unknown packageManager:", packageManager);
return void 0;
}
});
return result?.agent || null;
}
// src/install.ts
import { existsSync } from "node:fs";
import { resolve } from "node:path";
import process2 from "node:process";
import { x } from "tinyexec";
async function installPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = (typeof options.additionalArgs === "function" ? options.additionalArgs(agent, detectedAgent) : options.additionalArgs) || [];
if (options.preferOffline) {
if (detectedAgent === "yarn@berry")
args.unshift("--cached");
else
args.unshift("--prefer-offline");
}
if (agent === "pnpm") {
args.unshift(
/**
* Prevent pnpm from removing installed devDeps while `NODE_ENV` is `production`
* @see https://pnpm.io/cli/install#--prod--p
*/
"--prod=false"
);
if (existsSync(resolve(options.cwd ?? process2.cwd(), "pnpm-workspace.yaml"))) {
args.unshift("-w");
}
}
return x(
agent,
[
agent === "yarn" ? "add" : "install",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
// src/uninstall.ts
import { existsSync as existsSync2 } from "node:fs";
import process3 from "node:process";
import { resolve as resolve2 } from "node:path";
import { x as x2 } from "tinyexec";
async function uninstallPackage(names, options = {}) {
const detectedAgent = options.packageManager || await detectPackageManager(options.cwd) || "npm";
const [agent] = detectedAgent.split("@");
if (!Array.isArray(names))
names = [names];
const args = options.additionalArgs || [];
if (agent === "pnpm" && existsSync2(resolve2(options.cwd ?? process3.cwd(), "pnpm-workspace.yaml")))
args.unshift("-w");
return x2(
agent,
[
agent === "yarn" ? "remove" : "uninstall",
options.dev ? "-D" : "",
...args,
...names
].filter(Boolean),
{
nodeOptions: {
stdio: options.silent ? "ignore" : "inherit",
cwd: options.cwd
},
throwOnError: true
}
);
}
export {
detectPackageManager,
installPackage,
uninstallPackage
};
+58
View File
@@ -0,0 +1,58 @@
{
"name": "@antfu/install-pkg",
"type": "module",
"version": "1.1.0",
"description": "Install package programmatically.",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/install-pkg#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/install-pkg.git"
},
"bugs": {
"url": "https://github.com/antfu/install-pkg/issues"
},
"sideEffects": false,
"exports": {
".": {
"import": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
}
},
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"dependencies": {
"package-manager-detector": "^1.3.0",
"tinyexec": "^1.0.1"
},
"devDependencies": {
"@antfu/eslint-config": "^4.12.1",
"@antfu/ni": "^24.3.0",
"@types/node": "^22.15.12",
"bumpp": "^10.1.0",
"eslint": "^9.26.0",
"publint": "^0.3.12",
"tsup": "^8.4.0",
"tsx": "^4.19.4",
"typescript": "^5.8.3"
},
"scripts": {
"dev": "nr build --watch",
"start": "tsx src/index.ts",
"build": "tsup src/index.ts --format cjs,esm --dts --no-splitting",
"release": "bumpp --commit --push --tag && pnpm publish",
"lint": "eslint ."
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+323
View File
@@ -0,0 +1,323 @@
# ni
~~*`npm i` in a yarn project, again? F\*\*k!*~~
**ni** - use the right package manager
<br>
```
npm i -g @antfu/ni
```
<a href='https://docs.npmjs.com/cli/v6/commands/npm'>npm</a> · <a href='https://yarnpkg.com'>yarn</a> · <a href='https://pnpm.io/'>pnpm</a> · <a href='https://bun.sh/'>bun</a>
<br>
### `ni` - install
```bash
ni
# npm install
# yarn install
# pnpm install
# bun install
```
```bash
ni vite
# npm i vite
# yarn add vite
# pnpm add vite
# bun add vite
```
```bash
ni @types/node -D
# npm i @types/node -D
# yarn add @types/node -D
# pnpm add -D @types/node
# bun add -d @types/node
```
```bash
ni --frozen
# npm ci
# yarn install --frozen-lockfile (Yarn 1)
# yarn install --immutable (Yarn Berry)
# pnpm install --frozen-lockfile
# bun install --frozen-lockfile
```
```bash
ni -g eslint
# npm i -g eslint
# yarn global add eslint (Yarn 1)
# pnpm add -g eslint
# bun add -g eslint
# this uses default agent, regardless your current working directory
```
```bash
ni -i
# interactively select the dependency to install
# search for packages by name
```
<br>
### `nr` - run
```bash
nr dev --port=3000
# npm run dev -- --port=3000
# yarn run dev --port=3000
# pnpm run dev --port=3000
# bun run dev --port=3000
```
```bash
nr
# interactively select the script to run
# supports https://www.npmjs.com/package/npm-scripts-info convention
```
```bash
nr -
# rerun the last command
```
<br>
### `nlx` - download & execute
```bash
nlx vitest
# npx vitest
# yarn dlx vitest
# pnpm dlx vitest
# bunx vitest
```
<br>
### `nu` - upgrade
```bash
nu
# npm upgrade
# yarn upgrade (Yarn 1)
# yarn up (Yarn Berry)
# pnpm update
# bun update
```
```bash
nu -i
# (not available for npm & bun)
# yarn upgrade-interactive (Yarn 1)
# yarn up -i (Yarn Berry)
# pnpm update -i
```
<br>
### `nun` - uninstall
```bash
nun webpack
# npm uninstall webpack
# yarn remove webpack
# pnpm remove webpack
# bun remove webpack
```
```bash
nun
# interactively select
# the dependency to remove
```
```bash
nun -m
# interactive select,
# but with multiple dependencies
```
```bash
nun -g silent
# npm uninstall -g silent
# yarn global remove silent
# pnpm remove -g silent
# bun remove -g silent
```
<br>
### `nci` - clean install
```bash
nci
# npm ci
# yarn install --frozen-lockfile
# pnpm install --frozen-lockfile
# bun install --frozen-lockfile
```
if the corresponding node manager is not present, this command will install it globally along the way.
<br>
### `na` - agent alias
```bash
na
# npm
# yarn
# pnpm
# bun
```
```bash
na run foo
# npm run foo
# yarn run foo
# pnpm run foo
# bun run foo
```
<br>
### Global Flags
```bash
# ? | Print the command execution depends on the agent
ni vite ?
# -C | Change directory before running the command
ni -C packages/foo vite
nr -C playground dev
# -v, --version | Show version number
ni -v
# -h, --help | Show help
ni -h
```
<br>
### Config
```ini
; ~/.nirc
; fallback when no lock found
defaultAgent=npm # default "prompt"
; for global installs
globalAgent=npm
```
```bash
# ~/.bashrc
# custom configuration file path
export NI_CONFIG_FILE="$HOME/.config/ni/nirc"
# environment variables have higher priority than config file if presented
export NI_DEFAULT_AGENT="npm" # default "prompt"
export NI_GLOBAL_AGENT="npm"
```
```ps
# for Windows
# custom configuration file path in PowerShell accessible within the `$profile` path
$Env:NI_CONFIG_FILE = 'C:\to\your\config\location'
```
<br>
### Integrations
#### asdf
You can also install ni via the [3rd-party asdf-plugin](https://github.com/CanRau/asdf-ni.git) maintained by [CanRau](https://github.com/CanRau)
```bash
# first add the plugin
asdf plugin add ni https://github.com/CanRau/asdf-ni.git
# then install the latest version
asdf install ni latest
# and make it globally available
asdf global ni latest
```
### How?
**ni** assumes that you work with lockfiles (and you should)
Before it runs, it will detect your `yarn.lock` / `pnpm-lock.yaml` / `package-lock.json` / `bun.lockb` to know current package manager (or `packageManager` field in your packages.json if specified), and runs the [corresponding commands](https://github.com/antfu/ni/blob/main/src/agents.ts).
### Trouble shooting
#### Conflicts with PowerShell
PowerShell comes with a built-in alias `ni` for the `New-Item` cmdlet. To remove the alias in your current PowerShell session in favor of this package, use the following command:
```PowerShell
'Remove-Item Alias:ni -Force -ErrorAction Ignore'
```
If you want to persist the changes, you can add them to your PowerShell profile. The profile path is accessible within the `$profile` variable. The ps1 profile file can normally be found at
- PowerShell 5 (Windows PowerShell): `C:\Users\USERNAME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1`
- PowerShell 7: `C:\Users\USERNAME\Documents\PowerShell\Microsoft.PowerShell_profile.ps1`
- VSCode: `C:\Users\USERNAME\Documents\PowerShell\Microsoft.VSCode_profile.ps1`
You can use the following script to remove the alias at shell start by adding the above command to your profile:
```PowerShell
if (-not (Test-Path $profile)) {
New-Item -ItemType File -Path (Split-Path $profile) -Force -Name (Split-Path $profile -Leaf)
}
$profileEntry = 'Remove-Item Alias:ni -Force -ErrorAction Ignore'
$profileContent = Get-Content $profile
if ($profileContent -notcontains $profileEntry) {
("`n" + $profileEntry) | Out-File $profile -Append -Force -Encoding UTF8
}
```
#### `nx` and `nix` is no longer available
We renamed `nx`/`nix` to `nlx` to avoid conflicts with the other existing tools - [nx](https://nx.dev/) and [nix](https://nixos.org/). You can always alias them back on your shell configuration file (`.zshrc`, `.bashrc`, etc).
```bash
alias nx="nlx"
# or
alias nix="nlx"
```
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/na.mjs'
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/nci.mjs'
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/ni.mjs'
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/nlx.mjs'
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/nr.mjs'
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/nu.mjs'
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
'use strict'
import '../dist/nun.mjs'
+51
View File
@@ -0,0 +1,51 @@
'use strict';
const runner = require('./shared/ni.C82eau-4.cjs');
require('node:path');
require('node:process');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
exports.AGENTS = runner.AGENTS;
exports.CLI_TEMP_DIR = runner.CLI_TEMP_DIR;
exports.COMMANDS = runner.COMMANDS;
exports.INSTALL_PAGE = runner.INSTALL_PAGE;
exports.LOCKS = runner.LOCKS;
exports.UnsupportedCommand = runner.UnsupportedCommand;
exports.cmdExists = runner.cmdExists;
exports.constructCommand = runner.constructCommand;
exports.detect = runner.detect;
exports.exclude = runner.exclude;
exports.formatPackageWithUrl = runner.formatPackageWithUrl;
exports.getCliCommand = runner.getCliCommand;
exports.getCommand = runner.getCommand;
exports.getConfig = runner.getConfig;
exports.getDefaultAgent = runner.getDefaultAgent;
exports.getGlobalAgent = runner.getGlobalAgent;
exports.limitText = runner.limitText;
exports.parseNa = runner.parseNa;
exports.parseNi = runner.parseNi;
exports.parseNlx = runner.parseNlx;
exports.parseNr = runner.parseNr;
exports.parseNu = runner.parseNu;
exports.parseNun = runner.parseNun;
exports.remove = runner.remove;
exports.resolveCommand = runner.resolveCommand;
exports.run = runner.run;
exports.runCli = runner.runCli;
exports.serializeCommand = runner.serializeCommand;
exports.writeFileSafe = runner.writeFileSafe;
+129
View File
@@ -0,0 +1,129 @@
import { Buffer } from 'node:buffer';
type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno';
type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno';
type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null;
interface AgentCommands {
'agent': AgentCommandValue;
'run': AgentCommandValue;
'install': AgentCommandValue;
'frozen': AgentCommandValue;
'global': AgentCommandValue;
'add': AgentCommandValue;
'upgrade': AgentCommandValue;
'upgrade-interactive': AgentCommandValue;
'execute': AgentCommandValue;
'execute-local': AgentCommandValue;
'uninstall': AgentCommandValue;
'global_uninstall': AgentCommandValue;
}
type Command = keyof AgentCommands;
interface ResolvedCommand {
/**
* CLI command.
*/
command: string;
/**
* Arguments for the CLI command, merged with user arguments.
*/
args: string[];
}
declare const COMMANDS: {
npm: AgentCommands;
yarn: AgentCommands;
'yarn@berry': AgentCommands;
pnpm: AgentCommands;
'pnpm@6': AgentCommands;
bun: AgentCommands;
deno: AgentCommands;
};
/**
* Resolve the command for the agent merging the command arguments with the provided arguments.
*
* For example, to show how to install `@antfu/ni` globally using `pnpm`:
* ```js
* import { resolveCommand } from 'package-manager-detector/commands'
* const { command, args } = resolveCommand('pnpm', 'global', ['@antfu/ni'])
* console.log(`${command} ${args.join(' ')}`) // 'pnpm add -g @antfu/ni'
* ```
*
* @param agent The agent to use.
* @param command the command to resolve.
* @param args The arguments to pass to the command.
* @returns {ResolvedCommand} The resolved command or `null` if the agent command is not found.
*/
declare function resolveCommand(agent: Agent, command: Command, args: string[]): ResolvedCommand | null;
/**
* Construct the command from the agent command merging the command arguments with the provided arguments.
* @param value {AgentCommandValue} The agent command to use.
* @param args The arguments to pass to the command.
* @returns {ResolvedCommand} The resolved command or `null` if the command is `null`.
*/
declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null;
declare const AGENTS: Agent[];
declare const LOCKS: Record<string, AgentName>;
declare const INSTALL_PAGE: Record<Agent, string>;
interface Config {
defaultAgent: Agent | 'prompt';
globalAgent: Agent;
}
declare function getConfig(): Promise<Config>;
declare function getDefaultAgent(programmatic?: boolean): Promise<Agent | "prompt">;
declare function getGlobalAgent(): Promise<Agent>;
interface DetectOptions {
autoInstall?: boolean;
programmatic?: boolean;
cwd?: string;
/**
* Should use Volta when present
*
* @see https://volta.sh/
* @default true
*/
detectVolta?: boolean;
}
declare function detect({ autoInstall, programmatic, cwd }?: DetectOptions): Promise<Agent | undefined>;
interface RunnerContext {
programmatic?: boolean;
hasLock?: boolean;
cwd?: string;
}
type Runner = (agent: Agent, args: string[], ctx?: RunnerContext) => Promise<ResolvedCommand | undefined> | ResolvedCommand | undefined;
declare function runCli(fn: Runner, options?: DetectOptions & {
args?: string[];
}): Promise<void>;
declare function getCliCommand(fn: Runner, args: string[], options?: DetectOptions, cwd?: string): Promise<ResolvedCommand | undefined>;
declare function run(fn: Runner, args: string[], options?: DetectOptions): Promise<void>;
declare class UnsupportedCommand extends Error {
constructor({ agent, command }: {
agent: Agent;
command: Command;
});
}
declare function getCommand(agent: Agent, command: Command, args?: string[]): ResolvedCommand;
declare const parseNi: Runner;
declare const parseNr: Runner;
declare const parseNu: Runner;
declare const parseNun: Runner;
declare const parseNlx: Runner;
declare const parseNa: Runner;
declare function serializeCommand(command?: ResolvedCommand): string | undefined;
declare const CLI_TEMP_DIR: string;
declare function remove<T>(arr: T[], v: T): T[];
declare function exclude<T>(arr: T[], ...v: T[]): T[];
declare function cmdExists(cmd: string): boolean;
/**
* Write file safely avoiding conflicts
*/
declare function writeFileSafe(path: string, data?: string | Buffer): Promise<boolean>;
declare function limitText(text: string, maxWidth: number): string;
declare function formatPackageWithUrl(pkg: string, url?: string, limits?: number): string;
export { AGENTS, CLI_TEMP_DIR, COMMANDS, type DetectOptions, INSTALL_PAGE, LOCKS, type Runner, type RunnerContext, UnsupportedCommand, cmdExists, constructCommand, detect, exclude, formatPackageWithUrl, getCliCommand, getCommand, getConfig, getDefaultAgent, getGlobalAgent, limitText, parseNa, parseNi, parseNlx, parseNr, parseNu, parseNun, remove, resolveCommand, run, runCli, serializeCommand, writeFileSafe };
+129
View File
@@ -0,0 +1,129 @@
import { Buffer } from 'node:buffer';
type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno';
type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno';
type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null;
interface AgentCommands {
'agent': AgentCommandValue;
'run': AgentCommandValue;
'install': AgentCommandValue;
'frozen': AgentCommandValue;
'global': AgentCommandValue;
'add': AgentCommandValue;
'upgrade': AgentCommandValue;
'upgrade-interactive': AgentCommandValue;
'execute': AgentCommandValue;
'execute-local': AgentCommandValue;
'uninstall': AgentCommandValue;
'global_uninstall': AgentCommandValue;
}
type Command = keyof AgentCommands;
interface ResolvedCommand {
/**
* CLI command.
*/
command: string;
/**
* Arguments for the CLI command, merged with user arguments.
*/
args: string[];
}
declare const COMMANDS: {
npm: AgentCommands;
yarn: AgentCommands;
'yarn@berry': AgentCommands;
pnpm: AgentCommands;
'pnpm@6': AgentCommands;
bun: AgentCommands;
deno: AgentCommands;
};
/**
* Resolve the command for the agent merging the command arguments with the provided arguments.
*
* For example, to show how to install `@antfu/ni` globally using `pnpm`:
* ```js
* import { resolveCommand } from 'package-manager-detector/commands'
* const { command, args } = resolveCommand('pnpm', 'global', ['@antfu/ni'])
* console.log(`${command} ${args.join(' ')}`) // 'pnpm add -g @antfu/ni'
* ```
*
* @param agent The agent to use.
* @param command the command to resolve.
* @param args The arguments to pass to the command.
* @returns {ResolvedCommand} The resolved command or `null` if the agent command is not found.
*/
declare function resolveCommand(agent: Agent, command: Command, args: string[]): ResolvedCommand | null;
/**
* Construct the command from the agent command merging the command arguments with the provided arguments.
* @param value {AgentCommandValue} The agent command to use.
* @param args The arguments to pass to the command.
* @returns {ResolvedCommand} The resolved command or `null` if the command is `null`.
*/
declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null;
declare const AGENTS: Agent[];
declare const LOCKS: Record<string, AgentName>;
declare const INSTALL_PAGE: Record<Agent, string>;
interface Config {
defaultAgent: Agent | 'prompt';
globalAgent: Agent;
}
declare function getConfig(): Promise<Config>;
declare function getDefaultAgent(programmatic?: boolean): Promise<Agent | "prompt">;
declare function getGlobalAgent(): Promise<Agent>;
interface DetectOptions {
autoInstall?: boolean;
programmatic?: boolean;
cwd?: string;
/**
* Should use Volta when present
*
* @see https://volta.sh/
* @default true
*/
detectVolta?: boolean;
}
declare function detect({ autoInstall, programmatic, cwd }?: DetectOptions): Promise<Agent | undefined>;
interface RunnerContext {
programmatic?: boolean;
hasLock?: boolean;
cwd?: string;
}
type Runner = (agent: Agent, args: string[], ctx?: RunnerContext) => Promise<ResolvedCommand | undefined> | ResolvedCommand | undefined;
declare function runCli(fn: Runner, options?: DetectOptions & {
args?: string[];
}): Promise<void>;
declare function getCliCommand(fn: Runner, args: string[], options?: DetectOptions, cwd?: string): Promise<ResolvedCommand | undefined>;
declare function run(fn: Runner, args: string[], options?: DetectOptions): Promise<void>;
declare class UnsupportedCommand extends Error {
constructor({ agent, command }: {
agent: Agent;
command: Command;
});
}
declare function getCommand(agent: Agent, command: Command, args?: string[]): ResolvedCommand;
declare const parseNi: Runner;
declare const parseNr: Runner;
declare const parseNu: Runner;
declare const parseNun: Runner;
declare const parseNlx: Runner;
declare const parseNa: Runner;
declare function serializeCommand(command?: ResolvedCommand): string | undefined;
declare const CLI_TEMP_DIR: string;
declare function remove<T>(arr: T[], v: T): T[];
declare function exclude<T>(arr: T[], ...v: T[]): T[];
declare function cmdExists(cmd: string): boolean;
/**
* Write file safely avoiding conflicts
*/
declare function writeFileSafe(path: string, data?: string | Buffer): Promise<boolean>;
declare function limitText(text: string, maxWidth: number): string;
declare function formatPackageWithUrl(pkg: string, url?: string, limits?: number): string;
export { AGENTS, CLI_TEMP_DIR, COMMANDS, type DetectOptions, INSTALL_PAGE, LOCKS, type Runner, type RunnerContext, UnsupportedCommand, cmdExists, constructCommand, detect, exclude, formatPackageWithUrl, getCliCommand, getCommand, getConfig, getDefaultAgent, getGlobalAgent, limitText, parseNa, parseNi, parseNlx, parseNr, parseNu, parseNun, remove, resolveCommand, run, runCli, serializeCommand, writeFileSafe };
+129
View File
@@ -0,0 +1,129 @@
import { Buffer } from 'node:buffer';
type Agent = 'npm' | 'yarn' | 'yarn@berry' | 'pnpm' | 'pnpm@6' | 'bun' | 'deno';
type AgentName = 'npm' | 'yarn' | 'pnpm' | 'bun' | 'deno';
type AgentCommandValue = (string | number)[] | ((args: string[]) => string[]) | null;
interface AgentCommands {
'agent': AgentCommandValue;
'run': AgentCommandValue;
'install': AgentCommandValue;
'frozen': AgentCommandValue;
'global': AgentCommandValue;
'add': AgentCommandValue;
'upgrade': AgentCommandValue;
'upgrade-interactive': AgentCommandValue;
'execute': AgentCommandValue;
'execute-local': AgentCommandValue;
'uninstall': AgentCommandValue;
'global_uninstall': AgentCommandValue;
}
type Command = keyof AgentCommands;
interface ResolvedCommand {
/**
* CLI command.
*/
command: string;
/**
* Arguments for the CLI command, merged with user arguments.
*/
args: string[];
}
declare const COMMANDS: {
npm: AgentCommands;
yarn: AgentCommands;
'yarn@berry': AgentCommands;
pnpm: AgentCommands;
'pnpm@6': AgentCommands;
bun: AgentCommands;
deno: AgentCommands;
};
/**
* Resolve the command for the agent merging the command arguments with the provided arguments.
*
* For example, to show how to install `@antfu/ni` globally using `pnpm`:
* ```js
* import { resolveCommand } from 'package-manager-detector/commands'
* const { command, args } = resolveCommand('pnpm', 'global', ['@antfu/ni'])
* console.log(`${command} ${args.join(' ')}`) // 'pnpm add -g @antfu/ni'
* ```
*
* @param agent The agent to use.
* @param command the command to resolve.
* @param args The arguments to pass to the command.
* @returns {ResolvedCommand} The resolved command or `null` if the agent command is not found.
*/
declare function resolveCommand(agent: Agent, command: Command, args: string[]): ResolvedCommand | null;
/**
* Construct the command from the agent command merging the command arguments with the provided arguments.
* @param value {AgentCommandValue} The agent command to use.
* @param args The arguments to pass to the command.
* @returns {ResolvedCommand} The resolved command or `null` if the command is `null`.
*/
declare function constructCommand(value: AgentCommandValue, args: string[]): ResolvedCommand | null;
declare const AGENTS: Agent[];
declare const LOCKS: Record<string, AgentName>;
declare const INSTALL_PAGE: Record<Agent, string>;
interface Config {
defaultAgent: Agent | 'prompt';
globalAgent: Agent;
}
declare function getConfig(): Promise<Config>;
declare function getDefaultAgent(programmatic?: boolean): Promise<Agent | "prompt">;
declare function getGlobalAgent(): Promise<Agent>;
interface DetectOptions {
autoInstall?: boolean;
programmatic?: boolean;
cwd?: string;
/**
* Should use Volta when present
*
* @see https://volta.sh/
* @default true
*/
detectVolta?: boolean;
}
declare function detect({ autoInstall, programmatic, cwd }?: DetectOptions): Promise<Agent | undefined>;
interface RunnerContext {
programmatic?: boolean;
hasLock?: boolean;
cwd?: string;
}
type Runner = (agent: Agent, args: string[], ctx?: RunnerContext) => Promise<ResolvedCommand | undefined> | ResolvedCommand | undefined;
declare function runCli(fn: Runner, options?: DetectOptions & {
args?: string[];
}): Promise<void>;
declare function getCliCommand(fn: Runner, args: string[], options?: DetectOptions, cwd?: string): Promise<ResolvedCommand | undefined>;
declare function run(fn: Runner, args: string[], options?: DetectOptions): Promise<void>;
declare class UnsupportedCommand extends Error {
constructor({ agent, command }: {
agent: Agent;
command: Command;
});
}
declare function getCommand(agent: Agent, command: Command, args?: string[]): ResolvedCommand;
declare const parseNi: Runner;
declare const parseNr: Runner;
declare const parseNu: Runner;
declare const parseNun: Runner;
declare const parseNlx: Runner;
declare const parseNa: Runner;
declare function serializeCommand(command?: ResolvedCommand): string | undefined;
declare const CLI_TEMP_DIR: string;
declare function remove<T>(arr: T[], v: T): T[];
declare function exclude<T>(arr: T[], ...v: T[]): T[];
declare function cmdExists(cmd: string): boolean;
/**
* Write file safely avoiding conflicts
*/
declare function writeFileSafe(path: string, data?: string | Buffer): Promise<boolean>;
declare function limitText(text: string, maxWidth: number): string;
declare function formatPackageWithUrl(pkg: string, url?: string, limits?: number): string;
export { AGENTS, CLI_TEMP_DIR, COMMANDS, type DetectOptions, INSTALL_PAGE, LOCKS, type Runner, type RunnerContext, UnsupportedCommand, cmdExists, constructCommand, detect, exclude, formatPackageWithUrl, getCliCommand, getCommand, getConfig, getDefaultAgent, getGlobalAgent, limitText, parseNa, parseNi, parseNlx, parseNr, parseNu, parseNun, remove, resolveCommand, run, runCli, serializeCommand, writeFileSafe };
+17
View File
@@ -0,0 +1,17 @@
export { A as AGENTS, C as CLI_TEMP_DIR, u as COMMANDS, I as INSTALL_PAGE, L as LOCKS, U as UnsupportedCommand, o as cmdExists, v as constructCommand, d as detect, n as exclude, t as formatPackageWithUrl, k as getCliCommand, c as getCommand, g as getConfig, a as getDefaultAgent, b as getGlobalAgent, q as limitText, j as parseNa, p as parseNi, i as parseNlx, e as parseNr, f as parseNu, h as parseNun, m as remove, x as resolveCommand, l as run, r as runCli, s as serializeCommand, w as writeFileSafe } from './shared/ni.CtJepYoh.mjs';
import 'node:path';
import 'node:process';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const runner = require('./shared/ni.C82eau-4.cjs');
require('node:path');
require('node:process');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
runner.runCli(runner.parseNa);
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+19
View File
@@ -0,0 +1,19 @@
import { r as runCli, j as parseNa } from './shared/ni.CtJepYoh.mjs';
import 'node:path';
import 'node:process';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
runCli(parseNa);
+24
View File
@@ -0,0 +1,24 @@
'use strict';
const runner = require('./shared/ni.C82eau-4.cjs');
require('node:path');
require('node:process');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
runner.runCli(
(agent, _, hasLock) => runner.parseNi(agent, ["--frozen-if-present"], hasLock),
{ autoInstall: true }
);
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+22
View File
@@ -0,0 +1,22 @@
import { r as runCli, p as parseNi } from './shared/ni.CtJepYoh.mjs';
import 'node:path';
import 'node:process';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
runCli(
(agent, _, hasLock) => parseNi(agent, ["--frozen-if-present"], hasLock),
{ autoInstall: true }
);
+115
View File
@@ -0,0 +1,115 @@
'use strict';
const process = require('node:process');
const runner = require('./shared/ni.C82eau-4.cjs');
const fzf_es = require('./shared/ni.BK9cf7FY.cjs');
require('node:path');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
async function fetchNpmPackages(pattern) {
const registryLink = (pattern2) => `https://registry.npmjs.com/-/v1/search?text=${pattern2}&size=35`;
const terminalColumns = process__default.stdout?.columns || 80;
try {
const result = await fetch(registryLink(pattern)).then((res) => res.json());
return result.objects.map(({ package: pkg }) => ({
title: runner.formatPackageWithUrl(
`${pkg.name.padEnd(30, " ")} ${runner.c.blue(`v${pkg.version}`)}`,
pkg.links.repository ?? pkg.links.npm,
terminalColumns
),
value: pkg
}));
} catch {
console.error("Error when fetching npm registry");
process__default.exit(1);
}
}
runner.runCli(async (agent, args, ctx) => {
const isInteractive = args[0] === "-i";
if (isInteractive) {
let fetchPattern;
if (args[1] && !args[1].startsWith("-")) {
fetchPattern = args[1];
} else {
const { pattern } = await runner.prompts({
type: "text",
name: "pattern",
message: "search for package"
});
fetchPattern = pattern;
}
if (!fetchPattern) {
process__default.exitCode = 1;
return;
}
const packages = await fetchNpmPackages(fetchPattern);
if (!packages.length) {
console.error("No results found");
process__default.exitCode = 1;
return;
}
const fzf = new fzf_es.Fzf(packages, {
selector: (item) => item.title,
casing: "case-insensitive"
});
const { dependency } = await runner.prompts({
type: "autocomplete",
name: "dependency",
choices: packages,
instructions: false,
message: "choose a package to install",
limit: 15,
async suggest(input, choices) {
const results = fzf.find(input);
return results.map((r) => choices.find((c2) => c2.value === r.item.value));
}
});
if (!dependency) {
process__default.exitCode = 1;
return;
}
args = runner.exclude(args, "-d", "-p", "-i");
const canInstallPeers = ["npm", "pnpm"].includes(agent);
const { mode } = await runner.prompts({
type: "select",
name: "mode",
message: `install ${runner.c.yellow(dependency.name)} as`,
choices: [
{
title: "prod",
value: "",
selected: true
},
{
title: "dev",
value: "-D"
},
{
title: `peer`,
value: "--save-peer",
disabled: !canInstallPeers
}
]
});
args.push(dependency.name, mode);
}
return runner.parseNi(agent, args, ctx);
});
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+109
View File
@@ -0,0 +1,109 @@
import process from 'node:process';
import { t as formatPackageWithUrl, z as c, r as runCli, y as prompts, n as exclude, p as parseNi } from './shared/ni.CtJepYoh.mjs';
import { F as Fzf } from './shared/ni.DA7akRvA.mjs';
import 'node:path';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
async function fetchNpmPackages(pattern) {
const registryLink = (pattern2) => `https://registry.npmjs.com/-/v1/search?text=${pattern2}&size=35`;
const terminalColumns = process.stdout?.columns || 80;
try {
const result = await fetch(registryLink(pattern)).then((res) => res.json());
return result.objects.map(({ package: pkg }) => ({
title: formatPackageWithUrl(
`${pkg.name.padEnd(30, " ")} ${c.blue(`v${pkg.version}`)}`,
pkg.links.repository ?? pkg.links.npm,
terminalColumns
),
value: pkg
}));
} catch {
console.error("Error when fetching npm registry");
process.exit(1);
}
}
runCli(async (agent, args, ctx) => {
const isInteractive = args[0] === "-i";
if (isInteractive) {
let fetchPattern;
if (args[1] && !args[1].startsWith("-")) {
fetchPattern = args[1];
} else {
const { pattern } = await prompts({
type: "text",
name: "pattern",
message: "search for package"
});
fetchPattern = pattern;
}
if (!fetchPattern) {
process.exitCode = 1;
return;
}
const packages = await fetchNpmPackages(fetchPattern);
if (!packages.length) {
console.error("No results found");
process.exitCode = 1;
return;
}
const fzf = new Fzf(packages, {
selector: (item) => item.title,
casing: "case-insensitive"
});
const { dependency } = await prompts({
type: "autocomplete",
name: "dependency",
choices: packages,
instructions: false,
message: "choose a package to install",
limit: 15,
async suggest(input, choices) {
const results = fzf.find(input);
return results.map((r) => choices.find((c2) => c2.value === r.item.value));
}
});
if (!dependency) {
process.exitCode = 1;
return;
}
args = exclude(args, "-d", "-p", "-i");
const canInstallPeers = ["npm", "pnpm"].includes(agent);
const { mode } = await prompts({
type: "select",
name: "mode",
message: `install ${c.yellow(dependency.name)} as`,
choices: [
{
title: "prod",
value: "",
selected: true
},
{
title: "dev",
value: "-D"
},
{
title: `peer`,
value: "--save-peer",
disabled: !canInstallPeers
}
]
});
args.push(dependency.name, mode);
}
return parseNi(agent, args, ctx);
});
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const runner = require('./shared/ni.C82eau-4.cjs');
require('node:path');
require('node:process');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
runner.runCli(runner.parseNlx);
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+19
View File
@@ -0,0 +1,19 @@
import { r as runCli, i as parseNlx } from './shared/ni.CtJepYoh.mjs';
import 'node:path';
import 'node:process';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
runCli(parseNlx);
+105
View File
@@ -0,0 +1,105 @@
'use strict';
const process = require('node:process');
const runner = require('./shared/ni.C82eau-4.cjs');
const fzf_es = require('./shared/ni.BK9cf7FY.cjs');
const fs$1 = require('./shared/ni.DWRIF_6-.cjs');
const fs = require('node:fs');
const path = require('node:path');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
let storage;
const storagePath = path.resolve(runner.CLI_TEMP_DIR, "_storage.json");
async function load(fn) {
if (!storage) {
storage = fs.existsSync(storagePath) ? JSON.parse(await fs.promises.readFile(storagePath, "utf-8") || "{}") || {} : {};
}
return storage;
}
async function dump() {
if (storage)
await runner.writeFileSafe(storagePath, JSON.stringify(storage));
}
runner.runCli(async (agent, args, ctx) => {
const storage = await load();
if (args[0] === "-") {
if (!storage.lastRunCommand) {
if (!ctx?.programmatic) {
console.error("No last command found");
process__default.exit(1);
}
throw new Error("No last command found");
}
args[0] = storage.lastRunCommand;
}
if (args.length === 0 && !ctx?.programmatic) {
const pkg = fs$1.getPackageJSON(ctx);
const scripts = pkg.scripts || {};
const scriptsInfo = pkg["scripts-info"] || {};
const names = Object.entries(scripts);
if (!names.length)
return;
const raw = names.filter((i) => !i[0].startsWith("?")).map(([key, cmd]) => ({
key,
cmd,
description: scriptsInfo[key] || scripts[`?${key}`] || cmd
}));
const terminalColumns = process__default.stdout?.columns || 80;
const choices = raw.map(({ key, description }) => ({
title: key,
value: key,
description: runner.limitText(description, terminalColumns - 15)
}));
const fzf = new fzf_es.Fzf(raw, {
selector: (item) => `${item.key} ${item.description}`,
casing: "case-insensitive",
tiebreakers: [fzf_es.byLengthAsc]
});
if (storage.lastRunCommand) {
const last = choices.find((i) => i.value === storage.lastRunCommand);
if (last)
choices.unshift(last);
}
try {
const { fn } = await runner.prompts({
name: "fn",
message: "script to run",
type: "autocomplete",
choices,
async suggest(input, choices2) {
if (!input)
return choices2;
const results = fzf.find(input);
return results.map((r) => choices2.find((c) => c.value === r.item.key));
}
});
if (!fn)
return;
args.push(fn);
} catch {
process__default.exit(1);
}
}
if (storage.lastRunCommand !== args[0]) {
storage.lastRunCommand = args[0];
dump();
}
return runner.parseNr(agent, args);
});
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+99
View File
@@ -0,0 +1,99 @@
import process from 'node:process';
import { C as CLI_TEMP_DIR, w as writeFileSafe, r as runCli, q as limitText, y as prompts, e as parseNr } from './shared/ni.CtJepYoh.mjs';
import { F as Fzf, b as byLengthAsc } from './shared/ni.DA7akRvA.mjs';
import { g as getPackageJSON } from './shared/ni.C4mrCGPc.mjs';
import { existsSync, promises } from 'node:fs';
import { resolve } from 'node:path';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
let storage;
const storagePath = resolve(CLI_TEMP_DIR, "_storage.json");
async function load(fn) {
if (!storage) {
storage = existsSync(storagePath) ? JSON.parse(await promises.readFile(storagePath, "utf-8") || "{}") || {} : {};
}
return storage;
}
async function dump() {
if (storage)
await writeFileSafe(storagePath, JSON.stringify(storage));
}
runCli(async (agent, args, ctx) => {
const storage = await load();
if (args[0] === "-") {
if (!storage.lastRunCommand) {
if (!ctx?.programmatic) {
console.error("No last command found");
process.exit(1);
}
throw new Error("No last command found");
}
args[0] = storage.lastRunCommand;
}
if (args.length === 0 && !ctx?.programmatic) {
const pkg = getPackageJSON(ctx);
const scripts = pkg.scripts || {};
const scriptsInfo = pkg["scripts-info"] || {};
const names = Object.entries(scripts);
if (!names.length)
return;
const raw = names.filter((i) => !i[0].startsWith("?")).map(([key, cmd]) => ({
key,
cmd,
description: scriptsInfo[key] || scripts[`?${key}`] || cmd
}));
const terminalColumns = process.stdout?.columns || 80;
const choices = raw.map(({ key, description }) => ({
title: key,
value: key,
description: limitText(description, terminalColumns - 15)
}));
const fzf = new Fzf(raw, {
selector: (item) => `${item.key} ${item.description}`,
casing: "case-insensitive",
tiebreakers: [byLengthAsc]
});
if (storage.lastRunCommand) {
const last = choices.find((i) => i.value === storage.lastRunCommand);
if (last)
choices.unshift(last);
}
try {
const { fn } = await prompts({
name: "fn",
message: "script to run",
type: "autocomplete",
choices,
async suggest(input, choices2) {
if (!input)
return choices2;
const results = fzf.find(input);
return results.map((r) => choices2.find((c) => c.value === r.item.key));
}
});
if (!fn)
return;
args.push(fn);
} catch {
process.exit(1);
}
}
if (storage.lastRunCommand !== args[0]) {
storage.lastRunCommand = args[0];
dump();
}
return parseNr(agent, args);
});
+21
View File
@@ -0,0 +1,21 @@
'use strict';
const runner = require('./shared/ni.C82eau-4.cjs');
require('node:path');
require('node:process');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
runner.runCli(runner.parseNu);
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+19
View File
@@ -0,0 +1,19 @@
import { r as runCli, f as parseNu } from './shared/ni.CtJepYoh.mjs';
import 'node:path';
import 'node:process';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
runCli(parseNu);
+75
View File
@@ -0,0 +1,75 @@
'use strict';
const process = require('node:process');
const runner = require('./shared/ni.C82eau-4.cjs');
const fzf_es = require('./shared/ni.BK9cf7FY.cjs');
const fs = require('./shared/ni.DWRIF_6-.cjs');
require('node:path');
require('readline');
require('events');
require('node:module');
require('child_process');
require('path');
require('process');
require('stream');
require('node:fs');
require('os');
require('tty');
require('node:os');
require('fs');
require('fs/promises');
require('node:fs/promises');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
runner.runCli(async (agent, args, ctx) => {
const isInteractive = !args.length && !ctx?.programmatic;
if (isInteractive || args[0] === "-m") {
const pkg = fs.getPackageJSON(ctx);
const allDependencies = { ...pkg.dependencies, ...pkg.devDependencies };
const raw = Object.entries(allDependencies);
if (!raw.length) {
console.error("No dependencies found");
return;
}
const fzf = new fzf_es.Fzf(raw, {
selector: ([dep, version]) => `${dep} ${version}`,
casing: "case-insensitive"
});
const choices = raw.map(([dependency, version]) => ({
title: dependency,
value: dependency,
description: version
}));
const isMultiple = args[0] === "-m";
const type = isMultiple ? "autocompleteMultiselect" : "autocomplete";
if (isMultiple)
args = runner.exclude(args, "-m");
try {
const { depsToRemove } = await runner.prompts({
type,
name: "depsToRemove",
choices,
instructions: false,
message: `remove ${isMultiple ? "dependencies" : "dependency"}`,
async suggest(input, choices2) {
const results = fzf.find(input);
return results.map((r) => choices2.find((c) => c.value === r.item[0]));
}
});
if (!depsToRemove) {
process__default.exitCode = 1;
return;
}
const isSingleDependency = typeof depsToRemove === "string";
if (isSingleDependency)
args.push(depsToRemove);
else args.push(...depsToRemove);
} catch {
process__default.exit(1);
}
}
return runner.parseNun(agent, args);
});
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+2
View File
@@ -0,0 +1,2 @@
export { }
+69
View File
@@ -0,0 +1,69 @@
import process from 'node:process';
import { r as runCli, n as exclude, y as prompts, h as parseNun } from './shared/ni.CtJepYoh.mjs';
import { F as Fzf } from './shared/ni.DA7akRvA.mjs';
import { g as getPackageJSON } from './shared/ni.C4mrCGPc.mjs';
import 'node:path';
import 'readline';
import 'events';
import 'node:module';
import 'child_process';
import 'path';
import 'process';
import 'stream';
import 'node:fs';
import 'os';
import 'tty';
import 'node:os';
import 'fs';
import 'fs/promises';
import 'node:fs/promises';
runCli(async (agent, args, ctx) => {
const isInteractive = !args.length && !ctx?.programmatic;
if (isInteractive || args[0] === "-m") {
const pkg = getPackageJSON(ctx);
const allDependencies = { ...pkg.dependencies, ...pkg.devDependencies };
const raw = Object.entries(allDependencies);
if (!raw.length) {
console.error("No dependencies found");
return;
}
const fzf = new Fzf(raw, {
selector: ([dep, version]) => `${dep} ${version}`,
casing: "case-insensitive"
});
const choices = raw.map(([dependency, version]) => ({
title: dependency,
value: dependency,
description: version
}));
const isMultiple = args[0] === "-m";
const type = isMultiple ? "autocompleteMultiselect" : "autocomplete";
if (isMultiple)
args = exclude(args, "-m");
try {
const { depsToRemove } = await prompts({
type,
name: "depsToRemove",
choices,
instructions: false,
message: `remove ${isMultiple ? "dependencies" : "dependency"}`,
async suggest(input, choices2) {
const results = fzf.find(input);
return results.map((r) => choices2.find((c) => c.value === r.item[0]));
}
});
if (!depsToRemove) {
process.exitCode = 1;
return;
}
const isSingleDependency = typeof depsToRemove === "string";
if (isSingleDependency)
args.push(depsToRemove);
else args.push(...depsToRemove);
} catch {
process.exit(1);
}
}
return parseNun(agent, args);
});
+921
View File
@@ -0,0 +1,921 @@
'use strict';
/** @license
* fzf v0.5.2
* Copyright (c) 2021 Ajit
* Licensed under BSD 3-Clause
*/
const normalized = {
216: "O",
223: "s",
248: "o",
273: "d",
295: "h",
305: "i",
320: "l",
322: "l",
359: "t",
383: "s",
384: "b",
385: "B",
387: "b",
390: "O",
392: "c",
393: "D",
394: "D",
396: "d",
398: "E",
400: "E",
402: "f",
403: "G",
407: "I",
409: "k",
410: "l",
412: "M",
413: "N",
414: "n",
415: "O",
421: "p",
427: "t",
429: "t",
430: "T",
434: "V",
436: "y",
438: "z",
477: "e",
485: "g",
544: "N",
545: "d",
549: "z",
564: "l",
565: "n",
566: "t",
567: "j",
570: "A",
571: "C",
572: "c",
573: "L",
574: "T",
575: "s",
576: "z",
579: "B",
580: "U",
581: "V",
582: "E",
583: "e",
584: "J",
585: "j",
586: "Q",
587: "q",
588: "R",
589: "r",
590: "Y",
591: "y",
592: "a",
593: "a",
595: "b",
596: "o",
597: "c",
598: "d",
599: "d",
600: "e",
603: "e",
604: "e",
605: "e",
606: "e",
607: "j",
608: "g",
609: "g",
610: "G",
613: "h",
614: "h",
616: "i",
618: "I",
619: "l",
620: "l",
621: "l",
623: "m",
624: "m",
625: "m",
626: "n",
627: "n",
628: "N",
629: "o",
633: "r",
634: "r",
635: "r",
636: "r",
637: "r",
638: "r",
639: "r",
640: "R",
641: "R",
642: "s",
647: "t",
648: "t",
649: "u",
651: "v",
652: "v",
653: "w",
654: "y",
655: "Y",
656: "z",
657: "z",
663: "c",
665: "B",
666: "e",
667: "G",
668: "H",
669: "j",
670: "k",
671: "L",
672: "q",
686: "h",
867: "a",
868: "e",
869: "i",
870: "o",
871: "u",
872: "c",
873: "d",
874: "h",
875: "m",
876: "r",
877: "t",
878: "v",
879: "x",
7424: "A",
7427: "B",
7428: "C",
7429: "D",
7431: "E",
7432: "e",
7433: "i",
7434: "J",
7435: "K",
7436: "L",
7437: "M",
7438: "N",
7439: "O",
7440: "O",
7441: "o",
7442: "o",
7443: "o",
7446: "o",
7447: "o",
7448: "P",
7449: "R",
7450: "R",
7451: "T",
7452: "U",
7453: "u",
7454: "u",
7455: "m",
7456: "V",
7457: "W",
7458: "Z",
7522: "i",
7523: "r",
7524: "u",
7525: "v",
7834: "a",
7835: "s",
8305: "i",
8341: "h",
8342: "k",
8343: "l",
8344: "m",
8345: "n",
8346: "p",
8347: "s",
8348: "t",
8580: "c"
};
for (let i = "\u0300".codePointAt(0); i <= "\u036F".codePointAt(0); ++i) {
const diacritic = String.fromCodePoint(i);
for (const asciiChar of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
const withDiacritic = (asciiChar + diacritic).normalize();
const withDiacriticCodePoint = withDiacritic.codePointAt(0);
if (withDiacriticCodePoint > 126) {
normalized[withDiacriticCodePoint] = asciiChar;
}
}
}
const ranges = {
a: [7844, 7863],
e: [7870, 7879],
o: [7888, 7907],
u: [7912, 7921]
};
for (const lowerChar of Object.keys(ranges)) {
const upperChar = lowerChar.toUpperCase();
for (let i = ranges[lowerChar][0]; i <= ranges[lowerChar][1]; ++i) {
normalized[i] = i % 2 === 0 ? upperChar : lowerChar;
}
}
function normalizeRune(rune) {
if (rune < 192 || rune > 8580) {
return rune;
}
const normalizedChar = normalized[rune];
if (normalizedChar !== void 0)
return normalizedChar.codePointAt(0);
return rune;
}
function toShort(number) {
return number;
}
function toInt(number) {
return number;
}
function maxInt16(num1, num2) {
return num1 > num2 ? num1 : num2;
}
const strToRunes = (str) => str.split("").map((s) => s.codePointAt(0));
const whitespaceRunes = new Set(
" \f\n\r \v\xA0\u1680\u2028\u2029\u202F\u205F\u3000\uFEFF".split("").map((v) => v.codePointAt(0))
);
for (let codePoint = "\u2000".codePointAt(0); codePoint <= "\u200A".codePointAt(0); codePoint++) {
whitespaceRunes.add(codePoint);
}
const MAX_ASCII = "\x7F".codePointAt(0);
const CAPITAL_A_RUNE = "A".codePointAt(0);
const CAPITAL_Z_RUNE = "Z".codePointAt(0);
const SMALL_A_RUNE = "a".codePointAt(0);
const SMALL_Z_RUNE = "z".codePointAt(0);
const NUMERAL_ZERO_RUNE = "0".codePointAt(0);
const NUMERAL_NINE_RUNE = "9".codePointAt(0);
function indexAt(index, max, forward) {
if (forward) {
return index;
}
return max - index - 1;
}
const SCORE_MATCH = 16, SCORE_GAP_START = -3, SCORE_GAP_EXTENTION = -1, BONUS_BOUNDARY = SCORE_MATCH / 2, BONUS_NON_WORD = SCORE_MATCH / 2, BONUS_CAMEL_123 = BONUS_BOUNDARY + SCORE_GAP_EXTENTION, BONUS_CONSECUTIVE = -(SCORE_GAP_START + SCORE_GAP_EXTENTION), BONUS_FIRST_CHAR_MULTIPLIER = 2;
function createPosSet(withPos) {
if (withPos) {
return /* @__PURE__ */ new Set();
}
return null;
}
function alloc16(offset, slab2, size) {
if (slab2 !== null && slab2.i16.length > offset + size) {
const subarray = slab2.i16.subarray(offset, offset + size);
return [offset + size, subarray];
}
return [offset, new Int16Array(size)];
}
function alloc32(offset, slab2, size) {
if (slab2 !== null && slab2.i32.length > offset + size) {
const subarray = slab2.i32.subarray(offset, offset + size);
return [offset + size, subarray];
}
return [offset, new Int32Array(size)];
}
function charClassOfAscii(rune) {
if (rune >= SMALL_A_RUNE && rune <= SMALL_Z_RUNE) {
return 1;
} else if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
return 2;
} else if (rune >= NUMERAL_ZERO_RUNE && rune <= NUMERAL_NINE_RUNE) {
return 4;
} else {
return 0;
}
}
function charClassOfNonAscii(rune) {
const char = String.fromCodePoint(rune);
if (char !== char.toUpperCase()) {
return 1;
} else if (char !== char.toLowerCase()) {
return 2;
} else if (char.match(/\p{Number}/gu) !== null) {
return 4;
} else if (char.match(/\p{Letter}/gu) !== null) {
return 3;
}
return 0;
}
function charClassOf(rune) {
if (rune <= MAX_ASCII) {
return charClassOfAscii(rune);
}
return charClassOfNonAscii(rune);
}
function bonusFor(prevClass, currClass) {
if (prevClass === 0 && currClass !== 0) {
return BONUS_BOUNDARY;
} else if (prevClass === 1 && currClass === 2 || prevClass !== 4 && currClass === 4) {
return BONUS_CAMEL_123;
} else if (currClass === 0) {
return BONUS_NON_WORD;
}
return 0;
}
function bonusAt(input, idx) {
if (idx === 0) {
return BONUS_BOUNDARY;
}
return bonusFor(charClassOf(input[idx - 1]), charClassOf(input[idx]));
}
function trySkip(input, caseSensitive, char, from) {
let rest = input.slice(from);
let idx = rest.indexOf(char);
if (idx === 0) {
return from;
}
if (!caseSensitive && char >= SMALL_A_RUNE && char <= SMALL_Z_RUNE) {
if (idx > 0) {
rest = rest.slice(0, idx);
}
const uidx = rest.indexOf(char - 32);
if (uidx >= 0) {
idx = uidx;
}
}
if (idx < 0) {
return -1;
}
return from + idx;
}
function isAscii(runes) {
for (const rune of runes) {
if (rune >= 128) {
return false;
}
}
return true;
}
function asciiFuzzyIndex(input, pattern, caseSensitive) {
if (!isAscii(input)) {
return 0;
}
if (!isAscii(pattern)) {
return -1;
}
let firstIdx = 0, idx = 0;
for (let pidx = 0; pidx < pattern.length; pidx++) {
idx = trySkip(input, caseSensitive, pattern[pidx], idx);
if (idx < 0) {
return -1;
}
if (pidx === 0 && idx > 0) {
firstIdx = idx - 1;
}
idx++;
}
return firstIdx;
}
const fuzzyMatchV2 = (caseSensitive, normalize, forward, input, pattern, withPos, slab2) => {
const M = pattern.length;
if (M === 0) {
return [{ start: 0, end: 0, score: 0 }, createPosSet(withPos)];
}
const N = input.length;
if (slab2 !== null && N * M > slab2.i16.length) {
return fuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos);
}
const idx = asciiFuzzyIndex(input, pattern, caseSensitive);
if (idx < 0) {
return [{ start: -1, end: -1, score: 0 }, null];
}
let offset16 = 0, offset32 = 0, H0 = null, C0 = null, B = null, F = null;
[offset16, H0] = alloc16(offset16, slab2, N);
[offset16, C0] = alloc16(offset16, slab2, N);
[offset16, B] = alloc16(offset16, slab2, N);
[offset32, F] = alloc32(offset32, slab2, M);
const [, T] = alloc32(offset32, slab2, N);
for (let i = 0; i < T.length; i++) {
T[i] = input[i];
}
let maxScore = toShort(0), maxScorePos = 0;
let pidx = 0, lastIdx = 0;
const pchar0 = pattern[0];
let pchar = pattern[0], prevH0 = toShort(0), prevCharClass = 0, inGap = false;
let Tsub = T.subarray(idx);
let H0sub = H0.subarray(idx).subarray(0, Tsub.length), C0sub = C0.subarray(idx).subarray(0, Tsub.length), Bsub = B.subarray(idx).subarray(0, Tsub.length);
for (let [off, char] of Tsub.entries()) {
let charClass = null;
if (char <= MAX_ASCII) {
charClass = charClassOfAscii(char);
if (!caseSensitive && charClass === 2) {
char += 32;
}
} else {
charClass = charClassOfNonAscii(char);
if (!caseSensitive && charClass === 2) {
char = String.fromCodePoint(char).toLowerCase().codePointAt(0);
}
if (normalize) {
char = normalizeRune(char);
}
}
Tsub[off] = char;
const bonus = bonusFor(prevCharClass, charClass);
Bsub[off] = bonus;
prevCharClass = charClass;
if (char === pchar) {
if (pidx < M) {
F[pidx] = toInt(idx + off);
pidx++;
pchar = pattern[Math.min(pidx, M - 1)];
}
lastIdx = idx + off;
}
if (char === pchar0) {
const score = SCORE_MATCH + bonus * BONUS_FIRST_CHAR_MULTIPLIER;
H0sub[off] = score;
C0sub[off] = 1;
if (M === 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
maxScore = score;
maxScorePos = idx + off;
if (forward && bonus === BONUS_BOUNDARY) {
break;
}
}
inGap = false;
} else {
if (inGap) {
H0sub[off] = maxInt16(prevH0 + SCORE_GAP_EXTENTION, 0);
} else {
H0sub[off] = maxInt16(prevH0 + SCORE_GAP_START, 0);
}
C0sub[off] = 0;
inGap = true;
}
prevH0 = H0sub[off];
}
if (pidx !== M) {
return [{ start: -1, end: -1, score: 0 }, null];
}
if (M === 1) {
const result = {
start: maxScorePos,
end: maxScorePos + 1,
score: maxScore
};
if (!withPos) {
return [result, null];
}
const pos2 = /* @__PURE__ */ new Set();
pos2.add(maxScorePos);
return [result, pos2];
}
const f0 = F[0];
const width = lastIdx - f0 + 1;
let H = null;
[offset16, H] = alloc16(offset16, slab2, width * M);
{
const toCopy = H0.subarray(f0, lastIdx + 1);
for (const [i, v] of toCopy.entries()) {
H[i] = v;
}
}
let [, C] = alloc16(offset16, slab2, width * M);
{
const toCopy = C0.subarray(f0, lastIdx + 1);
for (const [i, v] of toCopy.entries()) {
C[i] = v;
}
}
const Fsub = F.subarray(1);
const Psub = pattern.slice(1).slice(0, Fsub.length);
for (const [off, f] of Fsub.entries()) {
let inGap2 = false;
const pchar2 = Psub[off], pidx2 = off + 1, row = pidx2 * width, Tsub2 = T.subarray(f, lastIdx + 1), Bsub2 = B.subarray(f).subarray(0, Tsub2.length), Csub = C.subarray(row + f - f0).subarray(0, Tsub2.length), Cdiag = C.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hsub = H.subarray(row + f - f0).subarray(0, Tsub2.length), Hdiag = H.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hleft = H.subarray(row + f - f0 - 1).subarray(0, Tsub2.length);
Hleft[0] = 0;
for (const [off2, char] of Tsub2.entries()) {
const col = off2 + f;
let s1 = 0, s2 = 0, consecutive = 0;
if (inGap2) {
s2 = Hleft[off2] + SCORE_GAP_EXTENTION;
} else {
s2 = Hleft[off2] + SCORE_GAP_START;
}
if (pchar2 === char) {
s1 = Hdiag[off2] + SCORE_MATCH;
let b = Bsub2[off2];
consecutive = Cdiag[off2] + 1;
if (b === BONUS_BOUNDARY) {
consecutive = 1;
} else if (consecutive > 1) {
b = maxInt16(b, maxInt16(BONUS_CONSECUTIVE, B[col - consecutive + 1]));
}
if (s1 + b < s2) {
s1 += Bsub2[off2];
consecutive = 0;
} else {
s1 += b;
}
}
Csub[off2] = consecutive;
inGap2 = s1 < s2;
const score = maxInt16(maxInt16(s1, s2), 0);
if (pidx2 === M - 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
maxScore = score;
maxScorePos = col;
}
Hsub[off2] = score;
}
}
const pos = createPosSet(withPos);
let j = f0;
if (withPos && pos !== null) {
let i = M - 1;
j = maxScorePos;
let preferMatch = true;
while (true) {
const I = i * width, j0 = j - f0, s = H[I + j0];
let s1 = 0, s2 = 0;
if (i > 0 && j >= F[i]) {
s1 = H[I - width + j0 - 1];
}
if (j > F[i]) {
s2 = H[I + j0 - 1];
}
if (s > s1 && (s > s2 || s === s2 && preferMatch)) {
pos.add(j);
if (i === 0) {
break;
}
i--;
}
preferMatch = C[I + j0] > 1 || I + width + j0 + 1 < C.length && C[I + width + j0 + 1] > 0;
j--;
}
}
return [{ start: j, end: maxScorePos + 1, score: maxScore }, pos];
};
function calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos) {
let pidx = 0, score = 0, inGap = false, consecutive = 0, firstBonus = toShort(0);
const pos = createPosSet(withPos);
let prevCharClass = 0;
if (sidx > 0) {
prevCharClass = charClassOf(text[sidx - 1]);
}
for (let idx = sidx; idx < eidx; idx++) {
let rune = text[idx];
const charClass = charClassOf(rune);
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
if (normalize) {
rune = normalizeRune(rune);
}
if (rune === pattern[pidx]) {
if (withPos && pos !== null) {
pos.add(idx);
}
score += SCORE_MATCH;
let bonus = bonusFor(prevCharClass, charClass);
if (consecutive === 0) {
firstBonus = bonus;
} else {
if (bonus === BONUS_BOUNDARY) {
firstBonus = bonus;
}
bonus = maxInt16(maxInt16(bonus, firstBonus), BONUS_CONSECUTIVE);
}
if (pidx === 0) {
score += bonus * BONUS_FIRST_CHAR_MULTIPLIER;
} else {
score += bonus;
}
inGap = false;
consecutive++;
pidx++;
} else {
if (inGap) {
score += SCORE_GAP_EXTENTION;
} else {
score += SCORE_GAP_START;
}
inGap = true;
consecutive = 0;
firstBonus = 0;
}
prevCharClass = charClass;
}
return [score, pos];
}
const fuzzyMatchV1 = (caseSensitive, normalize, forward, text, pattern, withPos, slab2) => {
if (pattern.length === 0) {
return [{ start: 0, end: 0, score: 0 }, null];
}
if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) {
return [{ start: -1, end: -1, score: 0 }, null];
}
let pidx = 0, sidx = -1, eidx = -1;
const lenRunes = text.length;
const lenPattern = pattern.length;
for (let index = 0; index < lenRunes; index++) {
let rune = text[indexAt(index, lenRunes, forward)];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
if (normalize) {
rune = normalizeRune(rune);
}
const pchar = pattern[indexAt(pidx, lenPattern, forward)];
if (rune === pchar) {
if (sidx < 0) {
sidx = index;
}
pidx++;
if (pidx === lenPattern) {
eidx = index + 1;
break;
}
}
}
if (sidx >= 0 && eidx >= 0) {
pidx--;
for (let index = eidx - 1; index >= sidx; index--) {
const tidx = indexAt(index, lenRunes, forward);
let rune = text[tidx];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
const pidx_ = indexAt(pidx, lenPattern, forward);
const pchar = pattern[pidx_];
if (rune === pchar) {
pidx--;
if (pidx < 0) {
sidx = index;
break;
}
}
}
if (!forward) {
const sidxTemp = sidx;
sidx = lenRunes - eidx;
eidx = lenRunes - sidxTemp;
}
const [score, pos] = calculateScore(
caseSensitive,
normalize,
text,
pattern,
sidx,
eidx,
withPos
);
return [{ start: sidx, end: eidx, score }, pos];
}
return [{ start: -1, end: -1, score: 0 }, null];
};
const exactMatchNaive = (caseSensitive, normalize, forward, text, pattern, withPos, slab2) => {
if (pattern.length === 0) {
return [{ start: 0, end: 0, score: 0 }, null];
}
const lenRunes = text.length;
const lenPattern = pattern.length;
if (lenRunes < lenPattern) {
return [{ start: -1, end: -1, score: 0 }, null];
}
if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) {
return [{ start: -1, end: -1, score: 0 }, null];
}
let pidx = 0;
let bestPos = -1, bonus = toShort(0), bestBonus = toShort(-1);
for (let index = 0; index < lenRunes; index++) {
const index_ = indexAt(index, lenRunes, forward);
let rune = text[index_];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
if (normalize) {
rune = normalizeRune(rune);
}
const pidx_ = indexAt(pidx, lenPattern, forward);
const pchar = pattern[pidx_];
if (pchar === rune) {
if (pidx_ === 0) {
bonus = bonusAt(text, index_);
}
pidx++;
if (pidx === lenPattern) {
if (bonus > bestBonus) {
bestPos = index;
bestBonus = bonus;
}
if (bonus === BONUS_BOUNDARY) {
break;
}
index -= pidx - 1;
pidx = 0;
bonus = 0;
}
} else {
index -= pidx;
pidx = 0;
bonus = 0;
}
}
if (bestPos >= 0) {
let sidx = 0, eidx = 0;
if (forward) {
sidx = bestPos - lenPattern + 1;
eidx = bestPos + 1;
} else {
sidx = lenRunes - (bestPos + 1);
eidx = lenRunes - (bestPos - lenPattern + 1);
}
const [score] = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false);
return [{ start: sidx, end: eidx, score }, null];
}
return [{ start: -1, end: -1, score: 0 }, null];
};
const SLAB_16_SIZE = 100 * 1024;
const SLAB_32_SIZE = 2048;
function makeSlab(size16, size32) {
return {
i16: new Int16Array(size16),
i32: new Int32Array(size32)
};
}
const slab = makeSlab(SLAB_16_SIZE, SLAB_32_SIZE);
const buildPatternForBasicMatch = (query, casing, normalize) => {
let caseSensitive = false;
switch (casing) {
case "smart-case":
if (query.toLowerCase() !== query) {
caseSensitive = true;
}
break;
case "case-sensitive":
caseSensitive = true;
break;
case "case-insensitive":
query = query.toLowerCase();
caseSensitive = false;
break;
}
let queryRunes = strToRunes(query);
if (normalize) {
queryRunes = queryRunes.map(normalizeRune);
}
return {
queryRunes,
caseSensitive
};
};
function getResultFromScoreMap(scoreMap, limit) {
const scoresInDesc = Object.keys(scoreMap).map((v) => parseInt(v, 10)).sort((a, b) => b - a);
let result = [];
for (const score of scoresInDesc) {
result = result.concat(scoreMap[score]);
if (result.length >= limit) {
break;
}
}
return result;
}
function getBasicMatchIter(scoreMap, queryRunes, caseSensitive) {
return (idx) => {
const itemRunes = this.runesList[idx];
if (queryRunes.length > itemRunes.length)
return;
let [match, positions] = this.algoFn(
caseSensitive,
this.opts.normalize,
this.opts.forward,
itemRunes,
queryRunes,
true,
slab
);
if (match.start === -1)
return;
if (this.opts.fuzzy === false) {
positions = /* @__PURE__ */ new Set();
for (let position = match.start; position < match.end; ++position) {
positions.add(position);
}
}
const scoreKey = this.opts.sort ? match.score : 0;
if (scoreMap[scoreKey] === void 0) {
scoreMap[scoreKey] = [];
}
scoreMap[scoreKey].push({
item: this.items[idx],
...match,
positions: positions != null ? positions : /* @__PURE__ */ new Set()
});
};
}
function basicMatch(query) {
const { queryRunes, caseSensitive } = buildPatternForBasicMatch(
query,
this.opts.casing,
this.opts.normalize
);
const scoreMap = {};
const iter2 = getBasicMatchIter.bind(this)(
scoreMap,
queryRunes,
caseSensitive
);
for (let i = 0, len = this.runesList.length; i < len; ++i) {
iter2(i);
}
return getResultFromScoreMap(scoreMap, this.opts.limit);
}
const defaultOpts = {
limit: Infinity,
selector: (v) => v,
casing: "smart-case",
normalize: true,
fuzzy: "v2",
tiebreakers: [],
sort: true,
forward: true
};
class BaseFinder {
constructor(list, ...optionsTuple) {
this.opts = { ...defaultOpts, ...optionsTuple[0] };
this.items = list;
this.runesList = list.map((item) => strToRunes(this.opts.selector(item).normalize()));
this.algoFn = exactMatchNaive;
switch (this.opts.fuzzy) {
case "v2":
this.algoFn = fuzzyMatchV2;
break;
case "v1":
this.algoFn = fuzzyMatchV1;
break;
}
}
}
const syncDefaultOpts = {
...defaultOpts,
match: basicMatch
};
class SyncFinder extends BaseFinder {
constructor(list, ...optionsTuple) {
super(list, ...optionsTuple);
this.opts = { ...syncDefaultOpts, ...optionsTuple[0] };
}
find(query) {
if (query.length === 0 || this.items.length === 0)
return this.items.slice(0, this.opts.limit).map(createResultItemWithEmptyPos);
query = query.normalize();
let result = this.opts.match.bind(this)(query);
return postProcessResultItems(result, this.opts);
}
}
const createResultItemWithEmptyPos = (item) => ({
item,
start: -1,
end: -1,
score: 0,
positions: /* @__PURE__ */ new Set()
});
function postProcessResultItems(result, opts) {
if (opts.sort) {
const { selector } = opts;
result.sort((a, b) => {
if (a.score === b.score) {
for (const tiebreaker of opts.tiebreakers) {
const diff = tiebreaker(a, b, selector);
if (diff !== 0) {
return diff;
}
}
}
return 0;
});
}
if (Number.isFinite(opts.limit)) {
result.splice(opts.limit);
}
return result;
}
function byLengthAsc(a, b, selector) {
return selector(a.item).length - selector(b.item).length;
}
class Fzf {
constructor(list, ...optionsTuple) {
this.finder = new SyncFinder(list, ...optionsTuple);
this.find = this.finder.find.bind(this.finder);
}
}
exports.Fzf = Fzf;
exports.byLengthAsc = byLengthAsc;
+23
View File
@@ -0,0 +1,23 @@
import fs from 'node:fs';
import { resolve } from 'node:path';
import process from 'node:process';
function getPackageJSON(ctx) {
const cwd = ctx?.cwd ?? process.cwd();
const path = resolve(cwd, "package.json");
if (fs.existsSync(path)) {
try {
const raw = fs.readFileSync(path, "utf-8");
const data = JSON.parse(raw);
return data;
} catch (e) {
if (!ctx?.programmatic) {
console.warn("Failed to parse package.json");
process.exit(1);
}
throw e;
}
}
}
export { getPackageJSON as g };
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+918
View File
@@ -0,0 +1,918 @@
/** @license
* fzf v0.5.2
* Copyright (c) 2021 Ajit
* Licensed under BSD 3-Clause
*/
const normalized = {
216: "O",
223: "s",
248: "o",
273: "d",
295: "h",
305: "i",
320: "l",
322: "l",
359: "t",
383: "s",
384: "b",
385: "B",
387: "b",
390: "O",
392: "c",
393: "D",
394: "D",
396: "d",
398: "E",
400: "E",
402: "f",
403: "G",
407: "I",
409: "k",
410: "l",
412: "M",
413: "N",
414: "n",
415: "O",
421: "p",
427: "t",
429: "t",
430: "T",
434: "V",
436: "y",
438: "z",
477: "e",
485: "g",
544: "N",
545: "d",
549: "z",
564: "l",
565: "n",
566: "t",
567: "j",
570: "A",
571: "C",
572: "c",
573: "L",
574: "T",
575: "s",
576: "z",
579: "B",
580: "U",
581: "V",
582: "E",
583: "e",
584: "J",
585: "j",
586: "Q",
587: "q",
588: "R",
589: "r",
590: "Y",
591: "y",
592: "a",
593: "a",
595: "b",
596: "o",
597: "c",
598: "d",
599: "d",
600: "e",
603: "e",
604: "e",
605: "e",
606: "e",
607: "j",
608: "g",
609: "g",
610: "G",
613: "h",
614: "h",
616: "i",
618: "I",
619: "l",
620: "l",
621: "l",
623: "m",
624: "m",
625: "m",
626: "n",
627: "n",
628: "N",
629: "o",
633: "r",
634: "r",
635: "r",
636: "r",
637: "r",
638: "r",
639: "r",
640: "R",
641: "R",
642: "s",
647: "t",
648: "t",
649: "u",
651: "v",
652: "v",
653: "w",
654: "y",
655: "Y",
656: "z",
657: "z",
663: "c",
665: "B",
666: "e",
667: "G",
668: "H",
669: "j",
670: "k",
671: "L",
672: "q",
686: "h",
867: "a",
868: "e",
869: "i",
870: "o",
871: "u",
872: "c",
873: "d",
874: "h",
875: "m",
876: "r",
877: "t",
878: "v",
879: "x",
7424: "A",
7427: "B",
7428: "C",
7429: "D",
7431: "E",
7432: "e",
7433: "i",
7434: "J",
7435: "K",
7436: "L",
7437: "M",
7438: "N",
7439: "O",
7440: "O",
7441: "o",
7442: "o",
7443: "o",
7446: "o",
7447: "o",
7448: "P",
7449: "R",
7450: "R",
7451: "T",
7452: "U",
7453: "u",
7454: "u",
7455: "m",
7456: "V",
7457: "W",
7458: "Z",
7522: "i",
7523: "r",
7524: "u",
7525: "v",
7834: "a",
7835: "s",
8305: "i",
8341: "h",
8342: "k",
8343: "l",
8344: "m",
8345: "n",
8346: "p",
8347: "s",
8348: "t",
8580: "c"
};
for (let i = "\u0300".codePointAt(0); i <= "\u036F".codePointAt(0); ++i) {
const diacritic = String.fromCodePoint(i);
for (const asciiChar of "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
const withDiacritic = (asciiChar + diacritic).normalize();
const withDiacriticCodePoint = withDiacritic.codePointAt(0);
if (withDiacriticCodePoint > 126) {
normalized[withDiacriticCodePoint] = asciiChar;
}
}
}
const ranges = {
a: [7844, 7863],
e: [7870, 7879],
o: [7888, 7907],
u: [7912, 7921]
};
for (const lowerChar of Object.keys(ranges)) {
const upperChar = lowerChar.toUpperCase();
for (let i = ranges[lowerChar][0]; i <= ranges[lowerChar][1]; ++i) {
normalized[i] = i % 2 === 0 ? upperChar : lowerChar;
}
}
function normalizeRune(rune) {
if (rune < 192 || rune > 8580) {
return rune;
}
const normalizedChar = normalized[rune];
if (normalizedChar !== void 0)
return normalizedChar.codePointAt(0);
return rune;
}
function toShort(number) {
return number;
}
function toInt(number) {
return number;
}
function maxInt16(num1, num2) {
return num1 > num2 ? num1 : num2;
}
const strToRunes = (str) => str.split("").map((s) => s.codePointAt(0));
const whitespaceRunes = new Set(
" \f\n\r \v\xA0\u1680\u2028\u2029\u202F\u205F\u3000\uFEFF".split("").map((v) => v.codePointAt(0))
);
for (let codePoint = "\u2000".codePointAt(0); codePoint <= "\u200A".codePointAt(0); codePoint++) {
whitespaceRunes.add(codePoint);
}
const MAX_ASCII = "\x7F".codePointAt(0);
const CAPITAL_A_RUNE = "A".codePointAt(0);
const CAPITAL_Z_RUNE = "Z".codePointAt(0);
const SMALL_A_RUNE = "a".codePointAt(0);
const SMALL_Z_RUNE = "z".codePointAt(0);
const NUMERAL_ZERO_RUNE = "0".codePointAt(0);
const NUMERAL_NINE_RUNE = "9".codePointAt(0);
function indexAt(index, max, forward) {
if (forward) {
return index;
}
return max - index - 1;
}
const SCORE_MATCH = 16, SCORE_GAP_START = -3, SCORE_GAP_EXTENTION = -1, BONUS_BOUNDARY = SCORE_MATCH / 2, BONUS_NON_WORD = SCORE_MATCH / 2, BONUS_CAMEL_123 = BONUS_BOUNDARY + SCORE_GAP_EXTENTION, BONUS_CONSECUTIVE = -(SCORE_GAP_START + SCORE_GAP_EXTENTION), BONUS_FIRST_CHAR_MULTIPLIER = 2;
function createPosSet(withPos) {
if (withPos) {
return /* @__PURE__ */ new Set();
}
return null;
}
function alloc16(offset, slab2, size) {
if (slab2 !== null && slab2.i16.length > offset + size) {
const subarray = slab2.i16.subarray(offset, offset + size);
return [offset + size, subarray];
}
return [offset, new Int16Array(size)];
}
function alloc32(offset, slab2, size) {
if (slab2 !== null && slab2.i32.length > offset + size) {
const subarray = slab2.i32.subarray(offset, offset + size);
return [offset + size, subarray];
}
return [offset, new Int32Array(size)];
}
function charClassOfAscii(rune) {
if (rune >= SMALL_A_RUNE && rune <= SMALL_Z_RUNE) {
return 1;
} else if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
return 2;
} else if (rune >= NUMERAL_ZERO_RUNE && rune <= NUMERAL_NINE_RUNE) {
return 4;
} else {
return 0;
}
}
function charClassOfNonAscii(rune) {
const char = String.fromCodePoint(rune);
if (char !== char.toUpperCase()) {
return 1;
} else if (char !== char.toLowerCase()) {
return 2;
} else if (char.match(/\p{Number}/gu) !== null) {
return 4;
} else if (char.match(/\p{Letter}/gu) !== null) {
return 3;
}
return 0;
}
function charClassOf(rune) {
if (rune <= MAX_ASCII) {
return charClassOfAscii(rune);
}
return charClassOfNonAscii(rune);
}
function bonusFor(prevClass, currClass) {
if (prevClass === 0 && currClass !== 0) {
return BONUS_BOUNDARY;
} else if (prevClass === 1 && currClass === 2 || prevClass !== 4 && currClass === 4) {
return BONUS_CAMEL_123;
} else if (currClass === 0) {
return BONUS_NON_WORD;
}
return 0;
}
function bonusAt(input, idx) {
if (idx === 0) {
return BONUS_BOUNDARY;
}
return bonusFor(charClassOf(input[idx - 1]), charClassOf(input[idx]));
}
function trySkip(input, caseSensitive, char, from) {
let rest = input.slice(from);
let idx = rest.indexOf(char);
if (idx === 0) {
return from;
}
if (!caseSensitive && char >= SMALL_A_RUNE && char <= SMALL_Z_RUNE) {
if (idx > 0) {
rest = rest.slice(0, idx);
}
const uidx = rest.indexOf(char - 32);
if (uidx >= 0) {
idx = uidx;
}
}
if (idx < 0) {
return -1;
}
return from + idx;
}
function isAscii(runes) {
for (const rune of runes) {
if (rune >= 128) {
return false;
}
}
return true;
}
function asciiFuzzyIndex(input, pattern, caseSensitive) {
if (!isAscii(input)) {
return 0;
}
if (!isAscii(pattern)) {
return -1;
}
let firstIdx = 0, idx = 0;
for (let pidx = 0; pidx < pattern.length; pidx++) {
idx = trySkip(input, caseSensitive, pattern[pidx], idx);
if (idx < 0) {
return -1;
}
if (pidx === 0 && idx > 0) {
firstIdx = idx - 1;
}
idx++;
}
return firstIdx;
}
const fuzzyMatchV2 = (caseSensitive, normalize, forward, input, pattern, withPos, slab2) => {
const M = pattern.length;
if (M === 0) {
return [{ start: 0, end: 0, score: 0 }, createPosSet(withPos)];
}
const N = input.length;
if (slab2 !== null && N * M > slab2.i16.length) {
return fuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos);
}
const idx = asciiFuzzyIndex(input, pattern, caseSensitive);
if (idx < 0) {
return [{ start: -1, end: -1, score: 0 }, null];
}
let offset16 = 0, offset32 = 0, H0 = null, C0 = null, B = null, F = null;
[offset16, H0] = alloc16(offset16, slab2, N);
[offset16, C0] = alloc16(offset16, slab2, N);
[offset16, B] = alloc16(offset16, slab2, N);
[offset32, F] = alloc32(offset32, slab2, M);
const [, T] = alloc32(offset32, slab2, N);
for (let i = 0; i < T.length; i++) {
T[i] = input[i];
}
let maxScore = toShort(0), maxScorePos = 0;
let pidx = 0, lastIdx = 0;
const pchar0 = pattern[0];
let pchar = pattern[0], prevH0 = toShort(0), prevCharClass = 0, inGap = false;
let Tsub = T.subarray(idx);
let H0sub = H0.subarray(idx).subarray(0, Tsub.length), C0sub = C0.subarray(idx).subarray(0, Tsub.length), Bsub = B.subarray(idx).subarray(0, Tsub.length);
for (let [off, char] of Tsub.entries()) {
let charClass = null;
if (char <= MAX_ASCII) {
charClass = charClassOfAscii(char);
if (!caseSensitive && charClass === 2) {
char += 32;
}
} else {
charClass = charClassOfNonAscii(char);
if (!caseSensitive && charClass === 2) {
char = String.fromCodePoint(char).toLowerCase().codePointAt(0);
}
if (normalize) {
char = normalizeRune(char);
}
}
Tsub[off] = char;
const bonus = bonusFor(prevCharClass, charClass);
Bsub[off] = bonus;
prevCharClass = charClass;
if (char === pchar) {
if (pidx < M) {
F[pidx] = toInt(idx + off);
pidx++;
pchar = pattern[Math.min(pidx, M - 1)];
}
lastIdx = idx + off;
}
if (char === pchar0) {
const score = SCORE_MATCH + bonus * BONUS_FIRST_CHAR_MULTIPLIER;
H0sub[off] = score;
C0sub[off] = 1;
if (M === 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
maxScore = score;
maxScorePos = idx + off;
if (forward && bonus === BONUS_BOUNDARY) {
break;
}
}
inGap = false;
} else {
if (inGap) {
H0sub[off] = maxInt16(prevH0 + SCORE_GAP_EXTENTION, 0);
} else {
H0sub[off] = maxInt16(prevH0 + SCORE_GAP_START, 0);
}
C0sub[off] = 0;
inGap = true;
}
prevH0 = H0sub[off];
}
if (pidx !== M) {
return [{ start: -1, end: -1, score: 0 }, null];
}
if (M === 1) {
const result = {
start: maxScorePos,
end: maxScorePos + 1,
score: maxScore
};
if (!withPos) {
return [result, null];
}
const pos2 = /* @__PURE__ */ new Set();
pos2.add(maxScorePos);
return [result, pos2];
}
const f0 = F[0];
const width = lastIdx - f0 + 1;
let H = null;
[offset16, H] = alloc16(offset16, slab2, width * M);
{
const toCopy = H0.subarray(f0, lastIdx + 1);
for (const [i, v] of toCopy.entries()) {
H[i] = v;
}
}
let [, C] = alloc16(offset16, slab2, width * M);
{
const toCopy = C0.subarray(f0, lastIdx + 1);
for (const [i, v] of toCopy.entries()) {
C[i] = v;
}
}
const Fsub = F.subarray(1);
const Psub = pattern.slice(1).slice(0, Fsub.length);
for (const [off, f] of Fsub.entries()) {
let inGap2 = false;
const pchar2 = Psub[off], pidx2 = off + 1, row = pidx2 * width, Tsub2 = T.subarray(f, lastIdx + 1), Bsub2 = B.subarray(f).subarray(0, Tsub2.length), Csub = C.subarray(row + f - f0).subarray(0, Tsub2.length), Cdiag = C.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hsub = H.subarray(row + f - f0).subarray(0, Tsub2.length), Hdiag = H.subarray(row + f - f0 - 1 - width).subarray(0, Tsub2.length), Hleft = H.subarray(row + f - f0 - 1).subarray(0, Tsub2.length);
Hleft[0] = 0;
for (const [off2, char] of Tsub2.entries()) {
const col = off2 + f;
let s1 = 0, s2 = 0, consecutive = 0;
if (inGap2) {
s2 = Hleft[off2] + SCORE_GAP_EXTENTION;
} else {
s2 = Hleft[off2] + SCORE_GAP_START;
}
if (pchar2 === char) {
s1 = Hdiag[off2] + SCORE_MATCH;
let b = Bsub2[off2];
consecutive = Cdiag[off2] + 1;
if (b === BONUS_BOUNDARY) {
consecutive = 1;
} else if (consecutive > 1) {
b = maxInt16(b, maxInt16(BONUS_CONSECUTIVE, B[col - consecutive + 1]));
}
if (s1 + b < s2) {
s1 += Bsub2[off2];
consecutive = 0;
} else {
s1 += b;
}
}
Csub[off2] = consecutive;
inGap2 = s1 < s2;
const score = maxInt16(maxInt16(s1, s2), 0);
if (pidx2 === M - 1 && (forward && score > maxScore || !forward && score >= maxScore)) {
maxScore = score;
maxScorePos = col;
}
Hsub[off2] = score;
}
}
const pos = createPosSet(withPos);
let j = f0;
if (withPos && pos !== null) {
let i = M - 1;
j = maxScorePos;
let preferMatch = true;
while (true) {
const I = i * width, j0 = j - f0, s = H[I + j0];
let s1 = 0, s2 = 0;
if (i > 0 && j >= F[i]) {
s1 = H[I - width + j0 - 1];
}
if (j > F[i]) {
s2 = H[I + j0 - 1];
}
if (s > s1 && (s > s2 || s === s2 && preferMatch)) {
pos.add(j);
if (i === 0) {
break;
}
i--;
}
preferMatch = C[I + j0] > 1 || I + width + j0 + 1 < C.length && C[I + width + j0 + 1] > 0;
j--;
}
}
return [{ start: j, end: maxScorePos + 1, score: maxScore }, pos];
};
function calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, withPos) {
let pidx = 0, score = 0, inGap = false, consecutive = 0, firstBonus = toShort(0);
const pos = createPosSet(withPos);
let prevCharClass = 0;
if (sidx > 0) {
prevCharClass = charClassOf(text[sidx - 1]);
}
for (let idx = sidx; idx < eidx; idx++) {
let rune = text[idx];
const charClass = charClassOf(rune);
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
if (normalize) {
rune = normalizeRune(rune);
}
if (rune === pattern[pidx]) {
if (withPos && pos !== null) {
pos.add(idx);
}
score += SCORE_MATCH;
let bonus = bonusFor(prevCharClass, charClass);
if (consecutive === 0) {
firstBonus = bonus;
} else {
if (bonus === BONUS_BOUNDARY) {
firstBonus = bonus;
}
bonus = maxInt16(maxInt16(bonus, firstBonus), BONUS_CONSECUTIVE);
}
if (pidx === 0) {
score += bonus * BONUS_FIRST_CHAR_MULTIPLIER;
} else {
score += bonus;
}
inGap = false;
consecutive++;
pidx++;
} else {
if (inGap) {
score += SCORE_GAP_EXTENTION;
} else {
score += SCORE_GAP_START;
}
inGap = true;
consecutive = 0;
firstBonus = 0;
}
prevCharClass = charClass;
}
return [score, pos];
}
const fuzzyMatchV1 = (caseSensitive, normalize, forward, text, pattern, withPos, slab2) => {
if (pattern.length === 0) {
return [{ start: 0, end: 0, score: 0 }, null];
}
if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) {
return [{ start: -1, end: -1, score: 0 }, null];
}
let pidx = 0, sidx = -1, eidx = -1;
const lenRunes = text.length;
const lenPattern = pattern.length;
for (let index = 0; index < lenRunes; index++) {
let rune = text[indexAt(index, lenRunes, forward)];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
if (normalize) {
rune = normalizeRune(rune);
}
const pchar = pattern[indexAt(pidx, lenPattern, forward)];
if (rune === pchar) {
if (sidx < 0) {
sidx = index;
}
pidx++;
if (pidx === lenPattern) {
eidx = index + 1;
break;
}
}
}
if (sidx >= 0 && eidx >= 0) {
pidx--;
for (let index = eidx - 1; index >= sidx; index--) {
const tidx = indexAt(index, lenRunes, forward);
let rune = text[tidx];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
const pidx_ = indexAt(pidx, lenPattern, forward);
const pchar = pattern[pidx_];
if (rune === pchar) {
pidx--;
if (pidx < 0) {
sidx = index;
break;
}
}
}
if (!forward) {
const sidxTemp = sidx;
sidx = lenRunes - eidx;
eidx = lenRunes - sidxTemp;
}
const [score, pos] = calculateScore(
caseSensitive,
normalize,
text,
pattern,
sidx,
eidx,
withPos
);
return [{ start: sidx, end: eidx, score }, pos];
}
return [{ start: -1, end: -1, score: 0 }, null];
};
const exactMatchNaive = (caseSensitive, normalize, forward, text, pattern, withPos, slab2) => {
if (pattern.length === 0) {
return [{ start: 0, end: 0, score: 0 }, null];
}
const lenRunes = text.length;
const lenPattern = pattern.length;
if (lenRunes < lenPattern) {
return [{ start: -1, end: -1, score: 0 }, null];
}
if (asciiFuzzyIndex(text, pattern, caseSensitive) < 0) {
return [{ start: -1, end: -1, score: 0 }, null];
}
let pidx = 0;
let bestPos = -1, bonus = toShort(0), bestBonus = toShort(-1);
for (let index = 0; index < lenRunes; index++) {
const index_ = indexAt(index, lenRunes, forward);
let rune = text[index_];
if (!caseSensitive) {
if (rune >= CAPITAL_A_RUNE && rune <= CAPITAL_Z_RUNE) {
rune += 32;
} else if (rune > MAX_ASCII) {
rune = String.fromCodePoint(rune).toLowerCase().codePointAt(0);
}
}
if (normalize) {
rune = normalizeRune(rune);
}
const pidx_ = indexAt(pidx, lenPattern, forward);
const pchar = pattern[pidx_];
if (pchar === rune) {
if (pidx_ === 0) {
bonus = bonusAt(text, index_);
}
pidx++;
if (pidx === lenPattern) {
if (bonus > bestBonus) {
bestPos = index;
bestBonus = bonus;
}
if (bonus === BONUS_BOUNDARY) {
break;
}
index -= pidx - 1;
pidx = 0;
bonus = 0;
}
} else {
index -= pidx;
pidx = 0;
bonus = 0;
}
}
if (bestPos >= 0) {
let sidx = 0, eidx = 0;
if (forward) {
sidx = bestPos - lenPattern + 1;
eidx = bestPos + 1;
} else {
sidx = lenRunes - (bestPos + 1);
eidx = lenRunes - (bestPos - lenPattern + 1);
}
const [score] = calculateScore(caseSensitive, normalize, text, pattern, sidx, eidx, false);
return [{ start: sidx, end: eidx, score }, null];
}
return [{ start: -1, end: -1, score: 0 }, null];
};
const SLAB_16_SIZE = 100 * 1024;
const SLAB_32_SIZE = 2048;
function makeSlab(size16, size32) {
return {
i16: new Int16Array(size16),
i32: new Int32Array(size32)
};
}
const slab = makeSlab(SLAB_16_SIZE, SLAB_32_SIZE);
const buildPatternForBasicMatch = (query, casing, normalize) => {
let caseSensitive = false;
switch (casing) {
case "smart-case":
if (query.toLowerCase() !== query) {
caseSensitive = true;
}
break;
case "case-sensitive":
caseSensitive = true;
break;
case "case-insensitive":
query = query.toLowerCase();
caseSensitive = false;
break;
}
let queryRunes = strToRunes(query);
if (normalize) {
queryRunes = queryRunes.map(normalizeRune);
}
return {
queryRunes,
caseSensitive
};
};
function getResultFromScoreMap(scoreMap, limit) {
const scoresInDesc = Object.keys(scoreMap).map((v) => parseInt(v, 10)).sort((a, b) => b - a);
let result = [];
for (const score of scoresInDesc) {
result = result.concat(scoreMap[score]);
if (result.length >= limit) {
break;
}
}
return result;
}
function getBasicMatchIter(scoreMap, queryRunes, caseSensitive) {
return (idx) => {
const itemRunes = this.runesList[idx];
if (queryRunes.length > itemRunes.length)
return;
let [match, positions] = this.algoFn(
caseSensitive,
this.opts.normalize,
this.opts.forward,
itemRunes,
queryRunes,
true,
slab
);
if (match.start === -1)
return;
if (this.opts.fuzzy === false) {
positions = /* @__PURE__ */ new Set();
for (let position = match.start; position < match.end; ++position) {
positions.add(position);
}
}
const scoreKey = this.opts.sort ? match.score : 0;
if (scoreMap[scoreKey] === void 0) {
scoreMap[scoreKey] = [];
}
scoreMap[scoreKey].push({
item: this.items[idx],
...match,
positions: positions != null ? positions : /* @__PURE__ */ new Set()
});
};
}
function basicMatch(query) {
const { queryRunes, caseSensitive } = buildPatternForBasicMatch(
query,
this.opts.casing,
this.opts.normalize
);
const scoreMap = {};
const iter2 = getBasicMatchIter.bind(this)(
scoreMap,
queryRunes,
caseSensitive
);
for (let i = 0, len = this.runesList.length; i < len; ++i) {
iter2(i);
}
return getResultFromScoreMap(scoreMap, this.opts.limit);
}
const defaultOpts = {
limit: Infinity,
selector: (v) => v,
casing: "smart-case",
normalize: true,
fuzzy: "v2",
tiebreakers: [],
sort: true,
forward: true
};
class BaseFinder {
constructor(list, ...optionsTuple) {
this.opts = { ...defaultOpts, ...optionsTuple[0] };
this.items = list;
this.runesList = list.map((item) => strToRunes(this.opts.selector(item).normalize()));
this.algoFn = exactMatchNaive;
switch (this.opts.fuzzy) {
case "v2":
this.algoFn = fuzzyMatchV2;
break;
case "v1":
this.algoFn = fuzzyMatchV1;
break;
}
}
}
const syncDefaultOpts = {
...defaultOpts,
match: basicMatch
};
class SyncFinder extends BaseFinder {
constructor(list, ...optionsTuple) {
super(list, ...optionsTuple);
this.opts = { ...syncDefaultOpts, ...optionsTuple[0] };
}
find(query) {
if (query.length === 0 || this.items.length === 0)
return this.items.slice(0, this.opts.limit).map(createResultItemWithEmptyPos);
query = query.normalize();
let result = this.opts.match.bind(this)(query);
return postProcessResultItems(result, this.opts);
}
}
const createResultItemWithEmptyPos = (item) => ({
item,
start: -1,
end: -1,
score: 0,
positions: /* @__PURE__ */ new Set()
});
function postProcessResultItems(result, opts) {
if (opts.sort) {
const { selector } = opts;
result.sort((a, b) => {
if (a.score === b.score) {
for (const tiebreaker of opts.tiebreakers) {
const diff = tiebreaker(a, b, selector);
if (diff !== 0) {
return diff;
}
}
}
return 0;
});
}
if (Number.isFinite(opts.limit)) {
result.splice(opts.limit);
}
return result;
}
function byLengthAsc(a, b, selector) {
return selector(a.item).length - selector(b.item).length;
}
class Fzf {
constructor(list, ...optionsTuple) {
this.finder = new SyncFinder(list, ...optionsTuple);
this.find = this.finder.find.bind(this.finder);
}
}
export { Fzf as F, byLengthAsc as b };
+30
View File
@@ -0,0 +1,30 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const process = require('node:process');
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
const fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
const process__default = /*#__PURE__*/_interopDefaultCompat(process);
function getPackageJSON(ctx) {
const cwd = ctx?.cwd ?? process__default.cwd();
const path$1 = path.resolve(cwd, "package.json");
if (fs__default.existsSync(path$1)) {
try {
const raw = fs__default.readFileSync(path$1, "utf-8");
const data = JSON.parse(raw);
return data;
} catch (e) {
if (!ctx?.programmatic) {
console.warn("Failed to parse package.json");
process__default.exit(1);
}
throw e;
}
}
}
exports.getPackageJSON = getPackageJSON;
+83
View File
@@ -0,0 +1,83 @@
{
"name": "@antfu/ni",
"type": "module",
"version": "0.23.2",
"packageManager": "pnpm@9.15.1",
"description": "Use the right package manager",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"homepage": "https://github.com/antfu-collective/ni#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu-collective/ni.git"
},
"bugs": {
"url": "https://github.com/antfu-collective/ni/issues"
},
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"bin": {
"ni": "bin/ni.mjs",
"nci": "bin/nci.mjs",
"nr": "bin/nr.mjs",
"nu": "bin/nu.mjs",
"nlx": "bin/nlx.mjs",
"na": "bin/na.mjs",
"nun": "bin/nun.mjs"
},
"files": [
"bin",
"dist"
],
"scripts": {
"prepublishOnly": "npm run build",
"dev": "tsx src/commands/ni.ts",
"nr": "tsx src/commands/nr.ts",
"build": "unbuild",
"stub": "unbuild --stub",
"release": "bumpp && npm publish",
"typecheck": "tsc",
"prepare": "npx simple-git-hooks",
"lint": "eslint .",
"test": "vitest"
},
"devDependencies": {
"@antfu/eslint-config": "^3.12.0",
"@posva/prompts": "^2.4.4",
"@types/fs-extra": "^11.0.4",
"@types/ini": "^4.1.1",
"@types/node": "^22.10.2",
"@types/which": "^3.0.4",
"bumpp": "^9.9.1",
"eslint": "^9.17.0",
"fs-extra": "^11.2.0",
"fzf": "^0.5.2",
"ini": "^5.0.0",
"lint-staged": "^15.2.11",
"package-manager-detector": "^0.2.8",
"picocolors": "^1.1.1",
"simple-git-hooks": "^2.11.1",
"taze": "^0.18.0",
"terminal-link": "^3.0.0",
"tinyexec": "^0.3.1",
"tinyglobby": "^0.2.10",
"tsx": "^4.19.2",
"typescript": "^5.7.2",
"unbuild": "^3.0.1",
"vitest": "^2.1.8",
"which": "^5.0.0"
},
"simple-git-hooks": {
"pre-commit": "pnpm lint-staged"
},
"lint-staged": {
"*": "eslint --fix"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+24
View File
@@ -0,0 +1,24 @@
# @antfu/utils
[![NPM version](https://img.shields.io/npm/v/@antfu/utils?color=a1b858&label=)](https://www.npmjs.com/package/@antfu/utils)
[![Docs](https://img.shields.io/badge/docs-green)](https://www.jsdocs.io/package/@antfu/utils)
Opinionated collection of common JavaScript / TypeScript utils by [@antfu](https://github.com/antfu).
- Tree-shakable ESM
- Fully typed - with TSDocs
- Type utilities - `Arrayable<T>`, `ElementOf<T>`, etc.
> This package is designed to be used as `devDependencies` and bundled into your dist.
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)
+844
View File
@@ -0,0 +1,844 @@
'use strict';
function clamp(n, min, max) {
return Math.min(max, Math.max(min, n));
}
function sum(...args) {
return flattenArrayable(args).reduce((a, b) => a + b, 0);
}
function lerp(min, max, t) {
const interpolation = clamp(t, 0, 1);
return min + (max - min) * interpolation;
}
function remap(n, inMin, inMax, outMin, outMax) {
const interpolation = (n - inMin) / (inMax - inMin);
return lerp(outMin, outMax, interpolation);
}
function toArray(array) {
array = array ?? [];
return Array.isArray(array) ? array : [array];
}
function flattenArrayable(array) {
return toArray(array).flat(1);
}
function mergeArrayable(...args) {
return args.flatMap((i) => toArray(i));
}
function partition(array, ...filters) {
const result = Array.from({ length: filters.length + 1 }).fill(null).map(() => []);
array.forEach((e, idx, arr) => {
let i = 0;
for (const filter of filters) {
if (filter(e, idx, arr)) {
result[i].push(e);
return;
}
i += 1;
}
result[i].push(e);
});
return result;
}
function uniq(array) {
return Array.from(new Set(array));
}
function uniqueBy(array, equalFn) {
return array.reduce((acc, cur) => {
const index = acc.findIndex((item) => equalFn(cur, item));
if (index === -1)
acc.push(cur);
return acc;
}, []);
}
function last(array) {
return at(array, -1);
}
function remove(array, value) {
if (!array)
return false;
const index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
return true;
}
return false;
}
function at(array, index) {
const len = array.length;
if (!len)
return void 0;
if (index < 0)
index += len;
return array[index];
}
function range(...args) {
let start, stop, step;
if (args.length === 1) {
start = 0;
step = 1;
[stop] = args;
} else {
[start, stop, step = 1] = args;
}
const arr = [];
let current = start;
while (current < stop) {
arr.push(current);
current += step || 1;
}
return arr;
}
function move(arr, from, to) {
arr.splice(to, 0, arr.splice(from, 1)[0]);
return arr;
}
function clampArrayRange(n, arr) {
return clamp(n, 0, arr.length - 1);
}
function sample(arr, quantity) {
return Array.from({ length: quantity }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function assert(condition, message) {
if (!condition)
throw new Error(message);
}
const toString = (v) => Object.prototype.toString.call(v);
function getTypeName(v) {
if (v === null)
return "null";
const type = toString(v).slice(8, -1).toLowerCase();
return typeof v === "object" || typeof v === "function" ? type : typeof v;
}
function noop() {
}
function isDeepEqual(value1, value2) {
const type1 = getTypeName(value1);
const type2 = getTypeName(value2);
if (type1 !== type2)
return false;
if (type1 === "array") {
if (value1.length !== value2.length)
return false;
return value1.every((item, i) => {
return isDeepEqual(item, value2[i]);
});
}
if (type1 === "object") {
const keyArr = Object.keys(value1);
if (keyArr.length !== Object.keys(value2).length)
return false;
return keyArr.every((key) => {
return isDeepEqual(value1[key], value2[key]);
});
}
return Object.is(value1, value2);
}
function notNullish(v) {
return v != null;
}
function noNull(v) {
return v !== null;
}
function notUndefined(v) {
return v !== void 0;
}
function isTruthy(v) {
return Boolean(v);
}
const isDef = (val) => typeof val !== "undefined";
const isBoolean = (val) => typeof val === "boolean";
const isFunction = (val) => typeof val === "function";
const isNumber = (val) => typeof val === "number";
const isString = (val) => typeof val === "string";
const isObject = (val) => toString(val) === "[object Object]";
const isUndefined = (val) => toString(val) === "[object Undefined]";
const isNull = (val) => toString(val) === "[object Null]";
const isRegExp = (val) => toString(val) === "[object RegExp]";
const isDate = (val) => toString(val) === "[object Date]";
const isWindow = (val) => typeof window !== "undefined" && toString(val) === "[object Window]";
const isBrowser = typeof window !== "undefined";
function slash(str) {
return str.replace(/\\/g, "/");
}
function ensurePrefix(prefix, str) {
if (!str.startsWith(prefix))
return prefix + str;
return str;
}
function ensureSuffix(suffix, str) {
if (!str.endsWith(suffix))
return str + suffix;
return str;
}
function template(str, ...args) {
const [firstArg, fallback] = args;
if (isObject(firstArg)) {
const vars = firstArg;
return str.replace(/{([\w\d]+)}/g, (_, key) => vars[key] || ((typeof fallback === "function" ? fallback(key) : fallback) ?? key));
} else {
return str.replace(/{(\d+)}/g, (_, key) => {
const index = Number(key);
if (Number.isNaN(index))
return key;
return args[index];
});
}
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function randomStr(size = 16, dict = urlAlphabet) {
let id = "";
let i = size;
const len = dict.length;
while (i--)
id += dict[Math.random() * len | 0];
return id;
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1).toLowerCase();
}
const _reFullWs = /^\s*$/;
function unindent(str) {
const lines = (typeof str === "string" ? str : str[0]).split("\n");
const whitespaceLines = lines.map((line) => _reFullWs.test(line));
const commonIndent = lines.reduce((min, line, idx) => {
var _a;
if (whitespaceLines[idx])
return min;
const indent = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0].length;
return indent === void 0 ? min : Math.min(min, indent);
}, Number.POSITIVE_INFINITY);
let emptyLinesHead = 0;
while (emptyLinesHead < lines.length && whitespaceLines[emptyLinesHead])
emptyLinesHead++;
let emptyLinesTail = 0;
while (emptyLinesTail < lines.length && whitespaceLines[lines.length - emptyLinesTail - 1])
emptyLinesTail++;
return lines.slice(emptyLinesHead, lines.length - emptyLinesTail).map((line) => line.slice(commonIndent)).join("\n");
}
const timestamp = () => +Date.now();
function batchInvoke(functions) {
functions.forEach((fn) => fn && fn());
}
function invoke(fn) {
return fn();
}
function tap(value, callback) {
callback(value);
return value;
}
function objectMap(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish)
);
}
function isKeyOf(obj, k) {
return k in obj;
}
function objectKeys(obj) {
return Object.keys(obj);
}
function objectEntries(obj) {
return Object.entries(obj);
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
if (isMergableObject(target[key])) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
});
}
return deepMerge(target, ...sources);
}
function deepMergeWithArray(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (Array.isArray(target) && Array.isArray(source))
target.push(...source);
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (Array.isArray(source[key])) {
if (!target[key])
target[key] = [];
deepMergeWithArray(target[key], source[key]);
} else if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
deepMergeWithArray(target[key], source[key]);
} else {
target[key] = source[key];
}
});
}
return deepMergeWithArray(target, ...sources);
}
function isMergableObject(item) {
return isObject(item) && !Array.isArray(item);
}
function objectPick(obj, keys, omitUndefined = false) {
return keys.reduce((n, k) => {
if (k in obj) {
if (!omitUndefined || obj[k] !== void 0)
n[k] = obj[k];
}
return n;
}, {});
}
function clearUndefined(obj) {
Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {});
return obj;
}
function hasOwnProperty(obj, v) {
if (obj == null)
return false;
return Object.prototype.hasOwnProperty.call(obj, v);
}
function createSingletonPromise(fn) {
let _promise;
function wrapper() {
if (!_promise)
_promise = fn();
return _promise;
}
wrapper.reset = async () => {
const _prev = _promise;
_promise = void 0;
if (_prev)
await _prev;
};
return wrapper;
}
function sleep(ms, callback) {
return new Promise(
(resolve) => setTimeout(async () => {
await (callback == null ? void 0 : callback());
resolve();
}, ms)
);
}
function createPromiseLock() {
const locks = [];
return {
async run(fn) {
const p = fn();
locks.push(p);
try {
return await p;
} finally {
remove(locks, p);
}
},
async wait() {
await Promise.allSettled(locks);
},
isWaiting() {
return Boolean(locks.length);
},
clear() {
locks.length = 0;
}
};
}
function createControlledPromise() {
let resolve, reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
}
/* eslint-disable no-undefined,no-param-reassign,no-shadow */
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
* are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through,
* as-is, to `callback` when the throttled-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds
* while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
* one final time after the last throttled-function call. (After the throttled-function has not been called for
* `delay` milliseconds, the internal counter is reset).
* @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
* immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
* callback will never executed if both noLeading = true and noTrailing = true.
* @param {boolean} [options.debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is
* false (at end), schedule `callback` to execute after `delay` ms.
*
* @returns {Function} A new, throttled, function.
*/
function throttle (delay, callback, options) {
var _ref = options || {},
_ref$noTrailing = _ref.noTrailing,
noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
_ref$noLeading = _ref.noLeading,
noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
_ref$debounceMode = _ref.debounceMode,
debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
/*
* After wrapper has stopped being called, this timeout ensures that
* `callback` is executed at the proper times in `throttle` and `end`
* debounce modes.
*/
var timeoutID;
var cancelled = false; // Keep track of the last time `callback` was executed.
var lastExec = 0; // Function to clear existing timeout
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
} // Function to cancel next exec
function cancel(options) {
var _ref2 = options || {},
_ref2$upcomingOnly = _ref2.upcomingOnly,
upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
/*
* The `wrapper` function encapsulates all of the throttling / debouncing
* functionality and when executed will limit the rate at which `callback`
* is executed.
*/
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
} // Execute `callback` and update the `lastExec` timestamp.
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
/*
* If `debounceMode` is true (at begin) this is used to clear the flag
* to allow future `callback` executions.
*/
function clear() {
timeoutID = undefined;
}
if (!noLeading && debounceMode && !timeoutID) {
/*
* Since `wrapper` is being called for the first time and
* `debounceMode` is true (at begin), execute `callback`
* and noLeading != true.
*/
exec();
}
clearExistingTimeout();
if (debounceMode === undefined && elapsed > delay) {
if (noLeading) {
/*
* In throttle mode with noLeading, if `delay` time has
* been exceeded, update `lastExec` and schedule `callback`
* to execute after `delay` ms.
*/
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
/*
* In throttle mode without noLeading, if `delay` time has been exceeded, execute
* `callback`.
*/
exec();
}
} else if (noTrailing !== true) {
/*
* In trailing throttle mode, since `delay` time has not been
* exceeded, schedule `callback` to execute `delay` ms after most
* recent execution.
*
* If `debounceMode` is true (at begin), schedule `clear` to execute
* after `delay` ms.
*
* If `debounceMode` is false (at end), schedule `callback` to
* execute after `delay` ms.
*/
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel; // Return the wrapper function.
return wrapper;
}
/* eslint-disable no-undefined */
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
* to `callback` when the debounced-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
* after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
* (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
*
* @returns {Function} A new, debounced function.
*/
function debounce (delay, callback, options) {
var _ref = options || {},
_ref$atBegin = _ref.atBegin,
atBegin = _ref$atBegin === void 0 ? false : _ref$atBegin;
return throttle(delay, callback, {
debounceMode: atBegin !== false
});
}
/*
How it works:
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
*/
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
class Queue {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
}
const AsyncResource = {
bind(fn, _type, thisArg) {
return fn.bind(thisArg);
},
};
function pLimit(concurrency) {
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
const queue = new Queue();
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.size > 0) {
queue.dequeue()();
}
};
const run = async (function_, resolve, arguments_) => {
activeCount++;
const result = (async () => function_(...arguments_))();
resolve(result);
try {
await result;
} catch {}
next();
};
const enqueue = (function_, resolve, arguments_) => {
queue.enqueue(
AsyncResource.bind(run.bind(undefined, function_, resolve, arguments_)),
);
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
}
})();
};
const generator = (function_, ...arguments_) => new Promise(resolve => {
enqueue(function_, resolve, arguments_);
});
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount,
},
pendingCount: {
get: () => queue.size,
},
clearQueue: {
value() {
queue.clear();
},
},
});
return generator;
}
const VOID = Symbol("p-void");
class PInstance extends Promise {
constructor(items = [], options) {
super(() => {
});
this.items = items;
this.options = options;
this.promises = /* @__PURE__ */ new Set();
}
get promise() {
var _a;
let batch;
const items = [...Array.from(this.items), ...Array.from(this.promises)];
if ((_a = this.options) == null ? void 0 : _a.concurrency) {
const limit = pLimit(this.options.concurrency);
batch = Promise.all(items.map((p2) => limit(() => p2)));
} else {
batch = Promise.all(items);
}
return batch.then((l) => l.filter((i) => i !== VOID));
}
add(...args) {
args.forEach((i) => {
this.promises.add(i);
});
}
map(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
if (v === VOID)
return VOID;
return fn(v, idx);
}),
this.options
);
}
filter(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
const r = await fn(v, idx);
if (!r)
return VOID;
return v;
}),
this.options
);
}
forEach(fn) {
return this.map(fn).then();
}
reduce(fn, initialValue) {
return this.promise.then((array) => array.reduce(fn, initialValue));
}
clear() {
this.promises.clear();
}
then(fn) {
const p2 = this.promise;
if (fn)
return p2.then(fn);
else
return p2;
}
catch(fn) {
return this.promise.catch(fn);
}
finally(fn) {
return this.promise.finally(fn);
}
}
function p(items, options) {
return new PInstance(items, options);
}
exports.assert = assert;
exports.at = at;
exports.batchInvoke = batchInvoke;
exports.capitalize = capitalize;
exports.clamp = clamp;
exports.clampArrayRange = clampArrayRange;
exports.clearUndefined = clearUndefined;
exports.createControlledPromise = createControlledPromise;
exports.createPromiseLock = createPromiseLock;
exports.createSingletonPromise = createSingletonPromise;
exports.debounce = debounce;
exports.deepMerge = deepMerge;
exports.deepMergeWithArray = deepMergeWithArray;
exports.ensurePrefix = ensurePrefix;
exports.ensureSuffix = ensureSuffix;
exports.flattenArrayable = flattenArrayable;
exports.getTypeName = getTypeName;
exports.hasOwnProperty = hasOwnProperty;
exports.invoke = invoke;
exports.isBoolean = isBoolean;
exports.isBrowser = isBrowser;
exports.isDate = isDate;
exports.isDeepEqual = isDeepEqual;
exports.isDef = isDef;
exports.isFunction = isFunction;
exports.isKeyOf = isKeyOf;
exports.isNull = isNull;
exports.isNumber = isNumber;
exports.isObject = isObject;
exports.isRegExp = isRegExp;
exports.isString = isString;
exports.isTruthy = isTruthy;
exports.isUndefined = isUndefined;
exports.isWindow = isWindow;
exports.last = last;
exports.lerp = lerp;
exports.mergeArrayable = mergeArrayable;
exports.move = move;
exports.noNull = noNull;
exports.noop = noop;
exports.notNullish = notNullish;
exports.notUndefined = notUndefined;
exports.objectEntries = objectEntries;
exports.objectKeys = objectKeys;
exports.objectMap = objectMap;
exports.objectPick = objectPick;
exports.p = p;
exports.partition = partition;
exports.randomStr = randomStr;
exports.range = range;
exports.remap = remap;
exports.remove = remove;
exports.sample = sample;
exports.shuffle = shuffle;
exports.slash = slash;
exports.sleep = sleep;
exports.sum = sum;
exports.tap = tap;
exports.template = template;
exports.throttle = throttle;
exports.timestamp = timestamp;
exports.toArray = toArray;
exports.toString = toString;
exports.unindent = unindent;
exports.uniq = uniq;
exports.uniqueBy = uniqueBy;
+614
View File
@@ -0,0 +1,614 @@
/**
* Promise, or maybe not
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
/**
* Function
*/
type Fn<T = void> = () => T;
/**
* Constructor
*/
type Constructor<T = void> = new (...args: any[]) => T;
/**
* Infers the element type of an array
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Defines an intersection type of all union items.
*
* @param U Union of any types that will be intersected.
* @returns U items intersected
* @see https://stackoverflow.com/a/50375286/9259330
*/
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/**
* Infers the arguments type of a function
*/
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
*
* @category Array
*/
declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
*
* @category Array
*/
declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*
* @category Array
* @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
*/
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
/**
* Unique an Array
*
* @category Array
*/
declare function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
*
* @category Array
*/
declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
/**
* Get last item
*
* @category Array
*/
declare function last(array: readonly []): undefined;
declare function last<T>(array: readonly T[]): T;
/**
* Remove an item from Array
*
* @category Array
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Get nth item of Array. Negative for backward
*
* @category Array
*/
declare function at(array: readonly [], index: number): undefined;
declare function at<T>(array: readonly T[], index: number): T;
/**
* Genrate a range array of numbers. The `stop` is exclusive.
*
* @category Array
*/
declare function range(stop: number): number[];
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move element in an Array
*
* @category Array
* @param arr
* @param from
* @param to
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Clamp a number to the index range of an array
*
* @category Array
*/
declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
/**
* Get random item(s) from an array
*
* @param arr
* @param quantity - quantity of random items which will be returned
*/
declare function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
*
* @category Array
*/
declare function shuffle<T>(array: T[]): T[];
declare function assert(condition: boolean, message: string): asserts condition;
declare const toString: (v: any) => string;
declare function getTypeName(v: any): string;
declare function noop(): void;
declare function isDeepEqual(value1: any, value2: any): boolean;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notNullish)
*/
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
/**
* Type guard to filter out null values
*
* @category Guards
* @example array.filter(noNull)
*/
declare function noNull<T>(v: T | null): v is Exclude<T, null>;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notUndefined)
*/
declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
/**
* Type guard to filter out falsy values
*
* @category Guards
* @example array.filter(isTruthy)
*/
declare function isTruthy<T>(v: T): v is NonNullable<T>;
declare const isDef: <T = any>(val?: T) => val is T;
declare const isBoolean: (val: any) => val is boolean;
declare const isFunction: <T extends Function>(val: any) => val is T;
declare const isNumber: (val: any) => val is number;
declare const isString: (val: unknown) => val is string;
declare const isObject: (val: any) => val is object;
declare const isUndefined: (val: any) => val is undefined;
declare const isNull: (val: any) => val is null;
declare const isRegExp: (val: any) => val is RegExp;
declare const isDate: (val: any) => val is Date;
declare const isWindow: (val: any) => boolean;
declare const isBrowser: boolean;
declare function clamp(n: number, min: number, max: number): number;
declare function sum(...args: number[] | number[][]): number;
/**
* Linearly interpolates between `min` and `max` based on `t`
*
* @category Math
* @param min The minimum value
* @param max The maximum value
* @param t The interpolation value clamped between 0 and 1
* @example
* ```
* const value = lerp(0, 2, 0.5) // value will be 1
* ```
*/
declare function lerp(min: number, max: number, t: number): number;
/**
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
*
* @category Math
* @example
* ```
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
* ```
*/
declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
/**
* Replace backslash to slash
*
* @category String
*/
declare function slash(str: string): string;
/**
* Ensure prefix of a string
*
* @category String
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix of a string
*
* @category String
*/
declare function ensureSuffix(suffix: string, str: string): string;
/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
* While using object/name based approach, you can pass a fallback value as the third argument
*
* @category String
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*
* ```
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
* 'placeholder'
* ) // Hello! My name is placeholder.
* ```
*/
declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
/**
* Generate a random string
* @category String
*/
declare function randomStr(size?: number, dict?: string): string;
/**
* First letter uppercase, other lowercase
* @category string
* @example
* ```
* capitalize('hello') => 'Hello'
* ```
*/
declare function capitalize(str: string): string;
/**
* Remove common leading whitespace from a template string.
* Will also remove empty lines at the beginning and end.
* @category string
* @example
* ```ts
* const str = unindent`
* if (a) {
* b()
* }
* `
*/
declare function unindent(str: TemplateStringsArray | string): string;
declare const timestamp: () => number;
/**
* Call every function in an array
*/
declare function batchInvoke(functions: Nullable<Fn>[]): void;
/**
* Call the function
*/
declare function invoke(fn: Fn): void;
/**
* Pass the value through the callback, and return the value
*
* @example
* ```
* function createUser(name: string): User {
* return tap(new User, user => {
* user.name = name
* })
* }
* ```
*/
declare function tap<T>(value: T, callback: (value: T) => void): T;
/**
* Map key/value pairs for an object, and construct a new one
*
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Type guard for any key, `k`.
* Marks `k` as a key of `T` if `k` is in `obj`.
*
* @category Object
* @param obj object to query for key `k`
* @param k key to check existence in `obj`
*/
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
/**
* Strict typed `Object.keys`
*
* @category Object
*/
declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
/**
* Strict typed `Object.entries`
*
* @category Object
*/
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Create a new subset object by giving keys
*
* @category Object
*/
declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
/**
* Clear undefined fields from an object. It mutates the object
*
* @category Object
*/
declare function clearUndefined<T extends object>(obj: T): T;
/**
* Determines whether an object has a property with the specified name
*
* @see https://eslint.org/docs/rules/no-prototype-builtins
* @category Object
*/
declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Promised `setTimeout`
*
* @category Promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Create a promise lock
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run<T = void>(fn: () => Promise<T>): Promise<T>;
wait(): Promise<void>;
isWaiting(): boolean;
clear(): void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
interface ThrottleOptions {
noTrailing?: boolean;
noLeading?: boolean;
debounceMode?: boolean;
}
interface DebounceOptions {
atBegin?: boolean;
}
type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.noTrailing
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*
* @param options.noLeading
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*
* @param options.debounceMode If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: ThrottleOptions,
): throttle<T>;
type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.atBegin
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: DebounceOptions,
): debounce<T>;
interface POptions {
/**
* How many promises are resolved at the same time.
*/
concurrency?: number | undefined;
}
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
options?: POptions | undefined;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>, options?: POptions | undefined);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
/**
* Utility for managing multiple promises.
*
* @see https://github.com/antfu/utils/tree/main/docs/p.md
* @category Promise
* @example
* ```
* import { p } from '@antfu/utils'
*
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+614
View File
@@ -0,0 +1,614 @@
/**
* Promise, or maybe not
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
/**
* Function
*/
type Fn<T = void> = () => T;
/**
* Constructor
*/
type Constructor<T = void> = new (...args: any[]) => T;
/**
* Infers the element type of an array
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Defines an intersection type of all union items.
*
* @param U Union of any types that will be intersected.
* @returns U items intersected
* @see https://stackoverflow.com/a/50375286/9259330
*/
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/**
* Infers the arguments type of a function
*/
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
*
* @category Array
*/
declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
*
* @category Array
*/
declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*
* @category Array
* @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
*/
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
/**
* Unique an Array
*
* @category Array
*/
declare function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
*
* @category Array
*/
declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
/**
* Get last item
*
* @category Array
*/
declare function last(array: readonly []): undefined;
declare function last<T>(array: readonly T[]): T;
/**
* Remove an item from Array
*
* @category Array
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Get nth item of Array. Negative for backward
*
* @category Array
*/
declare function at(array: readonly [], index: number): undefined;
declare function at<T>(array: readonly T[], index: number): T;
/**
* Genrate a range array of numbers. The `stop` is exclusive.
*
* @category Array
*/
declare function range(stop: number): number[];
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move element in an Array
*
* @category Array
* @param arr
* @param from
* @param to
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Clamp a number to the index range of an array
*
* @category Array
*/
declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
/**
* Get random item(s) from an array
*
* @param arr
* @param quantity - quantity of random items which will be returned
*/
declare function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
*
* @category Array
*/
declare function shuffle<T>(array: T[]): T[];
declare function assert(condition: boolean, message: string): asserts condition;
declare const toString: (v: any) => string;
declare function getTypeName(v: any): string;
declare function noop(): void;
declare function isDeepEqual(value1: any, value2: any): boolean;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notNullish)
*/
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
/**
* Type guard to filter out null values
*
* @category Guards
* @example array.filter(noNull)
*/
declare function noNull<T>(v: T | null): v is Exclude<T, null>;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notUndefined)
*/
declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
/**
* Type guard to filter out falsy values
*
* @category Guards
* @example array.filter(isTruthy)
*/
declare function isTruthy<T>(v: T): v is NonNullable<T>;
declare const isDef: <T = any>(val?: T) => val is T;
declare const isBoolean: (val: any) => val is boolean;
declare const isFunction: <T extends Function>(val: any) => val is T;
declare const isNumber: (val: any) => val is number;
declare const isString: (val: unknown) => val is string;
declare const isObject: (val: any) => val is object;
declare const isUndefined: (val: any) => val is undefined;
declare const isNull: (val: any) => val is null;
declare const isRegExp: (val: any) => val is RegExp;
declare const isDate: (val: any) => val is Date;
declare const isWindow: (val: any) => boolean;
declare const isBrowser: boolean;
declare function clamp(n: number, min: number, max: number): number;
declare function sum(...args: number[] | number[][]): number;
/**
* Linearly interpolates between `min` and `max` based on `t`
*
* @category Math
* @param min The minimum value
* @param max The maximum value
* @param t The interpolation value clamped between 0 and 1
* @example
* ```
* const value = lerp(0, 2, 0.5) // value will be 1
* ```
*/
declare function lerp(min: number, max: number, t: number): number;
/**
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
*
* @category Math
* @example
* ```
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
* ```
*/
declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
/**
* Replace backslash to slash
*
* @category String
*/
declare function slash(str: string): string;
/**
* Ensure prefix of a string
*
* @category String
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix of a string
*
* @category String
*/
declare function ensureSuffix(suffix: string, str: string): string;
/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
* While using object/name based approach, you can pass a fallback value as the third argument
*
* @category String
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*
* ```
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
* 'placeholder'
* ) // Hello! My name is placeholder.
* ```
*/
declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
/**
* Generate a random string
* @category String
*/
declare function randomStr(size?: number, dict?: string): string;
/**
* First letter uppercase, other lowercase
* @category string
* @example
* ```
* capitalize('hello') => 'Hello'
* ```
*/
declare function capitalize(str: string): string;
/**
* Remove common leading whitespace from a template string.
* Will also remove empty lines at the beginning and end.
* @category string
* @example
* ```ts
* const str = unindent`
* if (a) {
* b()
* }
* `
*/
declare function unindent(str: TemplateStringsArray | string): string;
declare const timestamp: () => number;
/**
* Call every function in an array
*/
declare function batchInvoke(functions: Nullable<Fn>[]): void;
/**
* Call the function
*/
declare function invoke(fn: Fn): void;
/**
* Pass the value through the callback, and return the value
*
* @example
* ```
* function createUser(name: string): User {
* return tap(new User, user => {
* user.name = name
* })
* }
* ```
*/
declare function tap<T>(value: T, callback: (value: T) => void): T;
/**
* Map key/value pairs for an object, and construct a new one
*
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Type guard for any key, `k`.
* Marks `k` as a key of `T` if `k` is in `obj`.
*
* @category Object
* @param obj object to query for key `k`
* @param k key to check existence in `obj`
*/
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
/**
* Strict typed `Object.keys`
*
* @category Object
*/
declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
/**
* Strict typed `Object.entries`
*
* @category Object
*/
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Create a new subset object by giving keys
*
* @category Object
*/
declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
/**
* Clear undefined fields from an object. It mutates the object
*
* @category Object
*/
declare function clearUndefined<T extends object>(obj: T): T;
/**
* Determines whether an object has a property with the specified name
*
* @see https://eslint.org/docs/rules/no-prototype-builtins
* @category Object
*/
declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Promised `setTimeout`
*
* @category Promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Create a promise lock
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run<T = void>(fn: () => Promise<T>): Promise<T>;
wait(): Promise<void>;
isWaiting(): boolean;
clear(): void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
interface ThrottleOptions {
noTrailing?: boolean;
noLeading?: boolean;
debounceMode?: boolean;
}
interface DebounceOptions {
atBegin?: boolean;
}
type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.noTrailing
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*
* @param options.noLeading
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*
* @param options.debounceMode If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: ThrottleOptions,
): throttle<T>;
type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.atBegin
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: DebounceOptions,
): debounce<T>;
interface POptions {
/**
* How many promises are resolved at the same time.
*/
concurrency?: number | undefined;
}
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
options?: POptions | undefined;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>, options?: POptions | undefined);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
/**
* Utility for managing multiple promises.
*
* @see https://github.com/antfu/utils/tree/main/docs/p.md
* @category Promise
* @example
* ```
* import { p } from '@antfu/utils'
*
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+614
View File
@@ -0,0 +1,614 @@
/**
* Promise, or maybe not
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
/**
* Function
*/
type Fn<T = void> = () => T;
/**
* Constructor
*/
type Constructor<T = void> = new (...args: any[]) => T;
/**
* Infers the element type of an array
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Defines an intersection type of all union items.
*
* @param U Union of any types that will be intersected.
* @returns U items intersected
* @see https://stackoverflow.com/a/50375286/9259330
*/
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/**
* Infers the arguments type of a function
*/
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
*
* @category Array
*/
declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
*
* @category Array
*/
declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*
* @category Array
* @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
*/
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
/**
* Unique an Array
*
* @category Array
*/
declare function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
*
* @category Array
*/
declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
/**
* Get last item
*
* @category Array
*/
declare function last(array: readonly []): undefined;
declare function last<T>(array: readonly T[]): T;
/**
* Remove an item from Array
*
* @category Array
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Get nth item of Array. Negative for backward
*
* @category Array
*/
declare function at(array: readonly [], index: number): undefined;
declare function at<T>(array: readonly T[], index: number): T;
/**
* Genrate a range array of numbers. The `stop` is exclusive.
*
* @category Array
*/
declare function range(stop: number): number[];
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move element in an Array
*
* @category Array
* @param arr
* @param from
* @param to
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Clamp a number to the index range of an array
*
* @category Array
*/
declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
/**
* Get random item(s) from an array
*
* @param arr
* @param quantity - quantity of random items which will be returned
*/
declare function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
*
* @category Array
*/
declare function shuffle<T>(array: T[]): T[];
declare function assert(condition: boolean, message: string): asserts condition;
declare const toString: (v: any) => string;
declare function getTypeName(v: any): string;
declare function noop(): void;
declare function isDeepEqual(value1: any, value2: any): boolean;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notNullish)
*/
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
/**
* Type guard to filter out null values
*
* @category Guards
* @example array.filter(noNull)
*/
declare function noNull<T>(v: T | null): v is Exclude<T, null>;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notUndefined)
*/
declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
/**
* Type guard to filter out falsy values
*
* @category Guards
* @example array.filter(isTruthy)
*/
declare function isTruthy<T>(v: T): v is NonNullable<T>;
declare const isDef: <T = any>(val?: T) => val is T;
declare const isBoolean: (val: any) => val is boolean;
declare const isFunction: <T extends Function>(val: any) => val is T;
declare const isNumber: (val: any) => val is number;
declare const isString: (val: unknown) => val is string;
declare const isObject: (val: any) => val is object;
declare const isUndefined: (val: any) => val is undefined;
declare const isNull: (val: any) => val is null;
declare const isRegExp: (val: any) => val is RegExp;
declare const isDate: (val: any) => val is Date;
declare const isWindow: (val: any) => boolean;
declare const isBrowser: boolean;
declare function clamp(n: number, min: number, max: number): number;
declare function sum(...args: number[] | number[][]): number;
/**
* Linearly interpolates between `min` and `max` based on `t`
*
* @category Math
* @param min The minimum value
* @param max The maximum value
* @param t The interpolation value clamped between 0 and 1
* @example
* ```
* const value = lerp(0, 2, 0.5) // value will be 1
* ```
*/
declare function lerp(min: number, max: number, t: number): number;
/**
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
*
* @category Math
* @example
* ```
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
* ```
*/
declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
/**
* Replace backslash to slash
*
* @category String
*/
declare function slash(str: string): string;
/**
* Ensure prefix of a string
*
* @category String
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix of a string
*
* @category String
*/
declare function ensureSuffix(suffix: string, str: string): string;
/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
* While using object/name based approach, you can pass a fallback value as the third argument
*
* @category String
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*
* ```
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
* 'placeholder'
* ) // Hello! My name is placeholder.
* ```
*/
declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
/**
* Generate a random string
* @category String
*/
declare function randomStr(size?: number, dict?: string): string;
/**
* First letter uppercase, other lowercase
* @category string
* @example
* ```
* capitalize('hello') => 'Hello'
* ```
*/
declare function capitalize(str: string): string;
/**
* Remove common leading whitespace from a template string.
* Will also remove empty lines at the beginning and end.
* @category string
* @example
* ```ts
* const str = unindent`
* if (a) {
* b()
* }
* `
*/
declare function unindent(str: TemplateStringsArray | string): string;
declare const timestamp: () => number;
/**
* Call every function in an array
*/
declare function batchInvoke(functions: Nullable<Fn>[]): void;
/**
* Call the function
*/
declare function invoke(fn: Fn): void;
/**
* Pass the value through the callback, and return the value
*
* @example
* ```
* function createUser(name: string): User {
* return tap(new User, user => {
* user.name = name
* })
* }
* ```
*/
declare function tap<T>(value: T, callback: (value: T) => void): T;
/**
* Map key/value pairs for an object, and construct a new one
*
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Type guard for any key, `k`.
* Marks `k` as a key of `T` if `k` is in `obj`.
*
* @category Object
* @param obj object to query for key `k`
* @param k key to check existence in `obj`
*/
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
/**
* Strict typed `Object.keys`
*
* @category Object
*/
declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
/**
* Strict typed `Object.entries`
*
* @category Object
*/
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Create a new subset object by giving keys
*
* @category Object
*/
declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
/**
* Clear undefined fields from an object. It mutates the object
*
* @category Object
*/
declare function clearUndefined<T extends object>(obj: T): T;
/**
* Determines whether an object has a property with the specified name
*
* @see https://eslint.org/docs/rules/no-prototype-builtins
* @category Object
*/
declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Promised `setTimeout`
*
* @category Promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Create a promise lock
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run<T = void>(fn: () => Promise<T>): Promise<T>;
wait(): Promise<void>;
isWaiting(): boolean;
clear(): void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
interface ThrottleOptions {
noTrailing?: boolean;
noLeading?: boolean;
debounceMode?: boolean;
}
interface DebounceOptions {
atBegin?: boolean;
}
type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.noTrailing
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*
* @param options.noLeading
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*
* @param options.debounceMode If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: ThrottleOptions,
): throttle<T>;
type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.atBegin
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: DebounceOptions,
): debounce<T>;
interface POptions {
/**
* How many promises are resolved at the same time.
*/
concurrency?: number | undefined;
}
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
options?: POptions | undefined;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>, options?: POptions | undefined);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
/**
* Utility for managing multiple promises.
*
* @see https://github.com/antfu/utils/tree/main/docs/p.md
* @category Promise
* @example
* ```
* import { p } from '@antfu/utils'
*
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+777
View File
@@ -0,0 +1,777 @@
function clamp(n, min, max) {
return Math.min(max, Math.max(min, n));
}
function sum(...args) {
return flattenArrayable(args).reduce((a, b) => a + b, 0);
}
function lerp(min, max, t) {
const interpolation = clamp(t, 0, 1);
return min + (max - min) * interpolation;
}
function remap(n, inMin, inMax, outMin, outMax) {
const interpolation = (n - inMin) / (inMax - inMin);
return lerp(outMin, outMax, interpolation);
}
function toArray(array) {
array = array ?? [];
return Array.isArray(array) ? array : [array];
}
function flattenArrayable(array) {
return toArray(array).flat(1);
}
function mergeArrayable(...args) {
return args.flatMap((i) => toArray(i));
}
function partition(array, ...filters) {
const result = Array.from({ length: filters.length + 1 }).fill(null).map(() => []);
array.forEach((e, idx, arr) => {
let i = 0;
for (const filter of filters) {
if (filter(e, idx, arr)) {
result[i].push(e);
return;
}
i += 1;
}
result[i].push(e);
});
return result;
}
function uniq(array) {
return Array.from(new Set(array));
}
function uniqueBy(array, equalFn) {
return array.reduce((acc, cur) => {
const index = acc.findIndex((item) => equalFn(cur, item));
if (index === -1)
acc.push(cur);
return acc;
}, []);
}
function last(array) {
return at(array, -1);
}
function remove(array, value) {
if (!array)
return false;
const index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
return true;
}
return false;
}
function at(array, index) {
const len = array.length;
if (!len)
return void 0;
if (index < 0)
index += len;
return array[index];
}
function range(...args) {
let start, stop, step;
if (args.length === 1) {
start = 0;
step = 1;
[stop] = args;
} else {
[start, stop, step = 1] = args;
}
const arr = [];
let current = start;
while (current < stop) {
arr.push(current);
current += step || 1;
}
return arr;
}
function move(arr, from, to) {
arr.splice(to, 0, arr.splice(from, 1)[0]);
return arr;
}
function clampArrayRange(n, arr) {
return clamp(n, 0, arr.length - 1);
}
function sample(arr, quantity) {
return Array.from({ length: quantity }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function assert(condition, message) {
if (!condition)
throw new Error(message);
}
const toString = (v) => Object.prototype.toString.call(v);
function getTypeName(v) {
if (v === null)
return "null";
const type = toString(v).slice(8, -1).toLowerCase();
return typeof v === "object" || typeof v === "function" ? type : typeof v;
}
function noop() {
}
function isDeepEqual(value1, value2) {
const type1 = getTypeName(value1);
const type2 = getTypeName(value2);
if (type1 !== type2)
return false;
if (type1 === "array") {
if (value1.length !== value2.length)
return false;
return value1.every((item, i) => {
return isDeepEqual(item, value2[i]);
});
}
if (type1 === "object") {
const keyArr = Object.keys(value1);
if (keyArr.length !== Object.keys(value2).length)
return false;
return keyArr.every((key) => {
return isDeepEqual(value1[key], value2[key]);
});
}
return Object.is(value1, value2);
}
function notNullish(v) {
return v != null;
}
function noNull(v) {
return v !== null;
}
function notUndefined(v) {
return v !== void 0;
}
function isTruthy(v) {
return Boolean(v);
}
const isDef = (val) => typeof val !== "undefined";
const isBoolean = (val) => typeof val === "boolean";
const isFunction = (val) => typeof val === "function";
const isNumber = (val) => typeof val === "number";
const isString = (val) => typeof val === "string";
const isObject = (val) => toString(val) === "[object Object]";
const isUndefined = (val) => toString(val) === "[object Undefined]";
const isNull = (val) => toString(val) === "[object Null]";
const isRegExp = (val) => toString(val) === "[object RegExp]";
const isDate = (val) => toString(val) === "[object Date]";
const isWindow = (val) => typeof window !== "undefined" && toString(val) === "[object Window]";
const isBrowser = typeof window !== "undefined";
function slash(str) {
return str.replace(/\\/g, "/");
}
function ensurePrefix(prefix, str) {
if (!str.startsWith(prefix))
return prefix + str;
return str;
}
function ensureSuffix(suffix, str) {
if (!str.endsWith(suffix))
return str + suffix;
return str;
}
function template(str, ...args) {
const [firstArg, fallback] = args;
if (isObject(firstArg)) {
const vars = firstArg;
return str.replace(/{([\w\d]+)}/g, (_, key) => vars[key] || ((typeof fallback === "function" ? fallback(key) : fallback) ?? key));
} else {
return str.replace(/{(\d+)}/g, (_, key) => {
const index = Number(key);
if (Number.isNaN(index))
return key;
return args[index];
});
}
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function randomStr(size = 16, dict = urlAlphabet) {
let id = "";
let i = size;
const len = dict.length;
while (i--)
id += dict[Math.random() * len | 0];
return id;
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1).toLowerCase();
}
const _reFullWs = /^\s*$/;
function unindent(str) {
const lines = (typeof str === "string" ? str : str[0]).split("\n");
const whitespaceLines = lines.map((line) => _reFullWs.test(line));
const commonIndent = lines.reduce((min, line, idx) => {
var _a;
if (whitespaceLines[idx])
return min;
const indent = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0].length;
return indent === void 0 ? min : Math.min(min, indent);
}, Number.POSITIVE_INFINITY);
let emptyLinesHead = 0;
while (emptyLinesHead < lines.length && whitespaceLines[emptyLinesHead])
emptyLinesHead++;
let emptyLinesTail = 0;
while (emptyLinesTail < lines.length && whitespaceLines[lines.length - emptyLinesTail - 1])
emptyLinesTail++;
return lines.slice(emptyLinesHead, lines.length - emptyLinesTail).map((line) => line.slice(commonIndent)).join("\n");
}
const timestamp = () => +Date.now();
function batchInvoke(functions) {
functions.forEach((fn) => fn && fn());
}
function invoke(fn) {
return fn();
}
function tap(value, callback) {
callback(value);
return value;
}
function objectMap(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish)
);
}
function isKeyOf(obj, k) {
return k in obj;
}
function objectKeys(obj) {
return Object.keys(obj);
}
function objectEntries(obj) {
return Object.entries(obj);
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
if (isMergableObject(target[key])) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
});
}
return deepMerge(target, ...sources);
}
function deepMergeWithArray(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (Array.isArray(target) && Array.isArray(source))
target.push(...source);
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (Array.isArray(source[key])) {
if (!target[key])
target[key] = [];
deepMergeWithArray(target[key], source[key]);
} else if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
deepMergeWithArray(target[key], source[key]);
} else {
target[key] = source[key];
}
});
}
return deepMergeWithArray(target, ...sources);
}
function isMergableObject(item) {
return isObject(item) && !Array.isArray(item);
}
function objectPick(obj, keys, omitUndefined = false) {
return keys.reduce((n, k) => {
if (k in obj) {
if (!omitUndefined || obj[k] !== void 0)
n[k] = obj[k];
}
return n;
}, {});
}
function clearUndefined(obj) {
Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {});
return obj;
}
function hasOwnProperty(obj, v) {
if (obj == null)
return false;
return Object.prototype.hasOwnProperty.call(obj, v);
}
function createSingletonPromise(fn) {
let _promise;
function wrapper() {
if (!_promise)
_promise = fn();
return _promise;
}
wrapper.reset = async () => {
const _prev = _promise;
_promise = void 0;
if (_prev)
await _prev;
};
return wrapper;
}
function sleep(ms, callback) {
return new Promise(
(resolve) => setTimeout(async () => {
await (callback == null ? void 0 : callback());
resolve();
}, ms)
);
}
function createPromiseLock() {
const locks = [];
return {
async run(fn) {
const p = fn();
locks.push(p);
try {
return await p;
} finally {
remove(locks, p);
}
},
async wait() {
await Promise.allSettled(locks);
},
isWaiting() {
return Boolean(locks.length);
},
clear() {
locks.length = 0;
}
};
}
function createControlledPromise() {
let resolve, reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
}
/* eslint-disable no-undefined,no-param-reassign,no-shadow */
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
* are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through,
* as-is, to `callback` when the throttled-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds
* while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
* one final time after the last throttled-function call. (After the throttled-function has not been called for
* `delay` milliseconds, the internal counter is reset).
* @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
* immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
* callback will never executed if both noLeading = true and noTrailing = true.
* @param {boolean} [options.debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is
* false (at end), schedule `callback` to execute after `delay` ms.
*
* @returns {Function} A new, throttled, function.
*/
function throttle (delay, callback, options) {
var _ref = options || {},
_ref$noTrailing = _ref.noTrailing,
noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
_ref$noLeading = _ref.noLeading,
noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
_ref$debounceMode = _ref.debounceMode,
debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
/*
* After wrapper has stopped being called, this timeout ensures that
* `callback` is executed at the proper times in `throttle` and `end`
* debounce modes.
*/
var timeoutID;
var cancelled = false; // Keep track of the last time `callback` was executed.
var lastExec = 0; // Function to clear existing timeout
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
} // Function to cancel next exec
function cancel(options) {
var _ref2 = options || {},
_ref2$upcomingOnly = _ref2.upcomingOnly,
upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
/*
* The `wrapper` function encapsulates all of the throttling / debouncing
* functionality and when executed will limit the rate at which `callback`
* is executed.
*/
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
} // Execute `callback` and update the `lastExec` timestamp.
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
/*
* If `debounceMode` is true (at begin) this is used to clear the flag
* to allow future `callback` executions.
*/
function clear() {
timeoutID = undefined;
}
if (!noLeading && debounceMode && !timeoutID) {
/*
* Since `wrapper` is being called for the first time and
* `debounceMode` is true (at begin), execute `callback`
* and noLeading != true.
*/
exec();
}
clearExistingTimeout();
if (debounceMode === undefined && elapsed > delay) {
if (noLeading) {
/*
* In throttle mode with noLeading, if `delay` time has
* been exceeded, update `lastExec` and schedule `callback`
* to execute after `delay` ms.
*/
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
/*
* In throttle mode without noLeading, if `delay` time has been exceeded, execute
* `callback`.
*/
exec();
}
} else if (noTrailing !== true) {
/*
* In trailing throttle mode, since `delay` time has not been
* exceeded, schedule `callback` to execute `delay` ms after most
* recent execution.
*
* If `debounceMode` is true (at begin), schedule `clear` to execute
* after `delay` ms.
*
* If `debounceMode` is false (at end), schedule `callback` to
* execute after `delay` ms.
*/
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel; // Return the wrapper function.
return wrapper;
}
/* eslint-disable no-undefined */
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
* to `callback` when the debounced-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
* after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
* (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
*
* @returns {Function} A new, debounced function.
*/
function debounce (delay, callback, options) {
var _ref = options || {},
_ref$atBegin = _ref.atBegin,
atBegin = _ref$atBegin === void 0 ? false : _ref$atBegin;
return throttle(delay, callback, {
debounceMode: atBegin !== false
});
}
/*
How it works:
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
*/
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
class Queue {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
}
const AsyncResource = {
bind(fn, _type, thisArg) {
return fn.bind(thisArg);
},
};
function pLimit(concurrency) {
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
const queue = new Queue();
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.size > 0) {
queue.dequeue()();
}
};
const run = async (function_, resolve, arguments_) => {
activeCount++;
const result = (async () => function_(...arguments_))();
resolve(result);
try {
await result;
} catch {}
next();
};
const enqueue = (function_, resolve, arguments_) => {
queue.enqueue(
AsyncResource.bind(run.bind(undefined, function_, resolve, arguments_)),
);
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
}
})();
};
const generator = (function_, ...arguments_) => new Promise(resolve => {
enqueue(function_, resolve, arguments_);
});
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount,
},
pendingCount: {
get: () => queue.size,
},
clearQueue: {
value() {
queue.clear();
},
},
});
return generator;
}
const VOID = Symbol("p-void");
class PInstance extends Promise {
constructor(items = [], options) {
super(() => {
});
this.items = items;
this.options = options;
this.promises = /* @__PURE__ */ new Set();
}
get promise() {
var _a;
let batch;
const items = [...Array.from(this.items), ...Array.from(this.promises)];
if ((_a = this.options) == null ? void 0 : _a.concurrency) {
const limit = pLimit(this.options.concurrency);
batch = Promise.all(items.map((p2) => limit(() => p2)));
} else {
batch = Promise.all(items);
}
return batch.then((l) => l.filter((i) => i !== VOID));
}
add(...args) {
args.forEach((i) => {
this.promises.add(i);
});
}
map(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
if (v === VOID)
return VOID;
return fn(v, idx);
}),
this.options
);
}
filter(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
const r = await fn(v, idx);
if (!r)
return VOID;
return v;
}),
this.options
);
}
forEach(fn) {
return this.map(fn).then();
}
reduce(fn, initialValue) {
return this.promise.then((array) => array.reduce(fn, initialValue));
}
clear() {
this.promises.clear();
}
then(fn) {
const p2 = this.promise;
if (fn)
return p2.then(fn);
else
return p2;
}
catch(fn) {
return this.promise.catch(fn);
}
finally(fn) {
return this.promise.finally(fn);
}
}
function p(items, options) {
return new PInstance(items, options);
}
export { assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+67
View File
@@ -0,0 +1,67 @@
{
"name": "@antfu/utils",
"type": "module",
"version": "0.7.10",
"packageManager": "pnpm@9.1.0",
"description": "Opinionated collection of common JavaScript / TypeScript utils by @antfu",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/utils#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/utils.git"
},
"bugs": {
"url": "https://github.com/antfu/utils/issues"
},
"keywords": [
"utils"
],
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "rollup -c",
"dev": "nr build --watch",
"lint": "eslint .",
"lint-fix": "nr lint --fix",
"prepublishOnly": "npm run build",
"release": "bumpp --commit --push --tag && npm publish",
"start": "esno src/index.ts",
"typecheck": "tsc --noEmit",
"test": "vitest"
},
"devDependencies": {
"@antfu/eslint-config": "^2.16.3",
"@antfu/ni": "^0.21.12",
"@rollup/plugin-alias": "^5.1.0",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/node": "^20.12.10",
"@types/throttle-debounce": "^5.0.2",
"bumpp": "^9.4.1",
"eslint": "npm:eslint-ts-patch@8.55.0-1",
"eslint-ts-patch": "8.55.0-1",
"esno": "^4.7.0",
"p-limit": "^5.0.0",
"rollup": "^4.17.2",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-esbuild": "^6.1.1",
"throttle-debounce": "5.0.0",
"typescript": "^5.4.5",
"vite": "^5.2.11",
"vitest": "^1.6.0"
}
}