CodeSampleX

示例

prompts 2.4.2: interactive cli prompts with pre-injected answers

已验证示例 — npm prompts 2.4.2: interactive cli prompts with pre-injected answers. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过.

sha256:d2e4f82438ecae88bba5adb130753d1b5d60a8310cf2daf3c8116de81872ef47

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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

契约

  1. prompts(questions, options) prompts for user input and returns a Promise resolving to an answers object
  2. prompts.inject(answers) pre-injects answers for testing without interactive terminal prompts
  3. 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

下载源代码构件 (tar.gz)

源代码

PROMPT.md
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.
csx.json
{"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"}
index.js
'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
};
package-lock.json
{
  "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"
    }
  }
}
package.json
{
  "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"
}
spec.json
{
  "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"
  }
}
test/contract.cjs
'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);
});

原始种子者

匿名