Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019-2022 Nuxt Project
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.

View file

@ -0,0 +1,23 @@
# `@nuxt/eslint-config`
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
Shared ESLint config for Nuxt 3 projects. Unopinionated by default, but customizable.
Refer to the [documentation](https://eslint.nuxt.com/packages/config) for more details.
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/@nuxt/eslint-config?style=flat-square
[npm-version-href]: https://npmjs.com/package/@nuxt/eslint-config
[npm-downloads-src]: https://img.shields.io/npm/dm/@nuxt/eslint-config?style=flat-square
[npm-downloads-href]: https://npmjs.com/package/@nuxt/eslint-config
[github-actions-src]: https://img.shields.io/github/workflow/status/nuxt/eslint-config/ci/main?style=flat-square
[github-actions-href]: https://github.com/nuxt/eslint-config/actions?query=workflow%3Aci
[codecov-src]: https://img.shields.io/codecov/c/gh/nuxt/eslint-config/main?style=flat-square
[codecov-href]: https://codecov.io/gh/nuxt/eslint-config
[lgtm-src]: https://img.shields.io/lgtm/grade/javascript/github/nuxt/eslint-config?style=flat-square
[lgtm-href]: https://lgtm.com/projects/g/nuxt/eslint-config
[bundlephobia-src]: https://img.shields.io/bundlephobia/minzip/@nuxt/eslint-config?style=flat-square
[bundlephobia-href]: https://bundlephobia.com/package/@nuxt/eslint-config

View file

@ -0,0 +1,235 @@
import { isPackageExists } from 'local-pkg';
import { e as ensurePackages, i as interopDefault, p as parserPlain } from '../shared/eslint-config.CePp8IWi.mjs';
import { b as GLOB_CSS, c as GLOB_POSTCSS, d as GLOB_SCSS, e as GLOB_LESS, f as GLOB_HTML, g as GLOB_XML, h as GLOB_SVG, i as GLOB_MARKDOWN, j as GLOB_GRAPHQL } from '../shared/eslint-config.CUi9znUC.mjs';
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
import 'pathe';
import 'node:process';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';
function mergePrettierOptions(options, overrides = {}) {
return {
...options,
...overrides,
plugins: [
...overrides.plugins || [],
...options.plugins || []
]
};
}
async function formatters(options = {}, stylistic) {
if (!options)
return [];
if (options === true) {
const isPrettierPluginXmlInScope = isPackageExists("@prettier/plugin-xml");
options = {
css: true,
graphql: true,
html: true,
// Markdown is disabled by default as many Nuxt projects use MDC with @nuxt/content,
// where Prettier doesn't fully understand.
markdown: false,
svg: isPrettierPluginXmlInScope,
xml: isPrettierPluginXmlInScope
};
}
await ensurePackages([
"eslint-plugin-format",
options.xml || options.svg ? "@prettier/plugin-xml" : void 0
]);
const {
indent,
quotes,
semi
} = {
indent: 2,
quotes: "single",
semi: false,
...stylistic
};
const prettierOptions = Object.assign(
{
endOfLine: "auto",
printWidth: 120,
semi,
singleQuote: quotes === "single",
tabWidth: typeof indent === "number" ? indent : 2,
trailingComma: "all",
useTabs: indent === "tab"
},
options.prettierOptions || {}
);
const prettierXmlOptions = {
xmlQuoteAttributes: "double",
xmlSelfClosingSpace: true,
xmlSortAttributesByKey: false,
xmlWhitespaceSensitivity: "ignore"
};
const dprintOptions = Object.assign(
{
indentWidth: typeof indent === "number" ? indent : 2,
quoteStyle: quotes === "single" ? "preferSingle" : "preferDouble",
useTabs: indent === "tab"
},
options.dprintOptions || {}
);
const pluginFormat = await interopDefault(import('eslint-plugin-format'));
const configs = [
{
name: "nuxt/formatter/setup",
plugins: {
format: pluginFormat
}
}
];
if (options.css) {
configs.push(
{
files: [GLOB_CSS, GLOB_POSTCSS],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/css",
rules: {
"format/prettier": [
"error",
mergePrettierOptions(prettierOptions, {
parser: "css"
})
]
}
},
{
files: [GLOB_SCSS],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/scss",
rules: {
"format/prettier": [
"error",
mergePrettierOptions(prettierOptions, {
parser: "scss"
})
]
}
},
{
files: [GLOB_LESS],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/less",
rules: {
"format/prettier": [
"error",
mergePrettierOptions(prettierOptions, {
parser: "less"
})
]
}
}
);
}
if (options.html) {
configs.push({
files: [GLOB_HTML],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/html",
rules: {
"format/prettier": [
"error",
mergePrettierOptions(prettierOptions, {
parser: "html"
})
]
}
});
}
if (options.xml) {
configs.push({
files: [GLOB_XML],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/xml",
rules: {
"format/prettier": [
"error",
mergePrettierOptions({ ...prettierXmlOptions, ...prettierOptions }, {
parser: "xml",
plugins: [
"@prettier/plugin-xml"
]
})
]
}
});
}
if (options.svg) {
configs.push({
files: [GLOB_SVG],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/svg",
rules: {
"format/prettier": [
"error",
mergePrettierOptions({ ...prettierXmlOptions, ...prettierOptions }, {
parser: "xml",
plugins: [
"@prettier/plugin-xml"
]
})
]
}
});
}
if (options.markdown) {
const formater = options.markdown === true ? "prettier" : options.markdown;
configs.push({
files: [GLOB_MARKDOWN],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/markdown",
rules: {
[`format/${formater}`]: [
"error",
formater === "prettier" ? mergePrettierOptions(prettierOptions, {
embeddedLanguageFormatting: "off",
parser: "markdown"
}) : {
...dprintOptions,
language: "markdown"
}
]
}
});
}
if (options.graphql) {
configs.push({
files: [GLOB_GRAPHQL],
languageOptions: {
parser: parserPlain
},
name: "nuxt/formatter/graphql",
rules: {
"format/prettier": [
"error",
mergePrettierOptions(prettierOptions, {
parser: "graphql"
})
]
}
});
}
return configs;
}
export { formatters };

View file

@ -0,0 +1,40 @@
import { r as resolveOptions } from '../shared/eslint-config.CePp8IWi.mjs';
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
import 'pathe';
import 'node:process';
import 'local-pkg';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';
async function imports(options) {
const resolved = resolveOptions(options);
if (resolved.features.import === false) {
return [];
}
const importOptions = resolved.features.import === true ? {} : resolved.features.import || {};
const plugin = importOptions.package === "eslint-plugin-import-lite" ? (await import('eslint-plugin-import-lite')).default : (await import('eslint-plugin-import-x')).default;
return [
{
name: "nuxt/import/rules",
plugins: {
import: plugin
},
rules: {
...importOptions.package === "eslint-plugin-import-lite" ? {
"import/consistent-type-specifier-style": ["error", "top-level"]
} : {},
"import/first": "error",
"import/no-duplicates": "error",
"import/no-mutable-exports": "error",
"import/no-named-default": "error",
...resolved.features.stylistic ? {
"import/newline-after-import": ["error", { count: 1 }]
} : {}
}
}
];
}
export { imports as default };

View file

@ -0,0 +1,47 @@
import jsdocPlugin from 'eslint-plugin-jsdoc';
import { G as GLOB_SRC, a as GLOB_VUE } from '../shared/eslint-config.CUi9znUC.mjs';
import { r as resolveOptions } from '../shared/eslint-config.CePp8IWi.mjs';
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
import 'pathe';
import 'node:process';
import 'local-pkg';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';
function jsdoc(options = {}) {
const resolved = resolveOptions(options);
return [
{
name: "nuxt/tooling/jsdoc",
files: [GLOB_SRC, GLOB_VUE],
plugins: {
jsdoc: jsdocPlugin
},
rules: {
"jsdoc/check-access": "warn",
"jsdoc/check-param-names": "warn",
"jsdoc/check-property-names": "warn",
"jsdoc/check-types": "warn",
"jsdoc/empty-tags": "warn",
"jsdoc/implements-on-classes": "warn",
"jsdoc/no-defaults": "warn",
"jsdoc/no-multi-asterisks": "warn",
"jsdoc/require-param-name": "warn",
"jsdoc/require-property": "warn",
"jsdoc/require-property-description": "warn",
"jsdoc/require-property-name": "warn",
"jsdoc/require-returns-check": "warn",
"jsdoc/require-returns-description": "warn",
"jsdoc/require-yields-check": "warn",
...resolved.features.stylistic ? {
"jsdoc/check-alignment": "warn",
"jsdoc/multiline-blocks": "warn"
} : {}
}
}
];
}
export { jsdoc as default };

View file

@ -0,0 +1,14 @@
import { configs } from 'eslint-plugin-regexp';
import { G as GLOB_SRC, a as GLOB_VUE } from '../shared/eslint-config.CUi9znUC.mjs';
function regexp() {
return [
{
...configs["flat/recommended"],
name: "nuxt/tooling/regexp",
files: [GLOB_SRC, GLOB_VUE]
}
];
}
export { regexp as default };

View file

@ -0,0 +1,12 @@
import stylistic$1 from '@stylistic/eslint-plugin';
import { G as GLOB_SRC, a as GLOB_VUE } from '../shared/eslint-config.CUi9znUC.mjs';
const stylistic = (options) => {
return {
name: "nuxt/stylistic",
files: [GLOB_SRC, GLOB_VUE],
...stylistic$1.configs.customize(options)
};
};
export { stylistic as default };

View file

@ -0,0 +1,125 @@
import parserTs from '@typescript-eslint/parser';
export { default as parserTs } from '@typescript-eslint/parser';
import pluginTs from '@typescript-eslint/eslint-plugin';
export { default as pluginTs } from '@typescript-eslint/eslint-plugin';
import { r as resolveOptions } from '../shared/eslint-config.CePp8IWi.mjs';
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
import 'pathe';
import 'node:process';
import 'local-pkg';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';
const getRulesFromConfigs = (config) => {
const array = Array.isArray(config) ? config : [config];
const object = array.reduce((acc, item) => {
return { ...acc, ...item.rules };
}, {});
return object;
};
function typescript(options) {
const resolved = resolveOptions(options);
if (resolved.features.typescript === false) {
return [];
}
const tsOptions = resolved.features.typescript === true ? {} : resolved.features.typescript;
const strict = tsOptions.strict === false ? false : true;
const tsconfigPath = tsOptions.tsconfigPath || void 0;
return [
{
name: "nuxt/typescript/setup",
plugins: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"@typescript-eslint": pluginTs
}
},
{
name: "nuxt/typescript/rules",
files: ["**/*.ts", "**/*.tsx", "**/*.mts", "**/*.cts", "**/*.vue"],
languageOptions: {
parser: parserTs,
parserOptions: {
extraFileExtensions: [".vue"],
sourceType: "module",
...tsconfigPath ? {
projectService: {
allowDefaultProject: ["./*.js"],
defaultProject: tsconfigPath
},
tsconfigRootDir: process.cwd()
} : {}
}
},
rules: {
...getRulesFromConfigs(pluginTs.configs["flat/recommended"]),
// Type-aware rules
...tsconfigPath ? getRulesFromConfigs(pluginTs.configs["flat/recommended-type-checked-only"]) : {},
// Strict rules
...strict ? tsconfigPath ? getRulesFromConfigs(pluginTs.configs["flat/strict-type-checked-only"]) : getRulesFromConfigs(pluginTs.configs["flat/strict"]) : {},
// Include typescript eslint rules in *.vue files
// https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/src/configs/eslint-recommended.ts
"constructor-super": "off",
// ts(2335) & ts(2377)
"getter-return": "off",
// ts(2378)
"no-const-assign": "off",
// ts(2588)
"no-dupe-args": "off",
// ts(2300)
"no-dupe-class-members": "off",
// ts(2393) & ts(2300)
"no-dupe-keys": "off",
// ts(1117)
"no-func-assign": "off",
// ts(2539)
"no-import-assign": "off",
// ts(2539) & ts(2540)
"no-new-symbol": "off",
// ts(7009)
"no-obj-calls": "off",
// ts(2349)
"no-redeclare": "off",
// ts(2451)
"no-setter-return": "off",
// ts(2408)
"no-this-before-super": "off",
// ts(2376)
"no-undef": "off",
// ts(2304)
"no-unreachable": "off",
// ts(7027)
"no-unsafe-negation": "off",
// ts(2365) & ts(2360) & ts(2358)
"no-var": "error",
// ts transpiles let/const to var, so no need for vars any more
"prefer-const": "error",
// ts provides better types with const
"prefer-rest-params": "error",
// ts provides better types with rest args over arguments
"prefer-spread": "error",
// ts transpiles spread to apply, so no need for manual apply
"valid-typeof": "off",
// ts(2367)
"no-unused-vars": "off",
// ts takes care of this
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/consistent-type-imports": ["error", {
disallowTypeAnnotations: false,
prefer: "type-imports"
}],
"@typescript-eslint/no-unused-vars": ["error", {
args: "after-used",
argsIgnorePattern: "^_",
ignoreRestSiblings: true,
vars: "all",
varsIgnorePattern: "^_"
}],
"@typescript-eslint/no-import-type-side-effects": "error"
}
}
];
}
export { typescript as default };

View file

@ -0,0 +1,44 @@
import pluginUnicorn from 'eslint-plugin-unicorn';
import { G as GLOB_SRC, a as GLOB_VUE } from '../shared/eslint-config.CUi9znUC.mjs';
function unicorn() {
return [
{
name: "nuxt/tooling/unicorn",
files: [GLOB_SRC, GLOB_VUE],
plugins: {
unicorn: pluginUnicorn
},
rules: {
// Pass error message when throwing errors
"unicorn/error-message": "error",
// Uppercase regex escapes
"unicorn/escape-case": "error",
// Array.isArray instead of instanceof
"unicorn/no-instanceof-array": "error",
// Ban `new Array` as `Array` constructor's params are ambiguous
"unicorn/no-new-array": "error",
// Prevent deprecated `new Buffer()`
"unicorn/no-new-buffer": "error",
// Lowercase number formatting for octal, hex, binary (0x1'error' instead of 0X1'error')
"unicorn/number-literal-case": "error",
// textContent instead of innerText
"unicorn/prefer-dom-node-text-content": "error",
// includes over indexOf when checking for existence
"unicorn/prefer-includes": "error",
// Prefer using the node: protocol
"unicorn/prefer-node-protocol": "error",
// Prefer using number properties like `Number.isNaN` rather than `isNaN`
"unicorn/prefer-number-properties": "error",
// String methods startsWith/endsWith instead of more complicated stuff
"unicorn/prefer-string-starts-ends-with": "error",
// Enforce throwing type error when throwing error while checking typeof
"unicorn/prefer-type-error": "error",
// Use new when throwing error
"unicorn/throw-new-error": "error"
}
}
];
}
export { unicorn as default };

View file

@ -0,0 +1,156 @@
import * as parserVue from 'vue-eslint-parser';
import pluginVue from 'eslint-plugin-vue';
import processorVueBlocks from 'eslint-processor-vue-blocks';
import { mergeProcessors } from 'eslint-merge-processors';
import { r as resolveOptions, a as removeUndefined } from '../shared/eslint-config.CePp8IWi.mjs';
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
import 'pathe';
import 'node:process';
import 'local-pkg';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';
const INLINE_ELEMENTS = ["a", "abbr", "audio", "b", "bdi", "bdo", "canvas", "cite", "code", "data", "del", "dfn", "em", "i", "iframe", "ins", "kbd", "label", "map", "mark", "noscript", "object", "output", "picture", "q", "ruby", "s", "samp", "small", "span", "strong", "sub", "sup", "svg", "time", "u", "var", "video"];
async function vue(options) {
const resolved = resolveOptions(options);
const hasTs = resolved.features.typescript !== false;
const parser = hasTs ? await import('./typescript.mjs').then((mod) => mod.parserTs) : void 0;
const {
indent = 2,
commaDangle = "always-multiline"
} = typeof resolved.features.stylistic === "boolean" ? {} : resolved.features.stylistic;
const configs = [
{
name: "nuxt/vue/setup",
plugins: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
vue: pluginVue
},
languageOptions: {
parserOptions: {
ecmaVersion: "latest",
extraFileExtensions: [".vue"],
parser,
sourceType: "module",
ecmaFeatures: {
jsx: true
}
},
// This allows Vue plugin to work with auto imports
// https://github.com/vuejs/eslint-plugin-vue/pull/2422
globals: {
computed: "readonly",
defineEmits: "readonly",
defineExpose: "readonly",
defineProps: "readonly",
onMounted: "readonly",
onUnmounted: "readonly",
reactive: "readonly",
ref: "readonly",
shallowReactive: "readonly",
shallowRef: "readonly",
toRef: "readonly",
toRefs: "readonly",
watch: "readonly",
watchEffect: "readonly"
}
}
},
{
name: "nuxt/vue/rules",
files: [
"**/*.vue"
],
languageOptions: {
parser: parserVue
},
processor: options.features?.formatters ? mergeProcessors([
pluginVue.processors[".vue"],
processorVueBlocks({
blocks: {
styles: true
}
})
]) : pluginVue.processors[".vue"],
rules: {
...pluginVue.configs.base.rules,
...pluginVue.configs["flat/essential"].map((c) => c.rules).reduce((acc, c) => ({ ...acc, ...c }), {}),
...pluginVue.configs["flat/strongly-recommended"].map((c) => c.rules).reduce((acc, c) => ({ ...acc, ...c }), {}),
...pluginVue.configs["flat/recommended"].map((c) => c.rules).reduce((acc, c) => ({ ...acc, ...c }), {}),
// Deprecated in favor of 'vue/block-order'
"vue/component-tags-order": void 0,
"vue/block-order": "warn",
...resolved.features.stylistic ? {
"vue/array-bracket-spacing": ["error", "never"],
"vue/arrow-spacing": ["error", { after: true, before: true }],
"vue/block-spacing": ["error", "always"],
"vue/block-tag-newline": [
"error",
{
multiline: "always",
singleline: "always"
}
],
"vue/brace-style": ["error", "stroustrup", { allowSingleLine: true }],
"vue/html-indent": ["error", indent],
"vue/html-quotes": ["error", "double"],
"vue/comma-dangle": ["error", commaDangle],
"vue/comma-spacing": ["error", { after: true, before: false }],
"vue/comma-style": ["error", "last"],
"vue/html-comment-content-spacing": [
"error",
"always",
{ exceptions: ["-"] }
],
"vue/key-spacing": ["error", { afterColon: true, beforeColon: false }],
"vue/keyword-spacing": ["error", { after: true, before: true }],
"vue/object-curly-newline": "off",
"vue/object-curly-spacing": ["error", "always"],
"vue/object-property-newline": [
"error",
{ allowAllPropertiesOnSameLine: true }
],
"vue/one-component-per-file": "off",
"vue/operator-linebreak": ["error", "before"],
"vue/padding-line-between-blocks": ["error", "always"],
"vue/quote-props": ["error", "consistent-as-needed"],
"vue/require-default-prop": "off",
"vue/space-in-parens": ["error", "never"],
"vue/template-curly-spacing": "error",
"vue/multiline-html-element-content-newline": ["error", {
ignoreWhenEmpty: true,
ignores: ["pre", "textarea", "router-link", "RouterLink", "nuxt-link", "NuxtLink", "u-link", "ULink", ...INLINE_ELEMENTS],
allowEmptyLines: false
}],
"vue/singleline-html-element-content-newline": ["error", {
ignoreWhenNoAttributes: true,
ignoreWhenEmpty: true,
ignores: ["pre", "textarea", "router-link", "RouterLink", "nuxt-link", "NuxtLink", "u-link", "ULink", ...INLINE_ELEMENTS],
externalIgnores: []
}]
} : {
// Disable Vue's default stylistic rules when stylistic is not enabled
"vue/html-closing-bracket-newline": void 0,
"vue/html-closing-bracket-spacing": void 0,
"vue/html-indent": void 0,
"vue/html-quotes": void 0,
"vue/max-attributes-per-line": void 0,
"vue/multiline-html-element-content-newline": void 0,
"vue/mustache-interpolation-spacing": void 0,
"vue/no-multi-spaces": void 0,
"vue/no-spaces-around-equal-signs-in-attribute": void 0,
"vue/singleline-html-element-content-newline": void 0
}
}
}
];
for (const config of configs) {
if (config.rules)
config.rules = removeUndefined(config.rules);
}
return configs;
}
export { vue as default };

View file

@ -0,0 +1,3 @@
export { Awaitable, ImportPluginOptions, NuxtESLintConfigOptions, NuxtESLintConfigOptionsResolved, NuxtESLintFeaturesOptions, NuxtSpecificOptions, OptionsFormatters, ToolingOptions, default as createConfigForNuxt, defineFlatConfigs, resolveOptions } from './index.mjs';
import 'eslint-flat-config-utils';
import '@stylistic/eslint-plugin';

View file

@ -0,0 +1,3 @@
export { Awaitable, ImportPluginOptions, NuxtESLintConfigOptions, NuxtESLintConfigOptionsResolved, NuxtESLintFeaturesOptions, NuxtSpecificOptions, OptionsFormatters, ToolingOptions, default as createConfigForNuxt, defineFlatConfigs, resolveOptions } from './index.js';
import 'eslint-flat-config-utils';
import '@stylistic/eslint-plugin';

View file

@ -0,0 +1,9 @@
export { c as createConfigForNuxt, d as defineFlatConfigs, r as resolveOptions } from './shared/eslint-config.CePp8IWi.mjs';
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
import 'pathe';
import 'node:process';
import 'local-pkg';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';

View file

@ -0,0 +1,227 @@
import { ResolvableFlatConfig, FlatConfigComposer } from 'eslint-flat-config-utils';
import { StylisticCustomizeOptions } from '@stylistic/eslint-plugin';
interface ToolingOptions {
/**
* Enable RegExp rules
*
* @see https://github.com/ota-meshi/eslint-plugin-regexp
* @default true
*/
regexp?: boolean;
/**
* Enable Unicorn rules
*
* @see https://github.com/sindresorhus/eslint-plugin-unicorn
* @default true
*/
unicorn?: boolean;
/**
* Enable jsdoc rules
*
* @default true
*/
jsdoc?: boolean;
}
interface NuxtSpecificOptions {
/**
* Sort keys in nuxt.config to maintain a consistent order
*
* @default true when `features.stylistic` is enabled
*/
sortConfigKeys?: boolean;
}
interface NuxtESLintFeaturesOptions {
/**
* Setup basic JavaScript, TypeScript and Vue plugins and rules.
*
* You might want to disable it when you are using other ESLint config that handles the basic setup.
*
* @default true
*/
standalone?: boolean;
/**
* Enable rules for Nuxt module authors or library authors
*
* @experimental Changes might not follow semver
* @default false
*/
tooling?: boolean | ToolingOptions;
/**
* Enable the import plugin
*
* @default true
*/
import?: boolean | ImportPluginOptions;
/**
* Enable stylistic ESLint rules for formatting and code style check
*
* @see https://eslint.style/guide/config-presets
* @default false
*/
stylistic?: boolean | StylisticCustomizeOptions;
/**
* Enable formatters to handling formatting for different file types
*
* Requires `eslint-plugin-format` to be installed
*
* @default false
*/
formatters?: boolean | OptionsFormatters;
/**
* Options for Nuxt specific rules
*/
nuxt?: NuxtSpecificOptions;
/**
* Enable TypeScript support. Can also be an object to config the options.
*
* By default it enables automatic when `typescript` is installed in the project.
*/
typescript?: boolean | {
/**
* Enable strict rules
* @see https://typescript-eslint.io/users/configs#strict
* @default true
*/
strict?: boolean;
/**
* Path to the tsconfig file, when this is provide, type-aware rules will be enabled.
*/
tsconfigPath?: string;
};
}
interface ImportPluginOptions {
/**
* The import plugin to use
*
* @default 'eslint-plugin-import-x'
*/
package?: 'eslint-plugin-import-lite' | 'eslint-plugin-import-x';
}
interface NuxtESLintConfigOptions {
features?: NuxtESLintFeaturesOptions;
dirs?: {
/**
* Nuxt source directory
*/
src?: string[];
/**
* Root directory for nuxt project
*/
root?: string[];
/**
* Directory for pages
*/
pages?: string[];
/**
* Directory for layouts
*/
layouts?: string[];
/**
* Directory for components
*/
components?: string[];
/**
* Directory for components with prefix
* Ignore `vue/multi-word-component-names`
*/
componentsPrefixed?: string[];
/**
* Directory for composobles
*/
composables?: string[];
/**
* Directory for plugins
*/
plugins?: string[];
/**
* Directory for modules
*/
modules?: string[];
/**
* Directory for middleware
*/
middleware?: string[];
/**
* Directory for server
*/
servers?: string[];
};
}
interface OptionsFormatters {
/**
* Enable formatting support for CSS, Less, Sass, and SCSS.
*
* Currently only support Prettier.
*/
css?: 'prettier' | boolean;
/**
* Enable formatting support for HTML.
*
* Currently only support Prettier.
*/
html?: 'prettier' | boolean;
/**
* Enable formatting support for XML.
*
* Currently only support Prettier.
*/
xml?: 'prettier' | boolean;
/**
* Enable formatting support for SVG.
*
* Currently only support Prettier.
*/
svg?: 'prettier' | boolean;
/**
* Enable formatting support for Markdown.
*
* Support both Prettier and dprint.
*
* When set to `true`, it will use Prettier.
*/
markdown?: 'prettier' | 'dprint' | boolean;
/**
* Enable formatting support for GraphQL.
*/
graphql?: 'prettier' | boolean;
/**
* Custom options for Prettier.
*
* By default it's controlled by our own config.
*/
prettierOptions?: any;
/**
* Custom options for dprint.
*
* By default it's controlled by our own config.
*/
dprintOptions?: boolean;
}
type NotNill<T> = T extends null | undefined ? never : T;
interface NuxtESLintConfigOptionsResolved {
features: Required<NotNill<NuxtESLintFeaturesOptions>>;
dirs: Required<NotNill<NuxtESLintConfigOptions['dirs']>>;
}
type Awaitable<T> = T | Promise<T>;
declare function resolveOptions(config: NuxtESLintConfigOptions): NuxtESLintConfigOptionsResolved;
/**
* Provide type definitions for constructing ESLint flat config items.
*
* This function takes flat config item, or an array of them as rest arguments.
* It also automatically resolves the promise if the config item is a promise.
*/
declare function defineFlatConfigs(...configs: ResolvableFlatConfig[]): FlatConfigComposer;
/**
* Create an array of ESLint flat configs for Nuxt 3, based on the given options.
* Accepts appending user configs as rest arguments from the second argument.
*
* For Nuxt apps, it's recommended to use `@nuxt/eslint` module instead, which will generate the necessary configuration based on your project.
* @see https://eslint.nuxt.com/packages/module
*/
declare function createConfigForNuxt(options?: NuxtESLintConfigOptions, ...userConfigs: ResolvableFlatConfig[]): FlatConfigComposer;
export { createConfigForNuxt, createConfigForNuxt as default, defineFlatConfigs, resolveOptions };
export type { Awaitable, ImportPluginOptions, NuxtESLintConfigOptions, NuxtESLintConfigOptionsResolved, NuxtESLintFeaturesOptions, NuxtSpecificOptions, OptionsFormatters, ToolingOptions };

View file

@ -0,0 +1,227 @@
import { ResolvableFlatConfig, FlatConfigComposer } from 'eslint-flat-config-utils';
import { StylisticCustomizeOptions } from '@stylistic/eslint-plugin';
interface ToolingOptions {
/**
* Enable RegExp rules
*
* @see https://github.com/ota-meshi/eslint-plugin-regexp
* @default true
*/
regexp?: boolean;
/**
* Enable Unicorn rules
*
* @see https://github.com/sindresorhus/eslint-plugin-unicorn
* @default true
*/
unicorn?: boolean;
/**
* Enable jsdoc rules
*
* @default true
*/
jsdoc?: boolean;
}
interface NuxtSpecificOptions {
/**
* Sort keys in nuxt.config to maintain a consistent order
*
* @default true when `features.stylistic` is enabled
*/
sortConfigKeys?: boolean;
}
interface NuxtESLintFeaturesOptions {
/**
* Setup basic JavaScript, TypeScript and Vue plugins and rules.
*
* You might want to disable it when you are using other ESLint config that handles the basic setup.
*
* @default true
*/
standalone?: boolean;
/**
* Enable rules for Nuxt module authors or library authors
*
* @experimental Changes might not follow semver
* @default false
*/
tooling?: boolean | ToolingOptions;
/**
* Enable the import plugin
*
* @default true
*/
import?: boolean | ImportPluginOptions;
/**
* Enable stylistic ESLint rules for formatting and code style check
*
* @see https://eslint.style/guide/config-presets
* @default false
*/
stylistic?: boolean | StylisticCustomizeOptions;
/**
* Enable formatters to handling formatting for different file types
*
* Requires `eslint-plugin-format` to be installed
*
* @default false
*/
formatters?: boolean | OptionsFormatters;
/**
* Options for Nuxt specific rules
*/
nuxt?: NuxtSpecificOptions;
/**
* Enable TypeScript support. Can also be an object to config the options.
*
* By default it enables automatic when `typescript` is installed in the project.
*/
typescript?: boolean | {
/**
* Enable strict rules
* @see https://typescript-eslint.io/users/configs#strict
* @default true
*/
strict?: boolean;
/**
* Path to the tsconfig file, when this is provide, type-aware rules will be enabled.
*/
tsconfigPath?: string;
};
}
interface ImportPluginOptions {
/**
* The import plugin to use
*
* @default 'eslint-plugin-import-x'
*/
package?: 'eslint-plugin-import-lite' | 'eslint-plugin-import-x';
}
interface NuxtESLintConfigOptions {
features?: NuxtESLintFeaturesOptions;
dirs?: {
/**
* Nuxt source directory
*/
src?: string[];
/**
* Root directory for nuxt project
*/
root?: string[];
/**
* Directory for pages
*/
pages?: string[];
/**
* Directory for layouts
*/
layouts?: string[];
/**
* Directory for components
*/
components?: string[];
/**
* Directory for components with prefix
* Ignore `vue/multi-word-component-names`
*/
componentsPrefixed?: string[];
/**
* Directory for composobles
*/
composables?: string[];
/**
* Directory for plugins
*/
plugins?: string[];
/**
* Directory for modules
*/
modules?: string[];
/**
* Directory for middleware
*/
middleware?: string[];
/**
* Directory for server
*/
servers?: string[];
};
}
interface OptionsFormatters {
/**
* Enable formatting support for CSS, Less, Sass, and SCSS.
*
* Currently only support Prettier.
*/
css?: 'prettier' | boolean;
/**
* Enable formatting support for HTML.
*
* Currently only support Prettier.
*/
html?: 'prettier' | boolean;
/**
* Enable formatting support for XML.
*
* Currently only support Prettier.
*/
xml?: 'prettier' | boolean;
/**
* Enable formatting support for SVG.
*
* Currently only support Prettier.
*/
svg?: 'prettier' | boolean;
/**
* Enable formatting support for Markdown.
*
* Support both Prettier and dprint.
*
* When set to `true`, it will use Prettier.
*/
markdown?: 'prettier' | 'dprint' | boolean;
/**
* Enable formatting support for GraphQL.
*/
graphql?: 'prettier' | boolean;
/**
* Custom options for Prettier.
*
* By default it's controlled by our own config.
*/
prettierOptions?: any;
/**
* Custom options for dprint.
*
* By default it's controlled by our own config.
*/
dprintOptions?: boolean;
}
type NotNill<T> = T extends null | undefined ? never : T;
interface NuxtESLintConfigOptionsResolved {
features: Required<NotNill<NuxtESLintFeaturesOptions>>;
dirs: Required<NotNill<NuxtESLintConfigOptions['dirs']>>;
}
type Awaitable<T> = T | Promise<T>;
declare function resolveOptions(config: NuxtESLintConfigOptions): NuxtESLintConfigOptionsResolved;
/**
* Provide type definitions for constructing ESLint flat config items.
*
* This function takes flat config item, or an array of them as rest arguments.
* It also automatically resolves the promise if the config item is a promise.
*/
declare function defineFlatConfigs(...configs: ResolvableFlatConfig[]): FlatConfigComposer;
/**
* Create an array of ESLint flat configs for Nuxt 3, based on the given options.
* Accepts appending user configs as rest arguments from the second argument.
*
* For Nuxt apps, it's recommended to use `@nuxt/eslint` module instead, which will generate the necessary configuration based on your project.
* @see https://eslint.nuxt.com/packages/module
*/
declare function createConfigForNuxt(options?: NuxtESLintConfigOptions, ...userConfigs: ResolvableFlatConfig[]): FlatConfigComposer;
export { createConfigForNuxt, createConfigForNuxt as default, defineFlatConfigs, resolveOptions };
export type { Awaitable, ImportPluginOptions, NuxtESLintConfigOptions, NuxtESLintConfigOptionsResolved, NuxtESLintFeaturesOptions, NuxtSpecificOptions, OptionsFormatters, ToolingOptions };

View file

@ -0,0 +1,9 @@
import 'eslint-flat-config-utils';
import 'eslint-config-flat-gitignore';
export { c as createConfigForNuxt, c as default, d as defineFlatConfigs, r as resolveOptions } from './shared/eslint-config.CePp8IWi.mjs';
import 'pathe';
import 'node:process';
import 'local-pkg';
import '@nuxt/eslint-plugin';
import '@eslint/js';
import 'globals';

View file

@ -0,0 +1,13 @@
const GLOB_SRC = "**/*.?([cm])[jt]s?(x)";
const GLOB_CSS = "**/*.css";
const GLOB_POSTCSS = "**/*.{p,post}css";
const GLOB_LESS = "**/*.less";
const GLOB_SCSS = "**/*.scss";
const GLOB_MARKDOWN = "**/*.md";
const GLOB_VUE = "**/*.vue";
const GLOB_XML = "**/*.xml";
const GLOB_SVG = "**/*.svg";
const GLOB_HTML = "**/*.htm?(l)";
const GLOB_GRAPHQL = "**/*.{g,graph}ql";
export { GLOB_SRC as G, GLOB_VUE as a, GLOB_CSS as b, GLOB_POSTCSS as c, GLOB_SCSS as d, GLOB_LESS as e, GLOB_HTML as f, GLOB_XML as g, GLOB_SVG as h, GLOB_MARKDOWN as i, GLOB_GRAPHQL as j };

View file

@ -0,0 +1,286 @@
import { composer } from 'eslint-flat-config-utils';
import gitignore from 'eslint-config-flat-gitignore';
import { join } from 'pathe';
import process from 'node:process';
import { isPackageExists } from 'local-pkg';
import nuxtPlugin from '@nuxt/eslint-plugin';
import pluginESLint from '@eslint/js';
import globals from 'globals';
const GLOB_EXTS = "{js,ts,jsx,tsx,vue}";
const parserPlain = {
meta: {
name: "parser-plain"
},
parseForESLint: (code) => ({
ast: {
body: [],
comments: [],
loc: { end: code.length, start: 0 },
range: [0, code.length],
tokens: [],
type: "Program"
},
scopeManager: null,
services: { isPlain: true },
visitorKeys: {
Program: []
}
})
};
async function ensurePackages(packages) {
if (process.env.CI || !process.stdout.isTTY)
return;
const nonExistingPackages = packages.filter((i) => i && !isPackageExists(i));
if (nonExistingPackages.length === 0)
return;
const p = await import('@clack/prompts');
const result = await p.confirm({
message: `${nonExistingPackages.length === 1 ? "Package is" : "Packages are"} required for this config: ${nonExistingPackages.join(", ")}. Do you want to install them?`
});
if (result)
await import('@antfu/install-pkg').then((i) => i.installPackage(nonExistingPackages, { dev: true }));
}
async function interopDefault(m) {
const resolved = await m;
return resolved.default || resolved;
}
function removeUndefined(obj) {
return Object.fromEntries(Object.entries(obj).filter(([, value]) => value !== void 0));
}
function resolveOptions(config) {
if ("__resolved" in config) {
return config;
}
const dirs = {
...config.dirs
};
dirs.root ||= [".", "./app"];
dirs.src ||= dirs.root;
dirs.pages ||= dirs.src.map((src) => `${src}/pages`);
dirs.layouts ||= dirs.src.map((src) => `${src}/layouts`);
dirs.components ||= dirs.src.map((src) => `${src}/components`);
dirs.composables ||= dirs.src.map((src) => `${src}/composables`);
dirs.plugins ||= dirs.src.map((src) => `${src}/plugins`);
dirs.modules ||= dirs.src.map((src) => `${src}/modules`);
dirs.middleware ||= dirs.src.map((src) => `${src}/middleware`);
dirs.servers ||= dirs.src.map((src) => `${src}/servers`);
dirs.componentsPrefixed ||= [];
const resolved = {
features: {
standalone: true,
stylistic: false,
typescript: isPackageExists("typescript"),
tooling: false,
formatters: false,
nuxt: {},
import: {},
...config.features
},
dirs
};
Object.defineProperty(resolved, "__resolved", { value: true, enumerable: false });
return resolved;
}
function disables(options) {
const resolved = resolveOptions(options);
const dirs = resolved.dirs;
const nestedGlobPattern = `**/*.${GLOB_EXTS}`;
const fileRoutes = [.../* @__PURE__ */ new Set([
// These files must have one-word names as they have a special meaning in Nuxt.
...dirs.src.flatMap((layersDir) => [
join(layersDir, `app.${GLOB_EXTS}`),
join(layersDir, `error.${GLOB_EXTS}`)
]) || [],
// Layouts and pages are not used directly by users so they can have one-word names.
...dirs.layouts.map((layoutsDir) => join(layoutsDir, nestedGlobPattern)) || [],
...dirs.pages.map((pagesDir) => join(pagesDir, nestedGlobPattern)) || [],
// These files should have multiple words in their names as they are within subdirectories.
...dirs.components.map((componentsDir) => join(componentsDir, "*", nestedGlobPattern)) || [],
// Prefixed components can have one-word names in file
...dirs.componentsPrefixed.map((componentsDir) => join(componentsDir, nestedGlobPattern)) || []
])].sort();
const configs = [];
if (fileRoutes.length) {
configs.push({
name: "nuxt/disables/routes",
files: fileRoutes,
rules: {
"vue/multi-word-component-names": "off"
}
});
}
return configs;
}
function nuxt(options) {
const resolved = resolveOptions(options);
const dirs = resolved.dirs;
const fileSingleRoot = [
...dirs.layouts?.map((layoutsDir) => join(layoutsDir, `**/*.${GLOB_EXTS}`)) || [],
...dirs.pages?.map((pagesDir) => join(pagesDir, `**/*.${GLOB_EXTS}`)) || [],
...dirs.components?.map((componentsDir) => join(componentsDir, `**/*.server.${GLOB_EXTS}`)) || []
].sort();
const {
sortConfigKeys = !!options.features?.stylistic
} = options.features?.nuxt || {};
const configs = [];
configs.push({
name: "nuxt/setup",
plugins: {
nuxt: nuxtPlugin
},
languageOptions: {
globals: {
// Nuxt's runtime globals
$fetch: "readonly"
}
}
});
if (fileSingleRoot.length)
configs.push({
name: "nuxt/vue/single-root",
files: fileSingleRoot,
rules: {
"vue/no-multiple-template-root": "error"
}
});
configs.push({
name: "nuxt/rules",
rules: {
"nuxt/prefer-import-meta": "error"
}
});
configs.push({
name: "nuxt/nuxt-config",
files: [
"**/.config/nuxt.?([cm])[jt]s?(x)",
"**/nuxt.config.?([cm])[jt]s?(x)"
],
rules: {
"nuxt/no-nuxt-config-test-key": "error"
}
});
if (sortConfigKeys) {
configs.push({
name: "nuxt/sort-config",
files: [
"**/.config/nuxt.?([cm])[jt]s?(x)",
"**/nuxt.config.?([cm])[jt]s?(x)"
],
rules: {
"nuxt/nuxt-config-keys-order": "error"
}
});
}
return configs;
}
function ignores() {
return [
{
ignores: [
"**/dist",
"**/node_modules",
"**/.nuxt",
"**/.output",
"**/.vercel",
"**/.netlify",
"**/public"
]
}
];
}
function javascript() {
return [
{
...pluginESLint.configs.recommended,
name: "nuxt/javascript",
languageOptions: {
ecmaVersion: 2022,
parserOptions: {
ecmaFeatures: {
jsx: true
},
ecmaVersion: 2022,
sourceType: "module"
},
sourceType: "module",
globals: {
...globals.browser,
...globals.es2021,
...globals.node,
document: "readonly",
navigator: "readonly",
window: "readonly",
// This is technically not a global function, but it's a common practice in nuxt.config.ts,
// we include it here to avoid false positives.
defineNuxtConfig: "readonly"
}
},
linterOptions: {
reportUnusedDisableDirectives: true
}
}
];
}
function defineFlatConfigs(...configs) {
return composer(...configs);
}
function createConfigForNuxt(options = {}, ...userConfigs) {
const c = composer();
const resolved = resolveOptions(options);
if (resolved.features.standalone !== false) {
c.append(
gitignore({ strict: false }),
ignores(),
javascript(),
// Make these imports async, as they are optional and imports plugins
resolved.features.typescript !== false ? import('../chunks/typescript.mjs').then((m) => m.default(resolved)) : void 0,
import('../chunks/vue.mjs').then((m) => m.default(resolved)),
import('../chunks/import.mjs').then((m) => m.default(resolved))
);
}
c.append(
nuxt(resolved)
);
if (resolved.features.tooling) {
const toolingOptions = typeof resolved.features.tooling === "boolean" ? {} : resolved.features.tooling;
c.append(
toolingOptions.jsdoc !== false && import('../chunks/jsdoc.mjs').then((m) => m.default(resolved)),
toolingOptions.unicorn !== false && import('../chunks/unicorn.mjs').then((m) => m.default()),
toolingOptions.regexp !== false && import('../chunks/regexp.mjs').then((m) => m.default())
);
}
const stylisticOptions = typeof resolved.features.stylistic === "boolean" ? {} : resolved.features.stylistic;
if (resolved.features.stylistic) {
c.append(
import('../chunks/stylistic.mjs').then((m) => m.default(stylisticOptions))
);
}
if (resolved.features.formatters) {
c.append(
import('../chunks/formatters.mjs').then((m) => m.formatters(resolved.features.formatters, stylisticOptions))
);
}
c.append(
disables(resolved)
);
if (userConfigs.length > 0) {
c.append(...userConfigs);
}
c.setPluginConflictsError().setPluginConflictsError("import", [
'Different instances of plugin "{{pluginName}}" found in multiple configs:',
"{{configNames}}.",
"You might forget to set `standalone: false`.",
"Please refer to https://eslint.nuxt.com/packages/module#custom-config-presets.",
""
].join("\n"));
return c;
}
export { removeUndefined as a, createConfigForNuxt as c, defineFlatConfigs as d, ensurePackages as e, interopDefault as i, parserPlain as p, resolveOptions as r };

View file

@ -0,0 +1,263 @@
# @clack/core
## 0.5.0
### Minor Changes
- 07ca32d: Reverted a change where placeholders were being set as values on return.
## 0.4.2
### Patch Changes
- 30aa7ed: Adds a new `selectableGroups` boolean to the group multi-select prompt. Using `selectableGroups: false` will disable the ability to select a top-level group, but still allow every child to be selected individually.
- 5dfce8a: Fixes an edge case for placeholder values. Previously, when pressing `enter` on an empty prompt, placeholder values would be ignored. Now, placeholder values are treated as the prompt value.
- f574297: Fix "TTY initialization failed: uv_tty_init returned EBADF (bad file descriptor)" error happening on Windows for non-tty terminals.
## 0.4.1
### Patch Changes
- 8093f3c: Adds `Error` support to the `validate` function
- e5ba09a: Fixes a cursor display bug in terminals that do not support the "hidden" escape sequence. See [Issue #127](https://github.com/bombshell-dev/clack/issues/127).
- 8cba8e3: Fixes a rendering bug with cursor positions for `TextPrompt`
## 0.4.0
### Minor Changes
- a83d2f8: Adds a new `updateSettings()` function to support new global keybindings.
`updateSettings()` accepts an `aliases` object that maps custom keys to an action (`up | down | left | right | space | enter | cancel`).
```ts
import { updateSettings } from "@clack/core";
// Support custom keybindings
updateSettings({
aliases: {
w: "up",
a: "left",
s: "down",
d: "right",
},
});
```
> [!WARNING]
> In order to enforce consistent, user-friendly defaults across the ecosystem, `updateSettings` does not support disabling Clack's default keybindings.
- 801246b: Adds a new `signal` option to support programmatic prompt cancellation with an [abort controller](https://kettanaito.com/blog/dont-sleep-on-abort-controller).
- a83d2f8: Updates default keybindings to support Vim motion shortcuts and map the `escape` key to cancel (`ctrl+c`).
| alias | action |
| ----- | ------ |
| `k` | up |
| `l` | right |
| `j` | down |
| `h` | left |
| `esc` | cancel |
### Patch Changes
- 51e12bc: Improves types for events and interaction states.
## 0.3.5
### Patch Changes
- 4845f4f: Fixes a bug which kept the terminal cursor hidden after a prompt is cancelled
- d7b2fb9: Adds missing `LICENSE` file. Since the `package.json` file has always included `"license": "MIT"`, please consider this a licensing clarification rather than a licensing change.
## 0.3.4
### Patch Changes
- a04e418: fix(@clack/core): keyboard input not working after await in spinner
- 4f6fcf5: feat(@clack/core): allow tab completion for placeholders
## 0.3.3
### Patch Changes
- cd79076: fix: restore raw mode on unblock
## 0.3.2
### Patch Changes
- c96eda5: Enable hard line-wrapping behavior for long words without spaces
## 0.3.1
### Patch Changes
- 58a1df1: Fix line duplication bug by automatically wrapping prompts to `process.stdout.columns`
## 0.3.0
### Minor Changes
- 8a4a12f: Add `GroupMultiSelect` prompt
### Patch Changes
- 8a4a12f: add `groupMultiselect` prompt
## 0.2.1
### Patch Changes
- ec812b6: fix `readline` hang on Windows
## 0.2.0
### Minor Changes
- d74dd05: Adds a `selectKey` prompt type
- 54c1bc3: **Breaking Change** `multiselect` has renamed `initialValue` to `initialValues`
## 0.1.9
### Patch Changes
- 1251132: Multiselect: return `Value[]` instead of `Option[]`.
- 8994382: Add a password prompt to `@clack/prompts`
## 0.1.8
### Patch Changes
- d96071c: Don't mutate `initialValue` in `multiselect`, fix parameter type for `validate()`.
Credits to @banjo for the bug report and initial PR!
## 0.1.7
### Patch Changes
- 6d9e675: Add support for neovim cursor motion (`hjkl`)
Thanks [@esau-morais](https://github.com/esau-morais) for the assist!
## 0.1.6
### Patch Changes
- 7fb5375: Adds a new `defaultValue` option to the text prompt, removes automatic usage of the placeholder value.
## 0.1.5
### Patch Changes
- de1314e: Support `required` option for multi-select
## 0.1.4
### Patch Changes
- ca77da1: Fix multiselect initial value logic
- 8aed606: Fix `MaxListenersExceededWarning` by detaching `stdin` listeners on close
## 0.1.3
### Patch Changes
- a99c458: Support `initialValue` option for text prompt
## 0.1.2
### Patch Changes
- Allow isCancel to type guard any unknown value
- 7dcad8f: Allow placeholder to be passed to TextPrompt
- 2242f13: Fix multiselect returning undefined
- b1341d6: Improved placeholder handling
## 0.1.1
### Patch Changes
- 4be7dbf: Ensure raw mode is unset on submit
- b480679: Preserve value if validation fails
## 0.1.0
### Minor Changes
- 7015ec9: Create new prompt: multi-select
## 0.0.12
### Patch Changes
- 9d371c3: Fix rendering bug when using y/n to confirm
## 0.0.11
### Patch Changes
- 441d5b7: fix select return undefined
- d20ef2a: Update keywords, URLs
- fe13c2f: fix cursor missing after submit
## 0.0.10
### Patch Changes
- a0cb382: Add `main` entrypoint
## 0.0.9
### Patch Changes
- Fix node@16 issue (cannot read "createInterface" of undefined)
## 0.0.8
### Patch Changes
- a4b5e13: Bug fixes, exposes `block` utility
## 0.0.7
### Patch Changes
- Fix cursor bug
## 0.0.6
### Patch Changes
- Fix error with character check
## 0.0.5
### Patch Changes
- 491f9e0: update readme
## 0.0.4
### Patch Changes
- 7372d5c: Fix bug with line deletion
## 0.0.3
### Patch Changes
- 5605d28: Do not bundle dependencies (take II)
## 0.0.2
### Patch Changes
- 2ee67cb: don't bundle deps
## 0.0.1
### Patch Changes
- 306598e: Initial publish, still WIP

View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) Nate Moore
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.

View file

@ -0,0 +1,22 @@
# `@clack/core`
Clack contains low-level primitives for implementing your own command-line applications.
Currently, `TextPrompt`, `SelectPrompt`, and `ConfirmPrompt` are exposed as well as the base `Prompt` class.
Each `Prompt` accepts a `render` function.
```js
import { TextPrompt, isCancel } from '@clack/core';
const p = new TextPrompt({
render() {
return `What's your name?\n${this.valueWithCursor}`;
},
});
const name = await p.prompt();
if (isCancel(name)) {
process.exit(0);
}
```

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,211 @@
import { Readable, Writable } from 'node:stream';
declare const actions: readonly ["up", "down", "left", "right", "space", "enter", "cancel"];
type Action = (typeof actions)[number];
interface ClackSettings {
/**
* Set custom global aliases for the default actions.
* This will not overwrite existing aliases, it will only add new ones!
*
* @param aliases - An object that maps aliases to actions
* @default { k: 'up', j: 'down', h: 'left', l: 'right', '\x03': 'cancel', 'escape': 'cancel' }
*/
aliases: Record<string, Action>;
}
declare function updateSettings(updates: ClackSettings): void;
/**
* The state of the prompt
*/
type ClackState = 'initial' | 'active' | 'cancel' | 'submit' | 'error';
/**
* Typed event emitter for clack
*/
interface ClackEvents {
initial: (value?: any) => void;
active: (value?: any) => void;
cancel: (value?: any) => void;
submit: (value?: any) => void;
error: (value?: any) => void;
cursor: (key?: Action) => void;
key: (key?: string) => void;
value: (value?: string) => void;
confirm: (value?: boolean) => void;
finalize: () => void;
}
interface PromptOptions<Self extends Prompt> {
render(this: Omit<Self, 'prompt'>): string | undefined;
placeholder?: string;
initialValue?: any;
validate?: ((value: any) => string | Error | undefined) | undefined;
input?: Readable;
output?: Writable;
debug?: boolean;
signal?: AbortSignal;
}
declare class Prompt {
protected input: Readable;
protected output: Writable;
private _abortSignal?;
private rl;
private opts;
private _render;
private _track;
private _prevFrame;
private _subscribers;
protected _cursor: number;
state: ClackState;
error: string;
value: any;
constructor(options: PromptOptions<Prompt>, trackValue?: boolean);
/**
* Unsubscribe all listeners
*/
protected unsubscribe(): void;
/**
* Set a subscriber with opts
* @param event - The event name
*/
private setSubscriber;
/**
* Subscribe to an event
* @param event - The event name
* @param cb - The callback
*/
on<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]): void;
/**
* Subscribe to an event once
* @param event - The event name
* @param cb - The callback
*/
once<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]): void;
/**
* Emit an event with data
* @param event - The event name
* @param data - The data to pass to the callback
*/
emit<T extends keyof ClackEvents>(event: T, ...data: Parameters<ClackEvents[T]>): void;
prompt(): Promise<string | symbol>;
private onKeypress;
protected close(): void;
private restoreCursor;
private render;
}
interface ConfirmOptions extends PromptOptions<ConfirmPrompt> {
active: string;
inactive: string;
initialValue?: boolean;
}
declare class ConfirmPrompt extends Prompt {
get cursor(): 0 | 1;
private get _value();
constructor(opts: ConfirmOptions);
}
interface GroupMultiSelectOptions<T extends {
value: any;
}> extends PromptOptions<GroupMultiSelectPrompt<T>> {
options: Record<string, T[]>;
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
selectableGroups?: boolean;
}
declare class GroupMultiSelectPrompt<T extends {
value: any;
}> extends Prompt {
#private;
options: (T & {
group: string | boolean;
})[];
cursor: number;
getGroupItems(group: string): T[];
isGroupSelected(group: string): boolean;
private toggleValue;
constructor(opts: GroupMultiSelectOptions<T>);
}
interface MultiSelectOptions<T extends {
value: any;
}> extends PromptOptions<MultiSelectPrompt<T>> {
options: T[];
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
}
declare class MultiSelectPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
private get _value();
private toggleAll;
private toggleValue;
constructor(opts: MultiSelectOptions<T>);
}
interface PasswordOptions extends PromptOptions<PasswordPrompt> {
mask?: string;
}
declare class PasswordPrompt extends Prompt {
valueWithCursor: string;
private _mask;
get cursor(): number;
get masked(): any;
constructor({ mask, ...opts }: PasswordOptions);
}
interface SelectOptions<T extends {
value: any;
}> extends PromptOptions<SelectPrompt<T>> {
options: T[];
initialValue?: T['value'];
}
declare class SelectPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
private get _value();
private changeValue;
constructor(opts: SelectOptions<T>);
}
interface SelectKeyOptions<T extends {
value: any;
}> extends PromptOptions<SelectKeyPrompt<T>> {
options: T[];
}
declare class SelectKeyPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
constructor(opts: SelectKeyOptions<T>);
}
interface TextOptions extends PromptOptions<TextPrompt> {
placeholder?: string;
defaultValue?: string;
}
declare class TextPrompt extends Prompt {
get valueWithCursor(): any;
get cursor(): number;
constructor(opts: TextOptions);
}
declare function isCancel(value: unknown): value is symbol;
declare function block({ input, output, overwrite, hideCursor, }?: {
input?: (NodeJS.ReadStream & {
fd: 0;
}) | undefined;
output?: (NodeJS.WriteStream & {
fd: 1;
}) | undefined;
overwrite?: boolean | undefined;
hideCursor?: boolean | undefined;
}): () => void;
export { type ClackSettings, ConfirmPrompt, GroupMultiSelectPrompt, MultiSelectPrompt, PasswordPrompt, Prompt, SelectKeyPrompt, SelectPrompt, type ClackState as State, TextPrompt, block, isCancel, updateSettings };

View file

@ -0,0 +1,211 @@
import { Readable, Writable } from 'node:stream';
declare const actions: readonly ["up", "down", "left", "right", "space", "enter", "cancel"];
type Action = (typeof actions)[number];
interface ClackSettings {
/**
* Set custom global aliases for the default actions.
* This will not overwrite existing aliases, it will only add new ones!
*
* @param aliases - An object that maps aliases to actions
* @default { k: 'up', j: 'down', h: 'left', l: 'right', '\x03': 'cancel', 'escape': 'cancel' }
*/
aliases: Record<string, Action>;
}
declare function updateSettings(updates: ClackSettings): void;
/**
* The state of the prompt
*/
type ClackState = 'initial' | 'active' | 'cancel' | 'submit' | 'error';
/**
* Typed event emitter for clack
*/
interface ClackEvents {
initial: (value?: any) => void;
active: (value?: any) => void;
cancel: (value?: any) => void;
submit: (value?: any) => void;
error: (value?: any) => void;
cursor: (key?: Action) => void;
key: (key?: string) => void;
value: (value?: string) => void;
confirm: (value?: boolean) => void;
finalize: () => void;
}
interface PromptOptions<Self extends Prompt> {
render(this: Omit<Self, 'prompt'>): string | undefined;
placeholder?: string;
initialValue?: any;
validate?: ((value: any) => string | Error | undefined) | undefined;
input?: Readable;
output?: Writable;
debug?: boolean;
signal?: AbortSignal;
}
declare class Prompt {
protected input: Readable;
protected output: Writable;
private _abortSignal?;
private rl;
private opts;
private _render;
private _track;
private _prevFrame;
private _subscribers;
protected _cursor: number;
state: ClackState;
error: string;
value: any;
constructor(options: PromptOptions<Prompt>, trackValue?: boolean);
/**
* Unsubscribe all listeners
*/
protected unsubscribe(): void;
/**
* Set a subscriber with opts
* @param event - The event name
*/
private setSubscriber;
/**
* Subscribe to an event
* @param event - The event name
* @param cb - The callback
*/
on<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]): void;
/**
* Subscribe to an event once
* @param event - The event name
* @param cb - The callback
*/
once<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]): void;
/**
* Emit an event with data
* @param event - The event name
* @param data - The data to pass to the callback
*/
emit<T extends keyof ClackEvents>(event: T, ...data: Parameters<ClackEvents[T]>): void;
prompt(): Promise<string | symbol>;
private onKeypress;
protected close(): void;
private restoreCursor;
private render;
}
interface ConfirmOptions extends PromptOptions<ConfirmPrompt> {
active: string;
inactive: string;
initialValue?: boolean;
}
declare class ConfirmPrompt extends Prompt {
get cursor(): 0 | 1;
private get _value();
constructor(opts: ConfirmOptions);
}
interface GroupMultiSelectOptions<T extends {
value: any;
}> extends PromptOptions<GroupMultiSelectPrompt<T>> {
options: Record<string, T[]>;
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
selectableGroups?: boolean;
}
declare class GroupMultiSelectPrompt<T extends {
value: any;
}> extends Prompt {
#private;
options: (T & {
group: string | boolean;
})[];
cursor: number;
getGroupItems(group: string): T[];
isGroupSelected(group: string): boolean;
private toggleValue;
constructor(opts: GroupMultiSelectOptions<T>);
}
interface MultiSelectOptions<T extends {
value: any;
}> extends PromptOptions<MultiSelectPrompt<T>> {
options: T[];
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
}
declare class MultiSelectPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
private get _value();
private toggleAll;
private toggleValue;
constructor(opts: MultiSelectOptions<T>);
}
interface PasswordOptions extends PromptOptions<PasswordPrompt> {
mask?: string;
}
declare class PasswordPrompt extends Prompt {
valueWithCursor: string;
private _mask;
get cursor(): number;
get masked(): any;
constructor({ mask, ...opts }: PasswordOptions);
}
interface SelectOptions<T extends {
value: any;
}> extends PromptOptions<SelectPrompt<T>> {
options: T[];
initialValue?: T['value'];
}
declare class SelectPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
private get _value();
private changeValue;
constructor(opts: SelectOptions<T>);
}
interface SelectKeyOptions<T extends {
value: any;
}> extends PromptOptions<SelectKeyPrompt<T>> {
options: T[];
}
declare class SelectKeyPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
constructor(opts: SelectKeyOptions<T>);
}
interface TextOptions extends PromptOptions<TextPrompt> {
placeholder?: string;
defaultValue?: string;
}
declare class TextPrompt extends Prompt {
get valueWithCursor(): any;
get cursor(): number;
constructor(opts: TextOptions);
}
declare function isCancel(value: unknown): value is symbol;
declare function block({ input, output, overwrite, hideCursor, }?: {
input?: (NodeJS.ReadStream & {
fd: 0;
}) | undefined;
output?: (NodeJS.WriteStream & {
fd: 1;
}) | undefined;
overwrite?: boolean | undefined;
hideCursor?: boolean | undefined;
}): () => void;
export { type ClackSettings, ConfirmPrompt, GroupMultiSelectPrompt, MultiSelectPrompt, PasswordPrompt, Prompt, SelectKeyPrompt, SelectPrompt, type ClackState as State, TextPrompt, block, isCancel, updateSettings };

View file

@ -0,0 +1,211 @@
import { Readable, Writable } from 'node:stream';
declare const actions: readonly ["up", "down", "left", "right", "space", "enter", "cancel"];
type Action = (typeof actions)[number];
interface ClackSettings {
/**
* Set custom global aliases for the default actions.
* This will not overwrite existing aliases, it will only add new ones!
*
* @param aliases - An object that maps aliases to actions
* @default { k: 'up', j: 'down', h: 'left', l: 'right', '\x03': 'cancel', 'escape': 'cancel' }
*/
aliases: Record<string, Action>;
}
declare function updateSettings(updates: ClackSettings): void;
/**
* The state of the prompt
*/
type ClackState = 'initial' | 'active' | 'cancel' | 'submit' | 'error';
/**
* Typed event emitter for clack
*/
interface ClackEvents {
initial: (value?: any) => void;
active: (value?: any) => void;
cancel: (value?: any) => void;
submit: (value?: any) => void;
error: (value?: any) => void;
cursor: (key?: Action) => void;
key: (key?: string) => void;
value: (value?: string) => void;
confirm: (value?: boolean) => void;
finalize: () => void;
}
interface PromptOptions<Self extends Prompt> {
render(this: Omit<Self, 'prompt'>): string | undefined;
placeholder?: string;
initialValue?: any;
validate?: ((value: any) => string | Error | undefined) | undefined;
input?: Readable;
output?: Writable;
debug?: boolean;
signal?: AbortSignal;
}
declare class Prompt {
protected input: Readable;
protected output: Writable;
private _abortSignal?;
private rl;
private opts;
private _render;
private _track;
private _prevFrame;
private _subscribers;
protected _cursor: number;
state: ClackState;
error: string;
value: any;
constructor(options: PromptOptions<Prompt>, trackValue?: boolean);
/**
* Unsubscribe all listeners
*/
protected unsubscribe(): void;
/**
* Set a subscriber with opts
* @param event - The event name
*/
private setSubscriber;
/**
* Subscribe to an event
* @param event - The event name
* @param cb - The callback
*/
on<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]): void;
/**
* Subscribe to an event once
* @param event - The event name
* @param cb - The callback
*/
once<T extends keyof ClackEvents>(event: T, cb: ClackEvents[T]): void;
/**
* Emit an event with data
* @param event - The event name
* @param data - The data to pass to the callback
*/
emit<T extends keyof ClackEvents>(event: T, ...data: Parameters<ClackEvents[T]>): void;
prompt(): Promise<string | symbol>;
private onKeypress;
protected close(): void;
private restoreCursor;
private render;
}
interface ConfirmOptions extends PromptOptions<ConfirmPrompt> {
active: string;
inactive: string;
initialValue?: boolean;
}
declare class ConfirmPrompt extends Prompt {
get cursor(): 0 | 1;
private get _value();
constructor(opts: ConfirmOptions);
}
interface GroupMultiSelectOptions<T extends {
value: any;
}> extends PromptOptions<GroupMultiSelectPrompt<T>> {
options: Record<string, T[]>;
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
selectableGroups?: boolean;
}
declare class GroupMultiSelectPrompt<T extends {
value: any;
}> extends Prompt {
#private;
options: (T & {
group: string | boolean;
})[];
cursor: number;
getGroupItems(group: string): T[];
isGroupSelected(group: string): boolean;
private toggleValue;
constructor(opts: GroupMultiSelectOptions<T>);
}
interface MultiSelectOptions<T extends {
value: any;
}> extends PromptOptions<MultiSelectPrompt<T>> {
options: T[];
initialValues?: T['value'][];
required?: boolean;
cursorAt?: T['value'];
}
declare class MultiSelectPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
private get _value();
private toggleAll;
private toggleValue;
constructor(opts: MultiSelectOptions<T>);
}
interface PasswordOptions extends PromptOptions<PasswordPrompt> {
mask?: string;
}
declare class PasswordPrompt extends Prompt {
valueWithCursor: string;
private _mask;
get cursor(): number;
get masked(): any;
constructor({ mask, ...opts }: PasswordOptions);
}
interface SelectOptions<T extends {
value: any;
}> extends PromptOptions<SelectPrompt<T>> {
options: T[];
initialValue?: T['value'];
}
declare class SelectPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
private get _value();
private changeValue;
constructor(opts: SelectOptions<T>);
}
interface SelectKeyOptions<T extends {
value: any;
}> extends PromptOptions<SelectKeyPrompt<T>> {
options: T[];
}
declare class SelectKeyPrompt<T extends {
value: any;
}> extends Prompt {
options: T[];
cursor: number;
constructor(opts: SelectKeyOptions<T>);
}
interface TextOptions extends PromptOptions<TextPrompt> {
placeholder?: string;
defaultValue?: string;
}
declare class TextPrompt extends Prompt {
get valueWithCursor(): any;
get cursor(): number;
constructor(opts: TextOptions);
}
declare function isCancel(value: unknown): value is symbol;
declare function block({ input, output, overwrite, hideCursor, }?: {
input?: (NodeJS.ReadStream & {
fd: 0;
}) | undefined;
output?: (NodeJS.WriteStream & {
fd: 1;
}) | undefined;
overwrite?: boolean | undefined;
hideCursor?: boolean | undefined;
}): () => void;
export { type ClackSettings, ConfirmPrompt, GroupMultiSelectPrompt, MultiSelectPrompt, PasswordPrompt, Prompt, SelectKeyPrompt, SelectPrompt, type ClackState as State, TextPrompt, block, isCancel, updateSettings };

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,62 @@
{
"name": "@clack/core",
"version": "0.5.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json"
},
"types": "./dist/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/bombshell-dev/clack.git",
"directory": "packages/core"
},
"bugs": {
"url": "https://github.com/bombshell-dev/clack/issues"
},
"homepage": "https://github.com/bombshell-dev/clack/tree/main/packages/core#readme",
"files": [
"dist",
"CHANGELOG.md"
],
"keywords": [
"ask",
"clack",
"cli",
"command-line",
"command",
"input",
"interact",
"interface",
"menu",
"prompt",
"prompts",
"stdin",
"ui"
],
"author": {
"name": "Nate Moore",
"email": "nate@natemoo.re",
"url": "https://twitter.com/n_moore"
},
"license": "MIT",
"dependencies": {
"picocolors": "^1.0.0",
"sisteransi": "^1.0.5"
},
"devDependencies": {
"vitest": "^1.6.0",
"wrap-ansi": "^8.1.0"
},
"scripts": {
"build": "unbuild",
"test": "vitest run"
}
}

View file

@ -0,0 +1,423 @@
# @clack/prompts
## 0.11.0
### Minor Changes
- 07ca32d: Reverted a change where placeholders were being set as values on return.
### Patch Changes
- Updated dependencies [07ca32d]
- @clack/core@0.5.0
## 0.10.1
### Patch Changes
- 11a5dc1: Fixes multiselect only shows hints on the first item in the options list. Now correctly shows hints for all selected options with hint property.
- 30aa7ed: Adds a new `selectableGroups` boolean to the group multi-select prompt. Using `selectableGroups: false` will disable the ability to select a top-level group, but still allow every child to be selected individually.
- Updated dependencies [30aa7ed]
- Updated dependencies [5dfce8a]
- Updated dependencies [f574297]
- @clack/core@0.4.2
## 0.10.0
### Minor Changes
- 613179d: Adds a new `indicator` option to `spinner`, which supports the original `"dots"` loading animation or a new `"timer"` loading animation.
```ts
import * as p from "@clack/prompts";
const spin = p.spinner({ indicator: "timer" });
spin.start("Loading");
await sleep(3000);
spin.stop("Loaded");
```
- a38b2bc: Adds `stream` API which provides the same methods as `log`, but for iterable (even async) message streams. This is particularly useful for AI responses which are dynamically generated by LLMs.
```ts
import * as p from "@clack/prompts";
await p.stream.step(
(async function* () {
yield* generateLLMResponse(question);
})()
);
```
## 0.9.1
### Patch Changes
- 8093f3c: Adds `Error` support to the `validate` function
- 98925e3: Exports the `Option` type and improves JSDocannotations
- 1904e57: Replace custom utility for stripping ANSI control sequences with Node's built-in [`stripVTControlCharacters`](https://nodejs.org/docs/latest/api/util.html#utilstripvtcontrolcharactersstr) utility.
- Updated dependencies [8093f3c]
- Updated dependencies [e5ba09a]
- Updated dependencies [8cba8e3]
- @clack/core@0.4.1
## 0.9.0
### Minor Changes
- a83d2f8: Adds a new `updateSettings()` function to support new global keybindings.
`updateSettings()` accepts an `aliases` object that maps custom keys to an action (`up | down | left | right | space | enter | cancel`).
```ts
import { updateSettings } from "@clack/prompts";
// Support custom keybindings
updateSettings({
aliases: {
w: "up",
a: "left",
s: "down",
d: "right",
},
});
```
> [!WARNING]
> In order to enforce consistent, user-friendly defaults across the ecosystem, `updateSettings` does not support disabling Clack's default keybindings.
- 801246b: Adds a new `signal` option to support programmatic prompt cancellation with an [abort controller](https://kettanaito.com/blog/dont-sleep-on-abort-controller).
One example use case is automatically cancelling a prompt after a timeout.
```ts
const shouldContinue = await confirm({
message: "This message will self destruct in 5 seconds",
signal: AbortSignal.timeout(5000),
});
```
Another use case is racing a long running task with a manual prompt.
```ts
const abortController = new AbortController();
const projectType = await Promise.race([
detectProjectType({
signal: abortController.signal,
}),
select({
message: "Pick a project type.",
options: [
{ value: "ts", label: "TypeScript" },
{ value: "js", label: "JavaScript" },
{ value: "coffee", label: "CoffeeScript", hint: "oh no" },
],
signal: abortController.signal,
}),
]);
abortController.abort();
```
- a83d2f8: Updates default keybindings to support Vim motion shortcuts and map the `escape` key to cancel (`ctrl+c`).
| alias | action |
| ----- | ------ |
| `k` | up |
| `l` | right |
| `j` | down |
| `h` | left |
| `esc` | cancel |
### Patch Changes
- f9f139d: Adapts `spinner` output for static CI environments
- Updated dependencies [a83d2f8]
- Updated dependencies [801246b]
- Updated dependencies [a83d2f8]
- Updated dependencies [51e12bc]
- @clack/core@0.4.0
## 0.8.2
### Patch Changes
- Updated dependencies [4845f4f]
- Updated dependencies [d7b2fb9]
- @clack/core@0.3.5
## 0.8.1
### Patch Changes
- 360afeb: feat: adaptative max items
## 0.8.0
### Minor Changes
- 9acccde: Add tasks function for executing tasks in spinners
### Patch Changes
- b5c6b9b: Feat multiselect maxItems option
- 50ed94a: fix: clear `spinner` hooks on `spinner.stop`
- Updated dependencies [a04e418]
- Updated dependencies [4f6fcf5]
- @clack/core@0.3.4
## 0.7.0
### Minor Changes
- b27a701: add maxItems option to select prompt
- 89371be: added a new method called `spinner.message(msg: string)`
### Patch Changes
- 52183c4: Fix `spinner` conflict with terminal on error between `spinner.start()` and `spinner.stop()`
- ab51d29: Fixes cases where the note title length was miscalculated due to ansi characters
- Updated dependencies [cd79076]
- @clack/core@0.3.3
## 0.6.3
### Patch Changes
- c96eda5: Enable hard line-wrapping behavior for long words without spaces
- Updated dependencies [c96eda5]
- @clack/core@0.3.2
## 0.6.2
### Patch Changes
- 58a1df1: Fix line duplication bug by automatically wrapping prompts to `process.stdout.columns`
- Updated dependencies [58a1df1]
- @clack/core@0.3.1
## 0.6.1
### Patch Changes
- ca08fb6: Support complex value types for `select`, `multiselect` and `groupMultiselect`.
## 0.6.0
### Minor Changes
- 8a4a12f: add `groupMultiselect` prompt
- 165a1b3: Add `log` APIs. Supports `log.info`, `log.success`, `log.warn`, and `log.error`. For low-level control, `log.message` is also exposed.
### Patch Changes
- Updated dependencies [8a4a12f]
- Updated dependencies [8a4a12f]
- @clack/core@0.3.0
## 0.5.1
### Patch Changes
- cc11917: Update default `password` mask
- Updated dependencies [ec812b6]
- @clack/core@0.2.1
## 0.5.0
### Minor Changes
- d74dd05: Adds a `selectKey` prompt type
- 54c1bc3: **Breaking Change** `multiselect` has renamed `initialValue` to `initialValues`
### Patch Changes
- Updated dependencies [d74dd05]
- Updated dependencies [54c1bc3]
- @clack/core@0.2.0
## 0.4.5
### Patch Changes
- 1251132: Multiselect: return `Value[]` instead of `Option[]`.
- 8994382: Add a password prompt to `@clack/prompts`
- Updated dependencies [1251132]
- Updated dependencies [8994382]
- @clack/core@0.1.9
## 0.4.4
### Patch Changes
- d96071c: Don't mutate `initialValue` in `multiselect`, fix parameter type for `validate()`.
Credits to @banjo for the bug report and initial PR!
- Updated dependencies [d96071c]
- @clack/core@0.1.8
## 0.4.3
### Patch Changes
- 83d890e: Fix text cancel display bug
## 0.4.2
### Patch Changes
- Update README
## 0.4.1
### Patch Changes
- 7fb5375: Adds a new `defaultValue` option to the text prompt, removes automatic usage of the placeholder value.
- Updated dependencies [7fb5375]
- @clack/core@0.1.6
## 0.4.0
### Minor Changes
- 61b88b6: Add `group` construct to group many prompts together
### Patch Changes
- de1314e: Support `required` option for multi-select
- Updated dependencies [de1314e]
- @clack/core@0.1.5
## 0.3.0
### Minor Changes
- 493c592: Improve types for select/multiselect prompts. Numbers and booleans are now supported as the `value` option.
- 15558e3: Improved Windows/non-unicode support
### Patch Changes
- ca77da1: Fix multiselect initial value logic
- Updated dependencies [ca77da1]
- Updated dependencies [8aed606]
- @clack/core@0.1.4
## 0.2.2
### Patch Changes
- 94b24d9: Fix CJS `ansi-regex` interop
## 0.2.1
### Patch Changes
- a99c458: Support `initialValue` option for text prompt
- Updated dependencies [a99c458]
- @clack/core@0.1.3
## 0.2.0
### Minor Changes
- Improved type safety
- b1341d6: Updated styles, new note component
### Patch Changes
- Updated dependencies [7dcad8f]
- Updated dependencies [2242f13]
- Updated dependencies [b1341d6]
- @clack/core@0.1.2
## 0.1.1
### Patch Changes
- fa09bf5: Use circle for radio, square for checkbox
- Updated dependencies [4be7dbf]
- Updated dependencies [b480679]
- @clack/core@0.1.1
## 0.1.0
### Minor Changes
- 7015ec9: Create new prompt: multi-select
### Patch Changes
- Updated dependencies [7015ec9]
- @clack/core@0.1.0
## 0.0.10
### Patch Changes
- e0b49e5: Update spinner so it actually spins
## 0.0.9
### Patch Changes
- Update README
## 0.0.8
### Patch Changes
- Updated dependencies [9d371c3]
- @clack/core@0.0.12
## 0.0.7
### Patch Changes
- Update README
## 0.0.6
### Patch Changes
- d20ef2a: Update keywords, URLs
- Updated dependencies [441d5b7]
- Updated dependencies [d20ef2a]
- Updated dependencies [fe13c2f]
- @clack/core@0.0.11
## 0.0.5
### Patch Changes
- Update README
## 0.0.4
### Patch Changes
- 80404ab: Update README
## 0.0.3
### Patch Changes
- a0cb382: Add `main` entrypoint
- Updated dependencies [a0cb382]
- @clack/core@0.0.10
## 0.0.2
### Patch Changes
- Updated dependencies
- @clack/core@0.0.9
## 0.0.1
### Patch Changes
- a4b5e13: Initial release
- Updated dependencies [a4b5e13]
- @clack/core@0.0.8

View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) Nate Moore
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.

View file

@ -0,0 +1,207 @@
# `@clack/prompts`
Effortlessly build beautiful command-line apps 🪄 [Try the demo](https://stackblitz.com/edit/clack-prompts?file=index.js)
![clack-prompt](https://github.com/bombshell-dev/clack/blob/main/.github/assets/clack-demo.gif)
---
`@clack/prompts` is an opinionated, pre-styled wrapper around [`@clack/core`](https://www.npmjs.com/package/@clack/core).
- 🤏 80% smaller than other options
- 💎 Beautiful, minimal UI
- ✅ Simple API
- 🧱 Comes with `text`, `confirm`, `select`, `multiselect`, and `spinner` components
## Basics
### Setup
The `intro` and `outro` functions will print a message to begin or end a prompt session, respectively.
```js
import { intro, outro } from '@clack/prompts';
intro(`create-my-app`);
// Do stuff
outro(`You're all set!`);
```
### Cancellation
The `isCancel` function is a guard that detects when a user cancels a question with `CTRL + C`. You should handle this situation for each prompt, optionally providing a nice cancellation message with the `cancel` utility.
```js
import { isCancel, cancel, text } from '@clack/prompts';
const value = await text({
message: 'What is the meaning of life?',
});
if (isCancel(value)) {
cancel('Operation cancelled.');
process.exit(0);
}
```
## Components
### Text
The text component accepts a single line of text.
```js
import { text } from '@clack/prompts';
const meaning = await text({
message: 'What is the meaning of life?',
placeholder: 'Not sure',
initialValue: '42',
validate(value) {
if (value.length === 0) return `Value is required!`;
},
});
```
### Confirm
The confirm component accepts a yes or no answer. The result is a boolean value of `true` or `false`.
```js
import { confirm } from '@clack/prompts';
const shouldContinue = await confirm({
message: 'Do you want to continue?',
});
```
### Select
The select component allows a user to choose one value from a list of options. The result is the `value` prop of a given option.
```js
import { select } from '@clack/prompts';
const projectType = await select({
message: 'Pick a project type.',
options: [
{ value: 'ts', label: 'TypeScript' },
{ value: 'js', label: 'JavaScript' },
{ value: 'coffee', label: 'CoffeeScript', hint: 'oh no' },
],
});
```
### Multi-Select
The `multiselect` component allows a user to choose many values from a list of options. The result is an array with all selected `value` props.
```js
import { multiselect } from '@clack/prompts';
const additionalTools = await multiselect({
message: 'Select additional tools.',
options: [
{ value: 'eslint', label: 'ESLint', hint: 'recommended' },
{ value: 'prettier', label: 'Prettier' },
{ value: 'gh-action', label: 'GitHub Action' },
],
required: false,
});
```
### Spinner
The spinner component surfaces a pending action, such as a long-running download or dependency installation.
```js
import { spinner } from '@clack/prompts';
const s = spinner();
s.start('Installing via npm');
// Do installation here
s.stop('Installed via npm');
```
## Utilities
### Grouping
Grouping prompts together is a great way to keep your code organized. This accepts a JSON object with a name that can be used to reference the group later. The second argument is an optional but has a `onCancel` callback that will be called if the user cancels one of the prompts in the group.
```js
import * as p from '@clack/prompts';
const group = await p.group(
{
name: () => p.text({ message: 'What is your name?' }),
age: () => p.text({ message: 'What is your age?' }),
color: ({ results }) =>
p.multiselect({
message: `What is your favorite color ${results.name}?`,
options: [
{ value: 'red', label: 'Red' },
{ value: 'green', label: 'Green' },
{ value: 'blue', label: 'Blue' },
],
}),
},
{
// On Cancel callback that wraps the group
// So if the user cancels one of the prompts in the group this function will be called
onCancel: ({ results }) => {
p.cancel('Operation cancelled.');
process.exit(0);
},
}
);
console.log(group.name, group.age, group.color);
```
### Tasks
Execute multiple tasks in spinners.
```js
await p.tasks([
{
title: 'Installing via npm',
task: async (message) => {
// Do installation here
return 'Installed via npm';
},
},
]);
```
### Logs
```js
import { log } from '@clack/prompts';
log.info('Info!');
log.success('Success!');
log.step('Step!');
log.warn('Warn!');
log.error('Error!');
log.message('Hello, World', { symbol: color.cyan('~') });
```
### Stream
When interacting with dynamic LLMs or other streaming message providers, use the `stream` APIs to log messages from an iterable, even an async one.
```js
import { stream } from '@clack/prompts';
stream.info((function *() { yield 'Info!'; })());
stream.success((function *() { yield 'Success!'; })());
stream.step((function *() { yield 'Step!'; })());
stream.warn((function *() { yield 'Warn!'; })());
stream.error((function *() { yield 'Error!'; })());
stream.message((function *() { yield 'Hello'; yield ", World" })(), { symbol: color.cyan('~') });
```
![clack-log-prompts](https://github.com/bombshell-dev/clack/blob/main/.github/assets/clack-logs.png)

View file

@ -0,0 +1,87 @@
"use strict";const node_util=require("node:util"),core=require("@clack/core"),process$1=require("node:process"),e=require("picocolors"),sisteransi=require("sisteransi");function _interopDefaultCompat(t){return t&&typeof t=="object"&&"default"in t?t.default:t}const process__default=_interopDefaultCompat(process$1),e__default=_interopDefaultCompat(e);function isUnicodeSupported(){return process__default.platform!=="win32"?process__default.env.TERM!=="linux":!!process__default.env.CI||!!process__default.env.WT_SESSION||!!process__default.env.TERMINUS_SUBLIME||process__default.env.ConEmuTask==="{cmd::Cmder}"||process__default.env.TERM_PROGRAM==="Terminus-Sublime"||process__default.env.TERM_PROGRAM==="vscode"||process__default.env.TERM==="xterm-256color"||process__default.env.TERM==="alacritty"||process__default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}const P=isUnicodeSupported(),u=(t,o)=>P?t:o,ie=u("\u25C6","*"),G=u("\u25A0","x"),L=u("\u25B2","x"),S=u("\u25C7","o"),ae=u("\u250C","T"),a=u("\u2502","|"),g=u("\u2514","\u2014"),_=u("\u25CF",">"),A=u("\u25CB"," "),C=u("\u25FB","[\u2022]"),V=u("\u25FC","[+]"),N=u("\u25FB","[ ]"),oe=u("\u25AA","\u2022"),j=u("\u2500","-"),le=u("\u256E","+"),ce=u("\u251C","+"),ue=u("\u256F","+"),B=u("\u25CF","\u2022"),W=u("\u25C6","*"),H=u("\u25B2","!"),q=u("\u25A0","x"),b=t=>{switch(t){case"initial":case"active":return e__default.cyan(ie);case"cancel":return e__default.red(G);case"error":return e__default.yellow(L);case"submit":return e__default.green(S)}},E=t=>{const{cursor:o,options:s,style:i}=t,r=t.maxItems??Number.POSITIVE_INFINITY,c=Math.max(process.stdout.rows-4,0),n=Math.min(c,Math.max(r,5));let l=0;o>=l+n-3?l=Math.max(Math.min(o-n+3,s.length-n),0):o<l+2&&(l=Math.max(o-2,0));const $=n<s.length&&l>0,h=n<s.length&&l+n<s.length;return s.slice(l,l+n).map((m,y,w)=>{const x=y===0&&$,M=y===w.length-1&&h;return x||M?e__default.dim("..."):i(m,y+l===o)})},text=t=>new core.TextPrompt({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,render(){const o=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`,s=t.placeholder?e__default.inverse(t.placeholder[0])+e__default.dim(t.placeholder.slice(1)):e__default.inverse(e__default.hidden("_")),i=this.value?this.valueWithCursor:s;switch(this.state){case"error":return`${o.trim()}
${e__default.yellow(a)} ${i}
${e__default.yellow(g)} ${e__default.yellow(this.error)}
`;case"submit":return`${o}${e__default.gray(a)} ${e__default.dim(this.value||t.placeholder)}`;case"cancel":return`${o}${e__default.gray(a)} ${e__default.strikethrough(e__default.dim(this.value??""))}${this.value?.trim()?`
${e__default.gray(a)}`:""}`;default:return`${o}${e__default.cyan(a)} ${i}
${e__default.cyan(g)}
`}}}).prompt(),password=t=>new core.PasswordPrompt({validate:t.validate,mask:t.mask??oe,render(){const o=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`,s=this.valueWithCursor,i=this.masked;switch(this.state){case"error":return`${o.trim()}
${e__default.yellow(a)} ${i}
${e__default.yellow(g)} ${e__default.yellow(this.error)}
`;case"submit":return`${o}${e__default.gray(a)} ${e__default.dim(i)}`;case"cancel":return`${o}${e__default.gray(a)} ${e__default.strikethrough(e__default.dim(i??""))}${i?`
${e__default.gray(a)}`:""}`;default:return`${o}${e__default.cyan(a)} ${s}
${e__default.cyan(g)}
`}}}).prompt(),confirm=t=>{const o=t.active??"Yes",s=t.inactive??"No";return new core.ConfirmPrompt({active:o,inactive:s,initialValue:t.initialValue??!0,render(){const i=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`,r=this.value?o:s;switch(this.state){case"submit":return`${i}${e__default.gray(a)} ${e__default.dim(r)}`;case"cancel":return`${i}${e__default.gray(a)} ${e__default.strikethrough(e__default.dim(r))}
${e__default.gray(a)}`;default:return`${i}${e__default.cyan(a)} ${this.value?`${e__default.green(_)} ${o}`:`${e__default.dim(A)} ${e__default.dim(o)}`} ${e__default.dim("/")} ${this.value?`${e__default.dim(A)} ${e__default.dim(s)}`:`${e__default.green(_)} ${s}`}
${e__default.cyan(g)}
`}}}).prompt()},select=t=>{const o=(s,i)=>{const r=s.label??String(s.value);switch(i){case"selected":return`${e__default.dim(r)}`;case"active":return`${e__default.green(_)} ${r} ${s.hint?e__default.dim(`(${s.hint})`):""}`;case"cancelled":return`${e__default.strikethrough(e__default.dim(r))}`;default:return`${e__default.dim(A)} ${e__default.dim(r)}`}};return new core.SelectPrompt({options:t.options,initialValue:t.initialValue,render(){const s=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`;switch(this.state){case"submit":return`${s}${e__default.gray(a)} ${o(this.options[this.cursor],"selected")}`;case"cancel":return`${s}${e__default.gray(a)} ${o(this.options[this.cursor],"cancelled")}
${e__default.gray(a)}`;default:return`${s}${e__default.cyan(a)} ${E({cursor:this.cursor,options:this.options,maxItems:t.maxItems,style:(i,r)=>o(i,r?"active":"inactive")}).join(`
${e__default.cyan(a)} `)}
${e__default.cyan(g)}
`}}}).prompt()},selectKey=t=>{const o=(s,i="inactive")=>{const r=s.label??String(s.value);return i==="selected"?`${e__default.dim(r)}`:i==="cancelled"?`${e__default.strikethrough(e__default.dim(r))}`:i==="active"?`${e__default.bgCyan(e__default.gray(` ${s.value} `))} ${r} ${s.hint?e__default.dim(`(${s.hint})`):""}`:`${e__default.gray(e__default.bgWhite(e__default.inverse(` ${s.value} `)))} ${r} ${s.hint?e__default.dim(`(${s.hint})`):""}`};return new core.SelectKeyPrompt({options:t.options,initialValue:t.initialValue,render(){const s=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`;switch(this.state){case"submit":return`${s}${e__default.gray(a)} ${o(this.options.find(i=>i.value===this.value)??t.options[0],"selected")}`;case"cancel":return`${s}${e__default.gray(a)} ${o(this.options[0],"cancelled")}
${e__default.gray(a)}`;default:return`${s}${e__default.cyan(a)} ${this.options.map((i,r)=>o(i,r===this.cursor?"active":"inactive")).join(`
${e__default.cyan(a)} `)}
${e__default.cyan(g)}
`}}}).prompt()},multiselect=t=>{const o=(s,i)=>{const r=s.label??String(s.value);return i==="active"?`${e__default.cyan(C)} ${r} ${s.hint?e__default.dim(`(${s.hint})`):""}`:i==="selected"?`${e__default.green(V)} ${e__default.dim(r)} ${s.hint?e__default.dim(`(${s.hint})`):""}`:i==="cancelled"?`${e__default.strikethrough(e__default.dim(r))}`:i==="active-selected"?`${e__default.green(V)} ${r} ${s.hint?e__default.dim(`(${s.hint})`):""}`:i==="submitted"?`${e__default.dim(r)}`:`${e__default.dim(N)} ${e__default.dim(r)}`};return new core.MultiSelectPrompt({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,validate(s){if(this.required&&s.length===0)return`Please select at least one option.
${e__default.reset(e__default.dim(`Press ${e__default.gray(e__default.bgWhite(e__default.inverse(" space ")))} to select, ${e__default.gray(e__default.bgWhite(e__default.inverse(" enter ")))} to submit`))}`},render(){const s=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`,i=(r,c)=>{const n=this.value.includes(r.value);return c&&n?o(r,"active-selected"):n?o(r,"selected"):o(r,c?"active":"inactive")};switch(this.state){case"submit":return`${s}${e__default.gray(a)} ${this.options.filter(({value:r})=>this.value.includes(r)).map(r=>o(r,"submitted")).join(e__default.dim(", "))||e__default.dim("none")}`;case"cancel":{const r=this.options.filter(({value:c})=>this.value.includes(c)).map(c=>o(c,"cancelled")).join(e__default.dim(", "));return`${s}${e__default.gray(a)} ${r.trim()?`${r}
${e__default.gray(a)}`:""}`}case"error":{const r=this.error.split(`
`).map((c,n)=>n===0?`${e__default.yellow(g)} ${e__default.yellow(c)}`:` ${c}`).join(`
`);return`${s+e__default.yellow(a)} ${E({options:this.options,cursor:this.cursor,maxItems:t.maxItems,style:i}).join(`
${e__default.yellow(a)} `)}
${r}
`}default:return`${s}${e__default.cyan(a)} ${E({options:this.options,cursor:this.cursor,maxItems:t.maxItems,style:i}).join(`
${e__default.cyan(a)} `)}
${e__default.cyan(g)}
`}}}).prompt()},groupMultiselect=t=>{const{selectableGroups:o=!0}=t,s=(i,r,c=[])=>{const n=i.label??String(i.value),l=typeof i.group=="string",$=l&&(c[c.indexOf(i)+1]??{group:!0}),h=l&&$.group===!0,m=l?o?`${h?g:a} `:" ":"";if(r==="active")return`${e__default.dim(m)}${e__default.cyan(C)} ${n} ${i.hint?e__default.dim(`(${i.hint})`):""}`;if(r==="group-active")return`${m}${e__default.cyan(C)} ${e__default.dim(n)}`;if(r==="group-active-selected")return`${m}${e__default.green(V)} ${e__default.dim(n)}`;if(r==="selected"){const w=l||o?e__default.green(V):"";return`${e__default.dim(m)}${w} ${e__default.dim(n)} ${i.hint?e__default.dim(`(${i.hint})`):""}`}if(r==="cancelled")return`${e__default.strikethrough(e__default.dim(n))}`;if(r==="active-selected")return`${e__default.dim(m)}${e__default.green(V)} ${n} ${i.hint?e__default.dim(`(${i.hint})`):""}`;if(r==="submitted")return`${e__default.dim(n)}`;const y=l||o?e__default.dim(N):"";return`${e__default.dim(m)}${y} ${e__default.dim(n)}`};return new core.GroupMultiSelectPrompt({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,selectableGroups:o,validate(i){if(this.required&&i.length===0)return`Please select at least one option.
${e__default.reset(e__default.dim(`Press ${e__default.gray(e__default.bgWhite(e__default.inverse(" space ")))} to select, ${e__default.gray(e__default.bgWhite(e__default.inverse(" enter ")))} to submit`))}`},render(){const i=`${e__default.gray(a)}
${b(this.state)} ${t.message}
`;switch(this.state){case"submit":return`${i}${e__default.gray(a)} ${this.options.filter(({value:r})=>this.value.includes(r)).map(r=>s(r,"submitted")).join(e__default.dim(", "))}`;case"cancel":{const r=this.options.filter(({value:c})=>this.value.includes(c)).map(c=>s(c,"cancelled")).join(e__default.dim(", "));return`${i}${e__default.gray(a)} ${r.trim()?`${r}
${e__default.gray(a)}`:""}`}case"error":{const r=this.error.split(`
`).map((c,n)=>n===0?`${e__default.yellow(g)} ${e__default.yellow(c)}`:` ${c}`).join(`
`);return`${i}${e__default.yellow(a)} ${this.options.map((c,n,l)=>{const $=this.value.includes(c.value)||c.group===!0&&this.isGroupSelected(`${c.value}`),h=n===this.cursor;return!h&&typeof c.group=="string"&&this.options[this.cursor].value===c.group?s(c,$?"group-active-selected":"group-active",l):h&&$?s(c,"active-selected",l):$?s(c,"selected",l):s(c,h?"active":"inactive",l)}).join(`
${e__default.yellow(a)} `)}
${r}
`}default:return`${i}${e__default.cyan(a)} ${this.options.map((r,c,n)=>{const l=this.value.includes(r.value)||r.group===!0&&this.isGroupSelected(`${r.value}`),$=c===this.cursor;return!$&&typeof r.group=="string"&&this.options[this.cursor].value===r.group?s(r,l?"group-active-selected":"group-active",n):$&&l?s(r,"active-selected",n):l?s(r,"selected",n):s(r,$?"active":"inactive",n)}).join(`
${e__default.cyan(a)} `)}
${e__default.cyan(g)}
`}}}).prompt()},note=(t="",o="")=>{const s=`
${t}
`.split(`
`),i=node_util.stripVTControlCharacters(o).length,r=Math.max(s.reduce((n,l)=>{const $=node_util.stripVTControlCharacters(l);return $.length>n?$.length:n},0),i)+2,c=s.map(n=>`${e__default.gray(a)} ${e__default.dim(n)}${" ".repeat(r-node_util.stripVTControlCharacters(n).length)}${e__default.gray(a)}`).join(`
`);process.stdout.write(`${e__default.gray(a)}
${e__default.green(S)} ${e__default.reset(o)} ${e__default.gray(j.repeat(Math.max(r-i-1,1))+le)}
${c}
${e__default.gray(ce+j.repeat(r+2)+ue)}
`)},cancel=(t="")=>{process.stdout.write(`${e__default.gray(g)} ${e__default.red(t)}
`)},intro=(t="")=>{process.stdout.write(`${e__default.gray(ae)} ${t}
`)},outro=(t="")=>{process.stdout.write(`${e__default.gray(a)}
${e__default.gray(g)} ${t}
`)},log={message:(t="",{symbol:o=e__default.gray(a)}={})=>{const s=[`${e__default.gray(a)}`];if(t){const[i,...r]=t.split(`
`);s.push(`${o} ${i}`,...r.map(c=>`${e__default.gray(a)} ${c}`))}process.stdout.write(`${s.join(`
`)}
`)},info:t=>{log.message(t,{symbol:e__default.blue(B)})},success:t=>{log.message(t,{symbol:e__default.green(W)})},step:t=>{log.message(t,{symbol:e__default.green(S)})},warn:t=>{log.message(t,{symbol:e__default.yellow(H)})},warning:t=>{log.warn(t)},error:t=>{log.message(t,{symbol:e__default.red(q)})}},D=`${e__default.gray(a)} `,stream={message:async(t,{symbol:o=e__default.gray(a)}={})=>{process.stdout.write(`${e__default.gray(a)}
${o} `);let s=3;for await(let i of t){i=i.replace(/\n/g,`
${D}`),i.includes(`
`)&&(s=3+node_util.stripVTControlCharacters(i.slice(i.lastIndexOf(`
`))).length);const r=node_util.stripVTControlCharacters(i).length;s+r<process.stdout.columns?(s+=r,process.stdout.write(i)):(process.stdout.write(`
${D}${i.trimStart()}`),s=3+node_util.stripVTControlCharacters(i.trimStart()).length)}process.stdout.write(`
`)},info:t=>stream.message(t,{symbol:e__default.blue(B)}),success:t=>stream.message(t,{symbol:e__default.green(W)}),step:t=>stream.message(t,{symbol:e__default.green(S)}),warn:t=>stream.message(t,{symbol:e__default.yellow(H)}),warning:t=>stream.warn(t),error:t=>stream.message(t,{symbol:e__default.red(q)})},spinner=({indicator:t="dots"}={})=>{const o=P?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],s=P?80:120,i=process.env.CI==="true";let r,c,n=!1,l="",$,h=performance.now();const m=p=>{const d=p>1?"Something went wrong":"Canceled";n&&R(d,p)},y=()=>m(2),w=()=>m(1),x=()=>{process.on("uncaughtExceptionMonitor",y),process.on("unhandledRejection",y),process.on("SIGINT",w),process.on("SIGTERM",w),process.on("exit",m)},M=()=>{process.removeListener("uncaughtExceptionMonitor",y),process.removeListener("unhandledRejection",y),process.removeListener("SIGINT",w),process.removeListener("SIGTERM",w),process.removeListener("exit",m)},T=()=>{if($===void 0)return;i&&process.stdout.write(`
`);const p=$.split(`
`);process.stdout.write(sisteransi.cursor.move(-999,p.length-1)),process.stdout.write(sisteransi.erase.down(p.length))},I=p=>p.replace(/\.+$/,""),k=p=>{const d=(performance.now()-p)/1e3,v=Math.floor(d/60),f=Math.floor(d%60);return v>0?`[${v}m ${f}s]`:`[${f}s]`},O=(p="")=>{n=!0,r=core.block(),l=I(p),h=performance.now(),process.stdout.write(`${e__default.gray(a)}
`);let d=0,v=0;x(),c=setInterval(()=>{if(i&&l===$)return;T(),$=l;const f=e__default.magenta(o[d]);if(i)process.stdout.write(`${f} ${l}...`);else if(t==="timer")process.stdout.write(`${f} ${l} ${k(h)}`);else{const F=".".repeat(Math.floor(v)).slice(0,3);process.stdout.write(`${f} ${l}${F}`)}d=d+1<o.length?d+1:0,v=v<o.length?v+.125:0},s)},R=(p="",d=0)=>{n=!1,clearInterval(c),T();const v=d===0?e__default.green(S):d===1?e__default.red(G):e__default.red(L);l=I(p??l),t==="timer"?process.stdout.write(`${v} ${l} ${k(h)}
`):process.stdout.write(`${v} ${l}
`),M(),r()};return{start:O,stop:R,message:(p="")=>{l=I(p??l)}}},group=async(t,o)=>{const s={},i=Object.keys(t);for(const r of i){const c=t[r],n=await c({results:s})?.catch(l=>{throw l});if(typeof o?.onCancel=="function"&&core.isCancel(n)){s[r]="canceled",o.onCancel({results:s});continue}s[r]=n}return s},tasks=async t=>{for(const o of t){if(o.enabled===!1)continue;const s=spinner();s.start(o.title);const i=await o.task(s.message);s.stop(i||o.title)}};exports.isCancel=core.isCancel,exports.updateSettings=core.updateSettings,exports.cancel=cancel,exports.confirm=confirm,exports.group=group,exports.groupMultiselect=groupMultiselect,exports.intro=intro,exports.log=log,exports.multiselect=multiselect,exports.note=note,exports.outro=outro,exports.password=password,exports.select=select,exports.selectKey=selectKey,exports.spinner=spinner,exports.stream=stream,exports.tasks=tasks,exports.text=text;
//# sourceMappingURL=index.cjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,165 @@
export { ClackSettings, isCancel, updateSettings } from '@clack/core';
interface TextOptions {
message: string;
placeholder?: string;
defaultValue?: string;
initialValue?: string;
validate?: (value: string) => string | Error | undefined;
}
declare const text: (opts: TextOptions) => Promise<string | symbol>;
interface PasswordOptions {
message: string;
mask?: string;
validate?: (value: string) => string | Error | undefined;
}
declare const password: (opts: PasswordOptions) => Promise<string | symbol>;
interface ConfirmOptions {
message: string;
active?: string;
inactive?: string;
initialValue?: boolean;
}
declare const confirm: (opts: ConfirmOptions) => Promise<boolean | symbol>;
type Primitive = Readonly<string | boolean | number>;
type Option<Value> = Value extends Primitive ? {
/**
* Internal data for this option.
*/
value: Value;
/**
* The optional, user-facing text for this option.
*
* By default, the `value` is converted to a string.
*/
label?: string;
/**
* An optional hint to display to the user when
* this option might be selected.
*
* By default, no `hint` is displayed.
*/
hint?: string;
} : {
/**
* Internal data for this option.
*/
value: Value;
/**
* Required. The user-facing text for this option.
*/
label: string;
/**
* An optional hint to display to the user when
* this option might be selected.
*
* By default, no `hint` is displayed.
*/
hint?: string;
};
interface SelectOptions<Value> {
message: string;
options: Option<Value>[];
initialValue?: Value;
maxItems?: number;
}
declare const select: <Value>(opts: SelectOptions<Value>) => Promise<symbol | Value>;
declare const selectKey: <Value extends string>(opts: SelectOptions<Value>) => Promise<symbol | Value>;
interface MultiSelectOptions<Value> {
message: string;
options: Option<Value>[];
initialValues?: Value[];
maxItems?: number;
required?: boolean;
cursorAt?: Value;
}
declare const multiselect: <Value>(opts: MultiSelectOptions<Value>) => Promise<symbol | Value[]>;
interface GroupMultiSelectOptions<Value> {
message: string;
options: Record<string, Option<Value>[]>;
initialValues?: Value[];
required?: boolean;
cursorAt?: Value;
selectableGroups?: boolean;
}
declare const groupMultiselect: <Value>(opts: GroupMultiSelectOptions<Value>) => Promise<symbol | Value[]>;
declare const note: (message?: string, title?: string) => void;
declare const cancel: (message?: string) => void;
declare const intro: (title?: string) => void;
declare const outro: (message?: string) => void;
type LogMessageOptions = {
symbol?: string;
};
declare const log: {
message: (message?: string, { symbol }?: LogMessageOptions) => void;
info: (message: string) => void;
success: (message: string) => void;
step: (message: string) => void;
warn: (message: string) => void;
/** alias for `log.warn()`. */
warning: (message: string) => void;
error: (message: string) => void;
};
declare const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
success: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
step: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
warn: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
/** alias for `log.warn()`. */
warning: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
};
interface SpinnerOptions {
indicator?: 'dots' | 'timer';
}
declare const spinner: ({ indicator }?: SpinnerOptions) => {
start: (msg?: string) => void;
stop: (msg?: string, code?: number) => void;
message: (msg?: string) => void;
};
type PromptGroupAwaitedReturn<T> = {
[P in keyof T]: Exclude<Awaited<T[P]>, symbol>;
};
interface PromptGroupOptions<T> {
/**
* Control how the group can be canceled
* if one of the prompts is canceled.
*/
onCancel?: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<T>>>;
}) => void;
}
type Prettify<T> = {
[P in keyof T]: T[P];
} & {};
type PromptGroup<T> = {
[P in keyof T]: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>;
}) => undefined | Promise<T[P] | undefined>;
};
/**
* Define a group of prompts to be displayed
* and return a results of objects within the group
*/
declare const group: <T>(prompts: PromptGroup<T>, opts?: PromptGroupOptions<T> | undefined) => Promise<{ [P in keyof PromptGroupAwaitedReturn<T>]: PromptGroupAwaitedReturn<T>[P]; }>;
type Task = {
/**
* Task title
*/
title: string;
/**
* Task function
*/
task: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>;
/**
* If enabled === false the task will be skipped
*/
enabled?: boolean;
};
/**
* Define a group of tasks to be executed
*/
declare const tasks: (tasks: Task[]) => Promise<void>;
export { type ConfirmOptions, type GroupMultiSelectOptions, type LogMessageOptions, type MultiSelectOptions, type Option, type PasswordOptions, type PromptGroup, type PromptGroupAwaitedReturn, type PromptGroupOptions, type SelectOptions, type SpinnerOptions, type Task, type TextOptions, cancel, confirm, group, groupMultiselect, intro, log, multiselect, note, outro, password, select, selectKey, spinner, stream, tasks, text };

View file

@ -0,0 +1,165 @@
export { ClackSettings, isCancel, updateSettings } from '@clack/core';
interface TextOptions {
message: string;
placeholder?: string;
defaultValue?: string;
initialValue?: string;
validate?: (value: string) => string | Error | undefined;
}
declare const text: (opts: TextOptions) => Promise<string | symbol>;
interface PasswordOptions {
message: string;
mask?: string;
validate?: (value: string) => string | Error | undefined;
}
declare const password: (opts: PasswordOptions) => Promise<string | symbol>;
interface ConfirmOptions {
message: string;
active?: string;
inactive?: string;
initialValue?: boolean;
}
declare const confirm: (opts: ConfirmOptions) => Promise<boolean | symbol>;
type Primitive = Readonly<string | boolean | number>;
type Option<Value> = Value extends Primitive ? {
/**
* Internal data for this option.
*/
value: Value;
/**
* The optional, user-facing text for this option.
*
* By default, the `value` is converted to a string.
*/
label?: string;
/**
* An optional hint to display to the user when
* this option might be selected.
*
* By default, no `hint` is displayed.
*/
hint?: string;
} : {
/**
* Internal data for this option.
*/
value: Value;
/**
* Required. The user-facing text for this option.
*/
label: string;
/**
* An optional hint to display to the user when
* this option might be selected.
*
* By default, no `hint` is displayed.
*/
hint?: string;
};
interface SelectOptions<Value> {
message: string;
options: Option<Value>[];
initialValue?: Value;
maxItems?: number;
}
declare const select: <Value>(opts: SelectOptions<Value>) => Promise<symbol | Value>;
declare const selectKey: <Value extends string>(opts: SelectOptions<Value>) => Promise<symbol | Value>;
interface MultiSelectOptions<Value> {
message: string;
options: Option<Value>[];
initialValues?: Value[];
maxItems?: number;
required?: boolean;
cursorAt?: Value;
}
declare const multiselect: <Value>(opts: MultiSelectOptions<Value>) => Promise<symbol | Value[]>;
interface GroupMultiSelectOptions<Value> {
message: string;
options: Record<string, Option<Value>[]>;
initialValues?: Value[];
required?: boolean;
cursorAt?: Value;
selectableGroups?: boolean;
}
declare const groupMultiselect: <Value>(opts: GroupMultiSelectOptions<Value>) => Promise<symbol | Value[]>;
declare const note: (message?: string, title?: string) => void;
declare const cancel: (message?: string) => void;
declare const intro: (title?: string) => void;
declare const outro: (message?: string) => void;
type LogMessageOptions = {
symbol?: string;
};
declare const log: {
message: (message?: string, { symbol }?: LogMessageOptions) => void;
info: (message: string) => void;
success: (message: string) => void;
step: (message: string) => void;
warn: (message: string) => void;
/** alias for `log.warn()`. */
warning: (message: string) => void;
error: (message: string) => void;
};
declare const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
success: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
step: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
warn: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
/** alias for `log.warn()`. */
warning: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
};
interface SpinnerOptions {
indicator?: 'dots' | 'timer';
}
declare const spinner: ({ indicator }?: SpinnerOptions) => {
start: (msg?: string) => void;
stop: (msg?: string, code?: number) => void;
message: (msg?: string) => void;
};
type PromptGroupAwaitedReturn<T> = {
[P in keyof T]: Exclude<Awaited<T[P]>, symbol>;
};
interface PromptGroupOptions<T> {
/**
* Control how the group can be canceled
* if one of the prompts is canceled.
*/
onCancel?: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<T>>>;
}) => void;
}
type Prettify<T> = {
[P in keyof T]: T[P];
} & {};
type PromptGroup<T> = {
[P in keyof T]: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>;
}) => undefined | Promise<T[P] | undefined>;
};
/**
* Define a group of prompts to be displayed
* and return a results of objects within the group
*/
declare const group: <T>(prompts: PromptGroup<T>, opts?: PromptGroupOptions<T> | undefined) => Promise<{ [P in keyof PromptGroupAwaitedReturn<T>]: PromptGroupAwaitedReturn<T>[P]; }>;
type Task = {
/**
* Task title
*/
title: string;
/**
* Task function
*/
task: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>;
/**
* If enabled === false the task will be skipped
*/
enabled?: boolean;
};
/**
* Define a group of tasks to be executed
*/
declare const tasks: (tasks: Task[]) => Promise<void>;
export { type ConfirmOptions, type GroupMultiSelectOptions, type LogMessageOptions, type MultiSelectOptions, type Option, type PasswordOptions, type PromptGroup, type PromptGroupAwaitedReturn, type PromptGroupOptions, type SelectOptions, type SpinnerOptions, type Task, type TextOptions, cancel, confirm, group, groupMultiselect, intro, log, multiselect, note, outro, password, select, selectKey, spinner, stream, tasks, text };

View file

@ -0,0 +1,165 @@
export { ClackSettings, isCancel, updateSettings } from '@clack/core';
interface TextOptions {
message: string;
placeholder?: string;
defaultValue?: string;
initialValue?: string;
validate?: (value: string) => string | Error | undefined;
}
declare const text: (opts: TextOptions) => Promise<string | symbol>;
interface PasswordOptions {
message: string;
mask?: string;
validate?: (value: string) => string | Error | undefined;
}
declare const password: (opts: PasswordOptions) => Promise<string | symbol>;
interface ConfirmOptions {
message: string;
active?: string;
inactive?: string;
initialValue?: boolean;
}
declare const confirm: (opts: ConfirmOptions) => Promise<boolean | symbol>;
type Primitive = Readonly<string | boolean | number>;
type Option<Value> = Value extends Primitive ? {
/**
* Internal data for this option.
*/
value: Value;
/**
* The optional, user-facing text for this option.
*
* By default, the `value` is converted to a string.
*/
label?: string;
/**
* An optional hint to display to the user when
* this option might be selected.
*
* By default, no `hint` is displayed.
*/
hint?: string;
} : {
/**
* Internal data for this option.
*/
value: Value;
/**
* Required. The user-facing text for this option.
*/
label: string;
/**
* An optional hint to display to the user when
* this option might be selected.
*
* By default, no `hint` is displayed.
*/
hint?: string;
};
interface SelectOptions<Value> {
message: string;
options: Option<Value>[];
initialValue?: Value;
maxItems?: number;
}
declare const select: <Value>(opts: SelectOptions<Value>) => Promise<symbol | Value>;
declare const selectKey: <Value extends string>(opts: SelectOptions<Value>) => Promise<symbol | Value>;
interface MultiSelectOptions<Value> {
message: string;
options: Option<Value>[];
initialValues?: Value[];
maxItems?: number;
required?: boolean;
cursorAt?: Value;
}
declare const multiselect: <Value>(opts: MultiSelectOptions<Value>) => Promise<symbol | Value[]>;
interface GroupMultiSelectOptions<Value> {
message: string;
options: Record<string, Option<Value>[]>;
initialValues?: Value[];
required?: boolean;
cursorAt?: Value;
selectableGroups?: boolean;
}
declare const groupMultiselect: <Value>(opts: GroupMultiSelectOptions<Value>) => Promise<symbol | Value[]>;
declare const note: (message?: string, title?: string) => void;
declare const cancel: (message?: string) => void;
declare const intro: (title?: string) => void;
declare const outro: (message?: string) => void;
type LogMessageOptions = {
symbol?: string;
};
declare const log: {
message: (message?: string, { symbol }?: LogMessageOptions) => void;
info: (message: string) => void;
success: (message: string) => void;
step: (message: string) => void;
warn: (message: string) => void;
/** alias for `log.warn()`. */
warning: (message: string) => void;
error: (message: string) => void;
};
declare const stream: {
message: (iterable: Iterable<string> | AsyncIterable<string>, { symbol }?: LogMessageOptions) => Promise<void>;
info: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
success: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
step: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
warn: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
/** alias for `log.warn()`. */
warning: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
error: (iterable: Iterable<string> | AsyncIterable<string>) => Promise<void>;
};
interface SpinnerOptions {
indicator?: 'dots' | 'timer';
}
declare const spinner: ({ indicator }?: SpinnerOptions) => {
start: (msg?: string) => void;
stop: (msg?: string, code?: number) => void;
message: (msg?: string) => void;
};
type PromptGroupAwaitedReturn<T> = {
[P in keyof T]: Exclude<Awaited<T[P]>, symbol>;
};
interface PromptGroupOptions<T> {
/**
* Control how the group can be canceled
* if one of the prompts is canceled.
*/
onCancel?: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<T>>>;
}) => void;
}
type Prettify<T> = {
[P in keyof T]: T[P];
} & {};
type PromptGroup<T> = {
[P in keyof T]: (opts: {
results: Prettify<Partial<PromptGroupAwaitedReturn<Omit<T, P>>>>;
}) => undefined | Promise<T[P] | undefined>;
};
/**
* Define a group of prompts to be displayed
* and return a results of objects within the group
*/
declare const group: <T>(prompts: PromptGroup<T>, opts?: PromptGroupOptions<T> | undefined) => Promise<{ [P in keyof PromptGroupAwaitedReturn<T>]: PromptGroupAwaitedReturn<T>[P]; }>;
type Task = {
/**
* Task title
*/
title: string;
/**
* Task function
*/
task: (message: (string: string) => void) => string | Promise<string> | void | Promise<void>;
/**
* If enabled === false the task will be skipped
*/
enabled?: boolean;
};
/**
* Define a group of tasks to be executed
*/
declare const tasks: (tasks: Task[]) => Promise<void>;
export { type ConfirmOptions, type GroupMultiSelectOptions, type LogMessageOptions, type MultiSelectOptions, type Option, type PasswordOptions, type PromptGroup, type PromptGroupAwaitedReturn, type PromptGroupOptions, type SelectOptions, type SpinnerOptions, type Task, type TextOptions, cancel, confirm, group, groupMultiselect, intro, log, multiselect, note, outro, password, select, selectKey, spinner, stream, tasks, text };

View file

@ -0,0 +1,87 @@
import{stripVTControlCharacters as S}from"node:util";import{TextPrompt as Q,PasswordPrompt as X,ConfirmPrompt as Z,SelectPrompt as ee,SelectKeyPrompt as te,MultiSelectPrompt as re,GroupMultiSelectPrompt as se,isCancel as ie,block as ne}from"@clack/core";export{isCancel,updateSettings}from"@clack/core";import y from"node:process";import e from"picocolors";import{cursor as oe,erase as ae}from"sisteransi";function ce(){return y.platform!=="win32"?y.env.TERM!=="linux":!!y.env.CI||!!y.env.WT_SESSION||!!y.env.TERMINUS_SUBLIME||y.env.ConEmuTask==="{cmd::Cmder}"||y.env.TERM_PROGRAM==="Terminus-Sublime"||y.env.TERM_PROGRAM==="vscode"||y.env.TERM==="xterm-256color"||y.env.TERM==="alacritty"||y.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}const V=ce(),u=(t,n)=>V?t:n,le=u("\u25C6","*"),L=u("\u25A0","x"),W=u("\u25B2","x"),C=u("\u25C7","o"),ue=u("\u250C","T"),o=u("\u2502","|"),d=u("\u2514","\u2014"),k=u("\u25CF",">"),P=u("\u25CB"," "),A=u("\u25FB","[\u2022]"),T=u("\u25FC","[+]"),F=u("\u25FB","[ ]"),$e=u("\u25AA","\u2022"),_=u("\u2500","-"),me=u("\u256E","+"),de=u("\u251C","+"),pe=u("\u256F","+"),q=u("\u25CF","\u2022"),D=u("\u25C6","*"),U=u("\u25B2","!"),K=u("\u25A0","x"),b=t=>{switch(t){case"initial":case"active":return e.cyan(le);case"cancel":return e.red(L);case"error":return e.yellow(W);case"submit":return e.green(C)}},G=t=>{const{cursor:n,options:r,style:i}=t,s=t.maxItems??Number.POSITIVE_INFINITY,c=Math.max(process.stdout.rows-4,0),a=Math.min(c,Math.max(s,5));let l=0;n>=l+a-3?l=Math.max(Math.min(n-a+3,r.length-a),0):n<l+2&&(l=Math.max(n-2,0));const $=a<r.length&&l>0,g=a<r.length&&l+a<r.length;return r.slice(l,l+a).map((p,v,f)=>{const j=v===0&&$,E=v===f.length-1&&g;return j||E?e.dim("..."):i(p,v+l===n)})},he=t=>new Q({validate:t.validate,placeholder:t.placeholder,defaultValue:t.defaultValue,initialValue:t.initialValue,render(){const n=`${e.gray(o)}
${b(this.state)} ${t.message}
`,r=t.placeholder?e.inverse(t.placeholder[0])+e.dim(t.placeholder.slice(1)):e.inverse(e.hidden("_")),i=this.value?this.valueWithCursor:r;switch(this.state){case"error":return`${n.trim()}
${e.yellow(o)} ${i}
${e.yellow(d)} ${e.yellow(this.error)}
`;case"submit":return`${n}${e.gray(o)} ${e.dim(this.value||t.placeholder)}`;case"cancel":return`${n}${e.gray(o)} ${e.strikethrough(e.dim(this.value??""))}${this.value?.trim()?`
${e.gray(o)}`:""}`;default:return`${n}${e.cyan(o)} ${i}
${e.cyan(d)}
`}}}).prompt(),ge=t=>new X({validate:t.validate,mask:t.mask??$e,render(){const n=`${e.gray(o)}
${b(this.state)} ${t.message}
`,r=this.valueWithCursor,i=this.masked;switch(this.state){case"error":return`${n.trim()}
${e.yellow(o)} ${i}
${e.yellow(d)} ${e.yellow(this.error)}
`;case"submit":return`${n}${e.gray(o)} ${e.dim(i)}`;case"cancel":return`${n}${e.gray(o)} ${e.strikethrough(e.dim(i??""))}${i?`
${e.gray(o)}`:""}`;default:return`${n}${e.cyan(o)} ${r}
${e.cyan(d)}
`}}}).prompt(),ye=t=>{const n=t.active??"Yes",r=t.inactive??"No";return new Z({active:n,inactive:r,initialValue:t.initialValue??!0,render(){const i=`${e.gray(o)}
${b(this.state)} ${t.message}
`,s=this.value?n:r;switch(this.state){case"submit":return`${i}${e.gray(o)} ${e.dim(s)}`;case"cancel":return`${i}${e.gray(o)} ${e.strikethrough(e.dim(s))}
${e.gray(o)}`;default:return`${i}${e.cyan(o)} ${this.value?`${e.green(k)} ${n}`:`${e.dim(P)} ${e.dim(n)}`} ${e.dim("/")} ${this.value?`${e.dim(P)} ${e.dim(r)}`:`${e.green(k)} ${r}`}
${e.cyan(d)}
`}}}).prompt()},ve=t=>{const n=(r,i)=>{const s=r.label??String(r.value);switch(i){case"selected":return`${e.dim(s)}`;case"active":return`${e.green(k)} ${s} ${r.hint?e.dim(`(${r.hint})`):""}`;case"cancelled":return`${e.strikethrough(e.dim(s))}`;default:return`${e.dim(P)} ${e.dim(s)}`}};return new ee({options:t.options,initialValue:t.initialValue,render(){const r=`${e.gray(o)}
${b(this.state)} ${t.message}
`;switch(this.state){case"submit":return`${r}${e.gray(o)} ${n(this.options[this.cursor],"selected")}`;case"cancel":return`${r}${e.gray(o)} ${n(this.options[this.cursor],"cancelled")}
${e.gray(o)}`;default:return`${r}${e.cyan(o)} ${G({cursor:this.cursor,options:this.options,maxItems:t.maxItems,style:(i,s)=>n(i,s?"active":"inactive")}).join(`
${e.cyan(o)} `)}
${e.cyan(d)}
`}}}).prompt()},we=t=>{const n=(r,i="inactive")=>{const s=r.label??String(r.value);return i==="selected"?`${e.dim(s)}`:i==="cancelled"?`${e.strikethrough(e.dim(s))}`:i==="active"?`${e.bgCyan(e.gray(` ${r.value} `))} ${s} ${r.hint?e.dim(`(${r.hint})`):""}`:`${e.gray(e.bgWhite(e.inverse(` ${r.value} `)))} ${s} ${r.hint?e.dim(`(${r.hint})`):""}`};return new te({options:t.options,initialValue:t.initialValue,render(){const r=`${e.gray(o)}
${b(this.state)} ${t.message}
`;switch(this.state){case"submit":return`${r}${e.gray(o)} ${n(this.options.find(i=>i.value===this.value)??t.options[0],"selected")}`;case"cancel":return`${r}${e.gray(o)} ${n(this.options[0],"cancelled")}
${e.gray(o)}`;default:return`${r}${e.cyan(o)} ${this.options.map((i,s)=>n(i,s===this.cursor?"active":"inactive")).join(`
${e.cyan(o)} `)}
${e.cyan(d)}
`}}}).prompt()},fe=t=>{const n=(r,i)=>{const s=r.label??String(r.value);return i==="active"?`${e.cyan(A)} ${s} ${r.hint?e.dim(`(${r.hint})`):""}`:i==="selected"?`${e.green(T)} ${e.dim(s)} ${r.hint?e.dim(`(${r.hint})`):""}`:i==="cancelled"?`${e.strikethrough(e.dim(s))}`:i==="active-selected"?`${e.green(T)} ${s} ${r.hint?e.dim(`(${r.hint})`):""}`:i==="submitted"?`${e.dim(s)}`:`${e.dim(F)} ${e.dim(s)}`};return new re({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,validate(r){if(this.required&&r.length===0)return`Please select at least one option.
${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(" space ")))} to select, ${e.gray(e.bgWhite(e.inverse(" enter ")))} to submit`))}`},render(){const r=`${e.gray(o)}
${b(this.state)} ${t.message}
`,i=(s,c)=>{const a=this.value.includes(s.value);return c&&a?n(s,"active-selected"):a?n(s,"selected"):n(s,c?"active":"inactive")};switch(this.state){case"submit":return`${r}${e.gray(o)} ${this.options.filter(({value:s})=>this.value.includes(s)).map(s=>n(s,"submitted")).join(e.dim(", "))||e.dim("none")}`;case"cancel":{const s=this.options.filter(({value:c})=>this.value.includes(c)).map(c=>n(c,"cancelled")).join(e.dim(", "));return`${r}${e.gray(o)} ${s.trim()?`${s}
${e.gray(o)}`:""}`}case"error":{const s=this.error.split(`
`).map((c,a)=>a===0?`${e.yellow(d)} ${e.yellow(c)}`:` ${c}`).join(`
`);return`${r+e.yellow(o)} ${G({options:this.options,cursor:this.cursor,maxItems:t.maxItems,style:i}).join(`
${e.yellow(o)} `)}
${s}
`}default:return`${r}${e.cyan(o)} ${G({options:this.options,cursor:this.cursor,maxItems:t.maxItems,style:i}).join(`
${e.cyan(o)} `)}
${e.cyan(d)}
`}}}).prompt()},be=t=>{const{selectableGroups:n=!0}=t,r=(i,s,c=[])=>{const a=i.label??String(i.value),l=typeof i.group=="string",$=l&&(c[c.indexOf(i)+1]??{group:!0}),g=l&&$.group===!0,p=l?n?`${g?d:o} `:" ":"";if(s==="active")return`${e.dim(p)}${e.cyan(A)} ${a} ${i.hint?e.dim(`(${i.hint})`):""}`;if(s==="group-active")return`${p}${e.cyan(A)} ${e.dim(a)}`;if(s==="group-active-selected")return`${p}${e.green(T)} ${e.dim(a)}`;if(s==="selected"){const f=l||n?e.green(T):"";return`${e.dim(p)}${f} ${e.dim(a)} ${i.hint?e.dim(`(${i.hint})`):""}`}if(s==="cancelled")return`${e.strikethrough(e.dim(a))}`;if(s==="active-selected")return`${e.dim(p)}${e.green(T)} ${a} ${i.hint?e.dim(`(${i.hint})`):""}`;if(s==="submitted")return`${e.dim(a)}`;const v=l||n?e.dim(F):"";return`${e.dim(p)}${v} ${e.dim(a)}`};return new se({options:t.options,initialValues:t.initialValues,required:t.required??!0,cursorAt:t.cursorAt,selectableGroups:n,validate(i){if(this.required&&i.length===0)return`Please select at least one option.
${e.reset(e.dim(`Press ${e.gray(e.bgWhite(e.inverse(" space ")))} to select, ${e.gray(e.bgWhite(e.inverse(" enter ")))} to submit`))}`},render(){const i=`${e.gray(o)}
${b(this.state)} ${t.message}
`;switch(this.state){case"submit":return`${i}${e.gray(o)} ${this.options.filter(({value:s})=>this.value.includes(s)).map(s=>r(s,"submitted")).join(e.dim(", "))}`;case"cancel":{const s=this.options.filter(({value:c})=>this.value.includes(c)).map(c=>r(c,"cancelled")).join(e.dim(", "));return`${i}${e.gray(o)} ${s.trim()?`${s}
${e.gray(o)}`:""}`}case"error":{const s=this.error.split(`
`).map((c,a)=>a===0?`${e.yellow(d)} ${e.yellow(c)}`:` ${c}`).join(`
`);return`${i}${e.yellow(o)} ${this.options.map((c,a,l)=>{const $=this.value.includes(c.value)||c.group===!0&&this.isGroupSelected(`${c.value}`),g=a===this.cursor;return!g&&typeof c.group=="string"&&this.options[this.cursor].value===c.group?r(c,$?"group-active-selected":"group-active",l):g&&$?r(c,"active-selected",l):$?r(c,"selected",l):r(c,g?"active":"inactive",l)}).join(`
${e.yellow(o)} `)}
${s}
`}default:return`${i}${e.cyan(o)} ${this.options.map((s,c,a)=>{const l=this.value.includes(s.value)||s.group===!0&&this.isGroupSelected(`${s.value}`),$=c===this.cursor;return!$&&typeof s.group=="string"&&this.options[this.cursor].value===s.group?r(s,l?"group-active-selected":"group-active",a):$&&l?r(s,"active-selected",a):l?r(s,"selected",a):r(s,$?"active":"inactive",a)}).join(`
${e.cyan(o)} `)}
${e.cyan(d)}
`}}}).prompt()},Me=(t="",n="")=>{const r=`
${t}
`.split(`
`),i=S(n).length,s=Math.max(r.reduce((a,l)=>{const $=S(l);return $.length>a?$.length:a},0),i)+2,c=r.map(a=>`${e.gray(o)} ${e.dim(a)}${" ".repeat(s-S(a).length)}${e.gray(o)}`).join(`
`);process.stdout.write(`${e.gray(o)}
${e.green(C)} ${e.reset(n)} ${e.gray(_.repeat(Math.max(s-i-1,1))+me)}
${c}
${e.gray(de+_.repeat(s+2)+pe)}
`)},xe=(t="")=>{process.stdout.write(`${e.gray(d)} ${e.red(t)}
`)},Ie=(t="")=>{process.stdout.write(`${e.gray(ue)} ${t}
`)},Se=(t="")=>{process.stdout.write(`${e.gray(o)}
${e.gray(d)} ${t}
`)},M={message:(t="",{symbol:n=e.gray(o)}={})=>{const r=[`${e.gray(o)}`];if(t){const[i,...s]=t.split(`
`);r.push(`${n} ${i}`,...s.map(c=>`${e.gray(o)} ${c}`))}process.stdout.write(`${r.join(`
`)}
`)},info:t=>{M.message(t,{symbol:e.blue(q)})},success:t=>{M.message(t,{symbol:e.green(D)})},step:t=>{M.message(t,{symbol:e.green(C)})},warn:t=>{M.message(t,{symbol:e.yellow(U)})},warning:t=>{M.warn(t)},error:t=>{M.message(t,{symbol:e.red(K)})}},J=`${e.gray(o)} `,x={message:async(t,{symbol:n=e.gray(o)}={})=>{process.stdout.write(`${e.gray(o)}
${n} `);let r=3;for await(let i of t){i=i.replace(/\n/g,`
${J}`),i.includes(`
`)&&(r=3+S(i.slice(i.lastIndexOf(`
`))).length);const s=S(i).length;r+s<process.stdout.columns?(r+=s,process.stdout.write(i)):(process.stdout.write(`
${J}${i.trimStart()}`),r=3+S(i.trimStart()).length)}process.stdout.write(`
`)},info:t=>x.message(t,{symbol:e.blue(q)}),success:t=>x.message(t,{symbol:e.green(D)}),step:t=>x.message(t,{symbol:e.green(C)}),warn:t=>x.message(t,{symbol:e.yellow(U)}),warning:t=>x.warn(t),error:t=>x.message(t,{symbol:e.red(K)})},Y=({indicator:t="dots"}={})=>{const n=V?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],r=V?80:120,i=process.env.CI==="true";let s,c,a=!1,l="",$,g=performance.now();const p=m=>{const h=m>1?"Something went wrong":"Canceled";a&&N(h,m)},v=()=>p(2),f=()=>p(1),j=()=>{process.on("uncaughtExceptionMonitor",v),process.on("unhandledRejection",v),process.on("SIGINT",f),process.on("SIGTERM",f),process.on("exit",p)},E=()=>{process.removeListener("uncaughtExceptionMonitor",v),process.removeListener("unhandledRejection",v),process.removeListener("SIGINT",f),process.removeListener("SIGTERM",f),process.removeListener("exit",p)},B=()=>{if($===void 0)return;i&&process.stdout.write(`
`);const m=$.split(`
`);process.stdout.write(oe.move(-999,m.length-1)),process.stdout.write(ae.down(m.length))},R=m=>m.replace(/\.+$/,""),O=m=>{const h=(performance.now()-m)/1e3,w=Math.floor(h/60),I=Math.floor(h%60);return w>0?`[${w}m ${I}s]`:`[${I}s]`},H=(m="")=>{a=!0,s=ne(),l=R(m),g=performance.now(),process.stdout.write(`${e.gray(o)}
`);let h=0,w=0;j(),c=setInterval(()=>{if(i&&l===$)return;B(),$=l;const I=e.magenta(n[h]);if(i)process.stdout.write(`${I} ${l}...`);else if(t==="timer")process.stdout.write(`${I} ${l} ${O(g)}`);else{const z=".".repeat(Math.floor(w)).slice(0,3);process.stdout.write(`${I} ${l}${z}`)}h=h+1<n.length?h+1:0,w=w<n.length?w+.125:0},r)},N=(m="",h=0)=>{a=!1,clearInterval(c),B();const w=h===0?e.green(C):h===1?e.red(L):e.red(W);l=R(m??l),t==="timer"?process.stdout.write(`${w} ${l} ${O(g)}
`):process.stdout.write(`${w} ${l}
`),E(),s()};return{start:H,stop:N,message:(m="")=>{l=R(m??l)}}},Ce=async(t,n)=>{const r={},i=Object.keys(t);for(const s of i){const c=t[s],a=await c({results:r})?.catch(l=>{throw l});if(typeof n?.onCancel=="function"&&ie(a)){r[s]="canceled",n.onCancel({results:r});continue}r[s]=a}return r},Te=async t=>{for(const n of t){if(n.enabled===!1)continue;const r=Y();r.start(n.title);const i=await n.task(r.message);r.stop(i||n.title)}};export{xe as cancel,ye as confirm,Ce as group,be as groupMultiselect,Ie as intro,M as log,fe as multiselect,Me as note,Se as outro,ge as password,ve as select,we as selectKey,Y as spinner,x as stream,Te as tasks,he as text};
//# sourceMappingURL=index.mjs.map

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,61 @@
{
"name": "@clack/prompts",
"version": "0.11.0",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json"
},
"types": "./dist/index.d.ts",
"repository": {
"type": "git",
"url": "git+https://github.com/bombshell-dev/clack.git",
"directory": "packages/prompts"
},
"bugs": {
"url": "https://github.com/bombshell-dev/clack/issues"
},
"homepage": "https://github.com/bombshell-dev/clack/tree/main/packages/prompts#readme",
"files": [
"dist",
"CHANGELOG.md"
],
"author": {
"name": "Nate Moore",
"email": "nate@natemoo.re",
"url": "https://twitter.com/n_moore"
},
"license": "MIT",
"keywords": [
"ask",
"clack",
"cli",
"command-line",
"command",
"input",
"interact",
"interface",
"menu",
"prompt",
"prompts",
"stdin",
"ui"
],
"dependencies": {
"picocolors": "^1.0.0",
"sisteransi": "^1.0.5",
"@clack/core": "0.5.0"
},
"devDependencies": {
"is-unicode-supported": "^1.3.0"
},
"scripts": {
"build": "unbuild"
}
}

View file

@ -0,0 +1,72 @@
{
"name": "@nuxt/eslint-config",
"version": "1.12.1",
"description": "ESLint config for Nuxt projects",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/eslint.git",
"directory": "packages/eslint-config"
},
"license": "MIT",
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": "./dist/index.mjs",
"./flat": "./dist/flat.mjs"
},
"typesVersions": {
"*": {
"flat": [
"./dist/flat.d.ts"
],
"*": [
"./dist/*",
"./*"
]
}
},
"files": [
"dist"
],
"peerDependencies": {
"eslint": "^9.0.0",
"eslint-plugin-format": "*"
},
"peerDependenciesMeta": {
"eslint-plugin-format": {
"optional": true
}
},
"dependencies": {
"@antfu/install-pkg": "^1.1.0",
"@clack/prompts": "^0.11.0",
"@eslint/js": "^9.39.1",
"@stylistic/eslint-plugin": "^5.6.1",
"@typescript-eslint/eslint-plugin": "^8.49.0",
"@typescript-eslint/parser": "^8.49.0",
"eslint-config-flat-gitignore": "^2.1.0",
"eslint-flat-config-utils": "^2.1.4",
"eslint-merge-processors": "^2.0.0",
"eslint-plugin-import-lite": "^0.3.0",
"eslint-plugin-import-x": "^4.16.1",
"eslint-plugin-jsdoc": "^61.5.0",
"eslint-plugin-regexp": "^2.10.0",
"eslint-plugin-unicorn": "^62.0.0",
"eslint-plugin-vue": "^10.6.2",
"eslint-processor-vue-blocks": "^2.0.0",
"globals": "^16.5.0",
"local-pkg": "^1.1.2",
"pathe": "^2.0.3",
"vue-eslint-parser": "^10.2.0",
"@nuxt/eslint-plugin": "1.12.1"
},
"devDependencies": {
"eslint": "^9.39.1",
"typescript": "^5.9.3"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub"
}
}