CodeSampleX

Пример

@vitest/pretty-format 4.1.11: format

Проверенный пример — npm @vitest/pretty-format 4.1.11: format. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:223dfb23688c906ae02ef0bbdbc48166e13d082a34ceadf06b62546cf6aeefc1

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-06

Кейс

HOW
Цель
verify @vitest/pretty-format.format in pkg:npm/%40vitest/pretty-format@4.1.11
Пакеты
Символы
  • @vitest/pretty-format.format
Окружение
node 22.23.2
Создан
2026-09-06T10:27:23Z

Контракт

  1. format serializes primitive values including strings, numbers, booleans, symbols, null, undefined, and BigInt
  2. format serializes plain objects and nested arrays with standard indentation
  3. format serializes Set and Map collections with entry representations
  4. format detects circular references and marks recursive pointers as Circular
  5. format respects callToJSON option by invoking or skipping toJSON method
  6. format respects escapeString option to escape nested double quotes
  7. format respects escapeRegex option for RegExp serialization
  8. format respects indent option to control spaces per indentation level
  9. format respects maxDepth option by truncating nested objects beyond depth limit
  10. format respects maxWidth option by truncating collection elements exceeding count
  11. format min option outputs compact single-line representation without added indentation
  12. format respects printBasicPrototype option for plain objects and arrays
  13. format respects printFunctionName option for named and anonymous functions
  14. format respects compareKeys option to customize object key sorting order
  15. format supports custom plugins implementing test and serialize hooks

Файлы

  • PROMPT.md
  • csx.json
  • index.mjs
  • 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 @vitest/pretty-format.format in pkg:npm/%40vitest/pretty-format@4.1.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/pretty-format@4.1.11
Demonstrate these symbols/APIs:
  - @vitest/pretty-format.format

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:61f5a612068622891909c92228f3ecbee2e03b51d3f9437a14e0e74dee273d65","contract":["format serializes primitive values including strings, numbers, booleans, symbols, null, undefined, and BigInt","format serializes plain objects and nested arrays with standard indentation","format serializes Set and Map collections with entry representations","format detects circular references and marks recursive pointers as Circular","format respects callToJSON option by invoking or skipping toJSON method","format respects escapeString option to escape nested double quotes","format respects escapeRegex option for RegExp serialization","format respects indent option to control spaces per indentation level","format respects maxDepth option by truncating nested objects beyond depth limit","format respects maxWidth option by truncating collection elements exceeding count","format min option outputs compact single-line representation without added indentation","format respects printBasicPrototype option for plain objects and arrays","format respects printFunctionName option for named and anonymous functions","format respects compareKeys option to customize object key sorting order","format supports custom plugins implementing test and serialize hooks"],"goal":"verify @vitest/pretty-format.format in pkg:npm/%40vitest/pretty-format@4.1.11","kind":"HOW","packages":["pkg:npm/%40vitest/pretty-format@4.1.11"],"schemaVersion":1,"symbols":["@vitest/pretty-format.format"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/pretty-format@4.1.11"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/pretty-format@4.1.11","symbols":["@vitest/pretty-format.format"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { format } from '@vitest/pretty-format';

export { format };

export function formatMinified(value) {
  return format(value, { min: true });
}

export function formatCustomIndent(value, indent) {
  return format(value, { indent });
}

export function formatWithPlugin(value, plugin) {
  return format(value, { plugins: [plugin] });
}
package-lock.json
{
  "name": "sample-vitest-pretty-format",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-pretty-format",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/pretty-format": "4.1.11"
      }
    },
    "node_modules/@vitest/pretty-format": {
      "version": "4.1.11",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
      "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^3.1.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/tinyrainbow": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
      "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-pretty-format",
  "version": "1.0.0",
  "description": "Clean-room verification sample for @vitest/pretty-format format API",
  "type": "module",
  "main": "index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@vitest/pretty-format": "4.1.11"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/pretty-format.format in pkg:npm/%40vitest/pretty-format@4.1.11",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/pretty-format@4.1.11"
  ],
  "symbols": [
    "@vitest/pretty-format.format"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { format } from '@vitest/pretty-format';
import { formatMinified, formatCustomIndent, formatWithPlugin } from '../index.mjs';

// 1. format serializes primitive values including strings, numbers, booleans, symbols, null, undefined, and BigInt
{
  assert.equal(format('hello world'), '"hello world"');
  assert.equal(format(42), '42');
  assert.equal(format(true), 'true');
  assert.equal(format(null), 'null');
  assert.equal(format(undefined), 'undefined');
  assert.equal(format(Symbol('test')), 'Symbol(test)');
  assert.equal(format(123n), '123n');
}

// 2. format serializes plain objects and nested arrays with standard indentation
{
  const obj = { a: 1, b: [2, 3] };
  const out = format(obj);
  assert.ok(out.includes('Object {'));
  assert.ok(out.includes('Array ['));
  assert.ok(out.includes('  "a": 1,'));
}

// 3. format serializes Set and Map collections with entry representations
{
  const set = new Set(['x', 'y']);
  const map = new Map([['k', 'v']]);
  assert.ok(format(set).includes('Set {'));
  assert.ok(format(map).includes('Map {'));
}

// 4. format detects circular references and marks recursive pointers as Circular
{
  const a = { name: 'cycle' };
  a.self = a;
  assert.ok(format(a).includes('[Circular]'));
}

// 5. format respects callToJSON option by invoking or skipping toJSON method
{
  const objWithToJSON = {
    toJSON() {
      return { transformed: true };
    },
    raw: 'ignored',
  };
  const withCall = format(objWithToJSON, { callToJSON: true });
  const withoutCall = format(objWithToJSON, { callToJSON: false });
  assert.ok(withCall.includes('"transformed": true'));
  assert.ok(!withCall.includes('"raw"'));
  assert.ok(withoutCall.includes('"raw": "ignored"'));
}

// 6. format respects escapeString option to escape nested double quotes
{
  const str = 'say "hello"';
  const escaped = format(str, { escapeString: true });
  const unescaped = format(str, { escapeString: false });
  assert.equal(escaped, '"say \\"hello\\""');
  assert.equal(unescaped, '"say "hello""');
}

// 7. format respects escapeRegex option for RegExp serialization
{
  const reg = /foo\/bar/;
  const escaped = format(reg, { escapeRegex: true });
  const unescaped = format(reg, { escapeRegex: false });
  assert.equal(escaped, '/foo\\\\/bar/');
  assert.equal(unescaped, '/foo\\/bar/');
}

// 8. format respects indent option to control spaces per indentation level
{
  const data = { x: 1 };
  const formatted4 = format(data, { indent: 4 });
  assert.equal(formatted4, 'Object {\n    "x": 1,\n}');
  assert.equal(formatCustomIndent(data, 4), 'Object {\n    "x": 1,\n}');
}

// 9. format respects maxDepth option by truncating nested objects beyond depth limit
{
  const nested = { a: { b: { c: 3 } } };
  const truncated = format(nested, { maxDepth: 1 });
  assert.ok(truncated.includes('"a": [Object]'));
  assert.ok(!truncated.includes('3'));
}

// 10. format respects maxWidth option by truncating collection elements exceeding count
{
  const list = [1, 2, 3, 4, 5];
  const truncated = format(list, { maxWidth: 2 });
  assert.ok(truncated.includes('1,'));
  assert.ok(truncated.includes('2,'));
  assert.ok(truncated.includes('…'));
  assert.ok(!truncated.includes('5'));
}

// 11. format min option outputs compact single-line representation without added indentation
{
  const data = { a: 1, b: 2 };
  const minified = format(data, { min: true });
  assert.equal(minified, '{"a": 1, "b": 2}');
  assert.equal(formatMinified(data), '{"a": 1, "b": 2}');
}

// 12. format respects printBasicPrototype option for plain objects and arrays
{
  const obj = { a: 1 };
  const withProto = format(obj, { printBasicPrototype: true });
  const withoutProto = format(obj, { printBasicPrototype: false });
  assert.ok(withProto.startsWith('Object {'));
  assert.ok(withoutProto.startsWith('{'));
}

// 13. format respects printFunctionName option for named and anonymous functions
{
  function namedFunc() {}
  const withName = format(namedFunc, { printFunctionName: true });
  const withoutName = format(namedFunc, { printFunctionName: false });
  assert.equal(withName, '[Function namedFunc]');
  assert.equal(withoutName, '[Function]');
}

// 14. format respects compareKeys option to customize object key sorting order
{
  const obj = { c: 3, a: 1, b: 2 };
  const desc = format(obj, {
    compareKeys: (k1, k2) => (k1 < k2 ? 1 : -1),
  });
  const lines = desc.split('\n');
  const cIndex = lines.findIndex((l) => l.includes('"c"'));
  const aIndex = lines.findIndex((l) => l.includes('"a"'));
  assert.ok(cIndex < aIndex);
}

// 15. format supports custom plugins implementing test and serialize hooks
{
  const customPlugin = {
    test: (val) => Boolean(val && val.__customType === 'Secret'),
    serialize: (val) => `<Secret: ${val.value}>`,
  };
  const data = { token: { __customType: 'Secret', value: 'redacted' } };
  const out = format(data, { plugins: [customPlugin] });
  assert.ok(out.includes('<Secret: redacted>'));
  assert.ok(formatWithPlugin(data, customPlugin).includes('<Secret: redacted>'));
}

console.log('All @vitest/pretty-format format contract assertions passed.');

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

аноним