Пример
prompts 2.4.2: interactive cli prompts with pre-injected answers
Проверенный пример — npm prompts 2.4.2: interactive cli prompts with pre-injected answers. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.
sha256:d2e4f82438ecae88bba5adb130753d1b5d60a8310cf2daf3c8116de81872ef47
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 1
- Ключи подписи, собравшие его
- 1
Заявленная среда
node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5… |
2026-08-23 |
Кейс
HOW- Цель
- interactive cli prompts with pre-injected answers
- Пакеты
- Символы
-
- prompts
- prompts.inject
- Окружение
- node 22.23.2
- Создан
- 2026-08-23T16:11:47Z
Контракт
- prompts(questions, options) prompts for user input and returns a Promise resolving to an answers object
- prompts.inject(answers) pre-injects answers for testing without interactive terminal prompts
- prompts supports sequential prompt executions and custom cancellation handling
Файлы
- PROMPT.md
- csx.json
- index.js
- package-lock.json
- package.json
- spec.json
- test/contract.cjs
Исходный код
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: interactive cli prompts with pre-injected answers
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/prompts@2.4.2
Demonstrate these symbols/APIs:
- prompts
- prompts.inject
Constraints:
- executionContext: node
Required runtime conditions:
- ecosystem: npm
- language: javascript
- moduleSystem: cjs
- packageManager: npm@10.9.8
- runtime: node@22.23.2
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:f751e2064e6238e121df7974723edc4df393f33bb069c7f0f42ed99625251eff","constraints":{"executionContext":"node"},"contract":["prompts(questions, options) prompts for user input and returns a Promise resolving to an answers object","prompts.inject(answers) pre-injects answers for testing without interactive terminal prompts","prompts supports sequential prompt executions and custom cancellation handling"],"goal":"interactive cli prompts with pre-injected answers","kind":"HOW","packages":["pkg:npm/prompts@2.4.2"],"schemaVersion":1,"symbols":["prompts","prompts.inject"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/prompts@2.4.2"],"schemaVersion":1,"subject":"pkg:npm/prompts@2.4.2","symbols":["prompts","prompts.inject"],"verifierAdapter":"node-typescript@1"}
'use strict';
const prompts = require('prompts');
/**
* Ask user for user profile details (username, age, confirmation).
* @param {Object} [options] - Options passed to prompts.
* @returns {Promise<Object>} The collected answers.
*/
async function askUserProfile(options = {}) {
const questions = [
{
type: 'text',
name: 'username',
message: 'Enter username:'
},
{
type: 'number',
name: 'age',
message: 'Enter age:'
},
{
type: 'confirm',
name: 'active',
message: 'Is account active?',
initial: true
}
];
return await prompts(questions, options);
}
/**
* Ask a single question.
* @param {Object} question - Prompt question configuration.
* @param {Object} [options] - Options passed to prompts.
* @returns {Promise<Object>} The collected answer.
*/
async function askSingle(question, options = {}) {
return await prompts(question, options);
}
/**
* Pre-inject answers for automated/headless testing.
* @param {Array<*>} answers - Injected answer values.
*/
function injectAnswers(answers) {
prompts.inject(answers);
}
module.exports = {
prompts,
askUserProfile,
askSingle,
injectAnswers
};
{
"name": "sample-prompts-inject",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-prompts-inject",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"prompts": "2.4.2"
}
},
"node_modules/kleur": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz",
"integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==",
"license": "MIT",
"engines": {
"node": ">=6"
}
},
"node_modules/prompts": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
"integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==",
"license": "MIT",
"dependencies": {
"kleur": "^3.0.3",
"sisteransi": "^1.0.5"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/sisteransi": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
"integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==",
"license": "MIT"
}
}
}
{
"name": "sample-prompts-inject",
"version": "1.0.0",
"private": true,
"description": "interactive cli prompts with pre-injected answers using prompts@2.4.2",
"main": "index.js",
"scripts": {
"test": "node test/contract.cjs"
},
"dependencies": {
"prompts": "2.4.2"
},
"license": "MIT-0"
}
{
"schemaVersion": 1,
"goal": "interactive cli prompts with pre-injected answers",
"kind": "HOW",
"packages": [
"pkg:npm/prompts@2.4.2"
],
"symbols": [
"prompts",
"prompts.inject"
],
"constraints": {
"executionContext": "node"
},
"runtimeConditions": {
"ecosystem": "npm",
"language": "javascript",
"moduleSystem": "cjs",
"packageManager": "npm@10.9.8",
"runtime": "node@22.23.2"
}
}
'use strict';
const assert = require('assert');
const prompts = require('prompts');
const { askUserProfile, askSingle, injectAnswers } = require('../index.js');
async function testPromptsInjectDirect() {
// Pre-inject responses for prompts
prompts.inject(['alice', 30, true]);
const answers = await prompts([
{ type: 'text', name: 'name', message: 'Name?' },
{ type: 'number', name: 'age', message: 'Age?' },
{ type: 'confirm', name: 'agree', message: 'Agree?' }
]);
assert.strictEqual(answers.name, 'alice', 'prompts should return injected string');
assert.strictEqual(answers.age, 30, 'prompts should return injected number');
assert.strictEqual(answers.agree, true, 'prompts should return injected boolean');
}
async function testAskUserProfileHelper() {
injectAnswers(['bob', 25, false]);
const profile = await askUserProfile();
assert.deepStrictEqual(profile, {
username: 'bob',
age: 25,
active: false
}, 'askUserProfile should return structured answers object from injected responses');
}
async function testSinglePrompt() {
injectAnswers(['developer']);
const result = await askSingle({
type: 'text',
name: 'role',
message: 'Role?'
});
assert.deepStrictEqual(result, { role: 'developer' }, 'askSingle should resolve single question with injected answer');
}
async function testSequentialInjections() {
prompts.inject(['first_answer']);
const first = await prompts({ type: 'text', name: 'val', message: 'First?' });
assert.strictEqual(first.val, 'first_answer');
prompts.inject(['second_answer']);
const second = await prompts({ type: 'text', name: 'val', message: 'Second?' });
assert.strictEqual(second.val, 'second_answer');
}
async function testCancelHandling() {
let cancelled = false;
// Injected error simulates user pressing Ctrl+C or aborting
const abortError = new Error('aborted');
prompts.inject([abortError]);
const result = await prompts(
{ type: 'text', name: 'abortedPrompt', message: 'Abort test' },
{
onCancel: () => {
cancelled = true;
return false;
}
}
);
assert.strictEqual(cancelled, true, 'onCancel handler should trigger when abort error injected');
}
async function runAll() {
await testPromptsInjectDirect();
await testAskUserProfileHelper();
await testSinglePrompt();
await testSequentialInjections();
await testCancelHandling();
console.log('All prompts contract tests passed successfully.');
}
runAll().catch((err) => {
console.error('Contract test failed:', err);
process.exit(1);
});
Исходный сидер
аноним