CodeSampleX

Пример

sprintf-js 1.1.3: sprintf

Проверенный пример — npm sprintf-js 1.1.3: sprintf. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: assert string formatting with %s…

sha256:fb16a10dc7e1ca3706d241b834cf38ba14a01dd374ee2cdf7afe0265bf99c74a

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
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-26
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Кейс

HOW
Цель
verify sprintf in pkg:npm/sprintf-js@1.1.3
Пакеты
Символы
  • sprintf
Окружение
node 22.23.2
Создан
2026-08-26T11:20:10Z

Контракт

  1. assert string formatting with %s placeholder replaces string values accurately
  2. assert integer formatting supports zero padding and explicit positive and negative signs
  3. assert floating point formatting with precision specifier formats decimal places
  4. assert hexadecimal and binary format specifiers convert integers to hex and binary representations
  5. assert named parameter substitution replaces dictionary keys in format strings
  6. assert positional argument specifiers allow argument swapping and indexing
  7. assert JSON specifier %j serializes objects to JSON strings
  8. assert vsprintf formats strings using an array of arguments

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs

Скачать артефакт с исходным кодом (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: verify sprintf in pkg:npm/sprintf-js@1.1.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/sprintf-js@1.1.3
Demonstrate these symbols/APIs:
  - sprintf
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:61bad7e92f057138d1c806fe1ed48162aabfae76b736dfe16cebb40b422c49b4","constraints":{"executionContext":"node"},"contract":["assert string formatting with %s placeholder replaces string values accurately","assert integer formatting supports zero padding and explicit positive and negative signs","assert floating point formatting with precision specifier formats decimal places","assert hexadecimal and binary format specifiers convert integers to hex and binary representations","assert named parameter substitution replaces dictionary keys in format strings","assert positional argument specifiers allow argument swapping and indexing","assert JSON specifier %j serializes objects to JSON strings","assert vsprintf formats strings using an array of arguments"],"goal":"verify sprintf in pkg:npm/sprintf-js@1.1.3","kind":"HOW","packages":["pkg:npm/sprintf-js@1.1.3"],"schemaVersion":1,"symbols":["sprintf"]},"contractCommand":["node","test/contract.mjs"],"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/sprintf-js@1.1.3"],"schemaVersion":1,"subject":"pkg:npm/sprintf-js@1.1.3","symbols":["sprintf"],"verifierAdapter":"node-typescript@1"}
index.js
const { sprintf, vsprintf } = require('sprintf-js');

function formatString(format, ...args) {
  return sprintf(format, ...args);
}

function formatWithNamedKeys(format, obj) {
  return sprintf(format, obj);
}

function formatWithPosition(format, ...args) {
  return sprintf(format, ...args);
}

function formatNumber(format, num) {
  return sprintf(format, num);
}

function formatJson(format, value) {
  return sprintf(format, value);
}

function formatArray(format, argsArray) {
  return vsprintf(format, argsArray);
}

module.exports = {
  sprintf,
  vsprintf,
  formatString,
  formatWithNamedKeys,
  formatWithPosition,
  formatNumber,
  formatJson,
  formatArray,
};
package-lock.json
{
  "name": "sample-sprintf-js",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-sprintf-js",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "sprintf-js": "1.1.3"
      }
    },
    "node_modules/sprintf-js": {
      "version": "1.1.3",
      "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
      "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==",
      "license": "BSD-3-Clause"
    }
  }
}
package.json
{
  "name": "sample-sprintf-js",
  "version": "1.0.0",
  "description": "Minimal clean-room sample verifying sprintf formatting in sprintf-js",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "sprintf-js": "1.1.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify sprintf in pkg:npm/sprintf-js@1.1.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/sprintf-js@1.1.3"
  ],
  "symbols": [
    "sprintf"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.mjs
import assert from 'node:assert';
import { sprintf, vsprintf } from 'sprintf-js';
import {
  formatString,
  formatWithNamedKeys,
  formatWithPosition,
  formatNumber,
  formatJson,
  formatArray,
} from '../index.js';

// 1. Basic string formatting with %s placeholder
const strResult = formatString('Hello, %s!', 'World');
assert.strictEqual(strResult, 'Hello, World!', 'Basic %s replacement must format properly');

// 2. Integer formatting with padding and signs
const paddedInt = formatNumber('%05d', 42);
assert.strictEqual(paddedInt, '00042', 'Integer with zero padding %05d must output 00042');
const positiveSigned = formatNumber('%+d', 100);
assert.strictEqual(positiveSigned, '+100', 'Positive integer with %+d must include plus sign');
const negativeSigned = formatNumber('%+d', -100);
assert.strictEqual(negativeSigned, '-100', 'Negative integer with %+d must include minus sign');

// 3. Floating point precision formatting with %f
const floatResult = formatNumber('%.2f', 3.141592);
assert.strictEqual(floatResult, '3.14', 'Floating point formatting %.2f must round to 2 decimals');

// 4. Hexadecimal and binary formatting with %x, %X, %b
const hexLower = formatNumber('%x', 255);
assert.strictEqual(hexLower, 'ff', 'Hexadecimal %x must output lowercase hex');
const hexUpper = formatNumber('%X', 255);
assert.strictEqual(hexUpper, 'FF', 'Hexadecimal %X must output uppercase hex');
const binaryVal = formatNumber('%b', 13);
assert.strictEqual(binaryVal, '1101', 'Binary %b must output binary string');

// 5. Named parameter substitution with %(key)s
const namedResult = formatWithNamedKeys('User %(name)s has %(count)d unread messages', {
  name: 'Alice',
  count: 5,
});
assert.strictEqual(
  namedResult,
  'User Alice has 5 unread messages',
  'Named placeholder substitution must replace named keys'
);

// 6. Positional argument indexing (%2$s %1$s)
const posResult = formatWithPosition('%2$s comes before %1$s', 'second', 'First');
assert.strictEqual(
  posResult,
  'First comes before second',
  'Positional argument indexing must swap arguments as specified'
);

// 7. JSON object formatting with %j
const jsonResult = formatJson('%j', { id: 1, active: true });
assert.strictEqual(
  jsonResult,
  '{"id":1,"active":true}',
  'JSON formatting %j must serialize object to compact JSON'
);

// 8. Array argument formatting with vsprintf
const arrayResult = formatArray('%s is %d years old', ['Bob', 30]);
assert.strictEqual(
  arrayResult,
  'Bob is 30 years old',
  'vsprintf must format string using an array of arguments'
);

console.log('All sprintf contract assertions passed.');

Исходный сидер

аноним