CodeSampleX

Exemplo

pretty-format 27.5.1: format JavaScript value to string using format function

Amostra verificada para npm pretty-format 27.5.1: format JavaScript value to string using format function. O contrato rodou em node 22 · linux alpine/x64 …

sha256:f5204f6e120246edb5176a748d643d9e579b25b24930ab05a12bdc598c57b14f

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-27

Caso

HOW
Objetivo
format JavaScript value to string using format function
Pacotes
Símbolos
  • format
  • prettyFormat
Criado
2026-08-27T22:22:19Z

Contrato

  1. format serializes primitive values including strings, numbers, booleans, symbols, 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 maxDepth option by truncating objects beyond depth limit
  6. format min option outputs compact single-line JSON-like representation
  7. format custom indent option controls spaces per indentation level
  8. format printFunctionName option controls whether function names are printed
  9. format supports custom plugins implementing test and serialize hooks
  10. format integrates with built-in ConvertAnsi plugin to convert ANSI escape sequences
  11. prettyFormat default export provides identical formatting behavior as format

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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: format JavaScript value to string using format function
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/pretty-format@27.5.1
Demonstrate these symbols/APIs:
  - format
  - prettyFormat

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:4a8a59560ce9776b65eb903941483d7fafd6a60e6692cbef492b4f3dab36c962","contract":["format serializes primitive values including strings, numbers, booleans, symbols, 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 maxDepth option by truncating objects beyond depth limit","format min option outputs compact single-line JSON-like representation","format custom indent option controls spaces per indentation level","format printFunctionName option controls whether function names are printed","format supports custom plugins implementing test and serialize hooks","format integrates with built-in ConvertAnsi plugin to convert ANSI escape sequences","prettyFormat default export provides identical formatting behavior as format"],"goal":"format JavaScript value to string using format function","kind":"HOW","packages":["pkg:npm/pretty-format@27.5.1"],"schemaVersion":1,"symbols":["format","prettyFormat"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/pretty-format@27.5.1"],"schemaVersion":1,"subject":"pkg:npm/pretty-format@27.5.1","symbols":["format","prettyFormat"],"verifierAdapter":"node-typescript@1"}
index.mjs
import prettyFormat, { format, plugins, DEFAULT_OPTIONS } from 'pretty-format';

export { prettyFormat, format, plugins, DEFAULT_OPTIONS };

export function formatWithCustomPlugin(value, plugin) {
  return format(value, { plugins: [plugin] });
}

export function formatMinified(value) {
  return format(value, { min: true });
}
package-lock.json
{
  "name": "sample-pretty-format",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pretty-format",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "pretty-format": "27.5.1"
      }
    },
    "node_modules/ansi-regex": {
      "version": "5.0.1",
      "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
      "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/ansi-styles": {
      "version": "5.2.0",
      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
      "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
      }
    },
    "node_modules/pretty-format": {
      "version": "27.5.1",
      "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz",
      "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
      "license": "MIT",
      "dependencies": {
        "ansi-regex": "^5.0.1",
        "ansi-styles": "^5.0.0",
        "react-is": "^17.0.1"
      },
      "engines": {
        "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
      }
    },
    "node_modules/react-is": {
      "version": "17.0.2",
      "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
      "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-pretty-format",
  "version": "1.0.0",
  "description": "Clean-room verification sample for pretty-format",
  "type": "module",
  "main": "index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "pretty-format": "27.5.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "format JavaScript value to string using format function",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pretty-format@27.5.1"
  ],
  "symbols": [
    "format",
    "prettyFormat"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import prettyFormat, { format, plugins, DEFAULT_OPTIONS } from 'pretty-format';
import { formatWithCustomPlugin, formatMinified } from '../index.mjs';

// 1. format serializes primitive values including strings, numbers, booleans, symbols, 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('testKey')), 'Symbol(testKey)');
  assert.equal(format(12345678901234567890n), '12345678901234567890n');
}

// 2. format serializes plain objects and nested arrays with standard indentation
{
  const obj = {
    str: 'value',
    num: 10,
    list: [1, 2],
  };
  const expected = [
    'Object {',
    '  "list": Array [',
    '    1,',
    '    2,',
    '  ],',
    '  "num": 10,',
    '  "str": "value",',
    '}',
  ].join('\n');
  assert.equal(format(obj), expected);
}

// 3. format serializes Set and Map collections with entry representations
{
  const set = new Set(['alpha', 'beta']);
  const setFormatted = format(set);
  assert.ok(setFormatted.includes('Set {'));
  assert.ok(setFormatted.includes('"alpha",'));
  assert.ok(setFormatted.includes('"beta",'));

  const map = new Map([['k1', 'v1'], ['k2', 'v2']]);
  const mapFormatted = format(map);
  assert.ok(mapFormatted.includes('Map {'));
  assert.ok(mapFormatted.includes('"k1" => "v1",'));
  assert.ok(mapFormatted.includes('"k2" => "v2",'));
}

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

// 5. format respects maxDepth option by truncating objects beyond depth limit
{
  const deeplyNested = {
    level1: {
      level2: {
        level3: 'deep',
      },
    },
  };
  const shallow = format(deeplyNested, { maxDepth: 1 });
  assert.ok(shallow.includes('"level1": [Object]'));
  assert.ok(!shallow.includes('level3'));
}

// 6. format min option outputs compact single-line JSON-like representation
{
  const data = { a: 1, b: 'two' };
  const minified = format(data, { min: true });
  assert.equal(minified, '{"a": 1, "b": "two"}');
  assert.equal(formatMinified(data), '{"a": 1, "b": "two"}');
}

// 7. format custom indent option controls spaces per indentation level
{
  const data = { x: 1 };
  const formatted4 = format(data, { indent: 4 });
  const expected4 = 'Object {\n    "x": 1,\n}';
  assert.equal(formatted4, expected4);
}

// 8. format printFunctionName option controls whether function names are printed
{
  function sampleFunction() {}
  assert.equal(format(sampleFunction, { printFunctionName: true }), '[Function sampleFunction]');
  assert.equal(format(sampleFunction, { printFunctionName: false }), '[Function]');
}

// 9. format supports custom plugins implementing test and serialize hooks
{
  const customPlugin = {
    test(val) {
      return val && typeof val === 'object' && val.__customBrand === 'Money';
    },
    serialize(val, config, indentation, depth, refs, printer) {
      return `${val.currency} ${val.amount.toFixed(2)}`;
    },
  };

  const payload = {
    price: { __customBrand: 'Money', currency: 'USD', amount: 99.5 },
  };
  const result = format(payload, { plugins: [customPlugin] });
  assert.ok(result.includes('"price": USD 99.50'));

  const resultHelper = formatWithCustomPlugin(payload, customPlugin);
  assert.ok(resultHelper.includes('"price": USD 99.50'));
}

// 10. format integrates with built-in ConvertAnsi plugin to convert ANSI escape sequences
{
  const ansiString = '\u001b[31mred text\u001b[39m';
  const ansiResult = format(ansiString, { plugins: [plugins.ConvertAnsi] });
  assert.equal(ansiResult, '"<red>red text</>"');
}

// 11. prettyFormat default export provides identical formatting behavior as format
{
  assert.equal(prettyFormat.format('test'), '"test"');
  assert.equal(prettyFormat.format({ a: 1 }), 'Object {\n  "a": 1,\n}');
}

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

Seeder de origem

anônimo