CodeSampleX

샘플

@vitest/snapshot 2.1.9: SnapshotState, NodeSnapshotEnvironment

검증된 샘플 — npm @vitest/snapshot 2.1.9: SnapshotState, NodeSnapshotEnvironment. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:c2b813070b2c42589f552ed45c9571c9977d469a26d9173582eee395c2c109e0

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-26

케이스

HOW
목표
verify pkg:npm/%40vitest/snapshot@2.1.9
패키지
심벌
  • SnapshotState
  • NodeSnapshotEnvironment
환경
node 22.23.2
생성일
2026-08-26T14:47:52Z

컨트랙트

  1. SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'.
  2. SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents.
  3. When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch.
  4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Notes on @vitest/snapshot SnapshotState and NodeSnapshotEnvironment

Search via `search_known_solution` returned `NO_SAFE_MATCH` for `@vitest/snapshot@2.1.9`, requiring fresh verification.

## API Characteristics

1. **Snapshot State Initialization:**
   `SnapshotState.create(testFilePath, options)` initializes a snapshot management instance. It requires `snapshotEnvironment` (an instance of `NodeSnapshotEnvironment` or custom `SnapshotEnvironment`) and `updateSnapshot` mode (`'all'`, `'new'`, or `'none'`).

2. **Matching and Formatting:**
   - Calling `state.match(...)` compares the serialized representation of `received` data against stored snapshots.
   - When updating or matching successfully, `pass` is `true`.
   - When `updateSnapshot: 'none'` and values differ, `pass` is `false`, and structured results with formatted values are provided.
   - `state.save()` commits the snapshot file to disk via the configured `SnapshotEnvironment`.

3. **Metrics Reporting:**
   - Calling `state.pack()` produces a summary containing counts of `added`, `matched`, `unmatched`, `updated`, and `unchecked` keys.

## Verified Contract

The contract in `test/contract.mjs` verifies:
- `SnapshotState.create` initializes state with `NodeSnapshotEnvironment` and matches new snapshots when `updateSnapshot` is `'all'`.
- `SnapshotState.prototype.save` writes snapshot files to disk with formatted serialized contents.
- When `updateSnapshot` is `'none'`, `SnapshotState.prototype.match` passes for matching values and fails on mismatch.
- `SnapshotState.prototype.pack` returns matched and unmatched counters for executed snapshot assertions.
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 pkg:npm/%40vitest/snapshot@2.1.9
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/snapshot@2.1.9
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:3311d53c154d23e5d943247beeb6cd077f6f92afcf5cfb16a254334b58d3c47a","constraints":{"executionContext":"node"},"contract":["SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'.","SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents.","When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch.","SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions."],"goal":"verify pkg:npm/%40vitest/snapshot@2.1.9","kind":"HOW","packages":["pkg:npm/%40vitest/snapshot@2.1.9"],"schemaVersion":1,"symbols":["SnapshotState","NodeSnapshotEnvironment"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","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/snapshot@2.1.9"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/snapshot@2.1.9","symbols":["SnapshotState","NodeSnapshotEnvironment"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { SnapshotState, addSerializer } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';

export async function createSnapshotManager(testFilePath, options = {}) {
  const env = new NodeSnapshotEnvironment();
  const state = await SnapshotState.create(testFilePath, {
    updateSnapshot: options.updateSnapshot || 'new',
    snapshotEnvironment: env,
  });
  return state;
}

export function registerCustomSerializer(serializer) {
  addSerializer(serializer);
}
package-lock.json
{
  "name": "vitest-snapshot-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "vitest-snapshot-sample",
      "version": "1.0.0",
      "dependencies": {
        "@vitest/snapshot": "2.1.9"
      }
    },
    "node_modules/@jridgewell/sourcemap-codec": {
      "version": "1.5.5",
      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
      "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
      "license": "MIT"
    },
    "node_modules/@vitest/pretty-format": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
      "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
      "license": "MIT",
      "dependencies": {
        "tinyrainbow": "^1.2.0"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/@vitest/snapshot": {
      "version": "2.1.9",
      "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
      "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/pretty-format": "2.1.9",
        "magic-string": "^0.30.12",
        "pathe": "^1.1.2"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "node_modules/magic-string": {
      "version": "0.30.21",
      "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
      "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
      "license": "MIT",
      "dependencies": {
        "@jridgewell/sourcemap-codec": "^1.5.5"
      }
    },
    "node_modules/pathe": {
      "version": "1.1.2",
      "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
      "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
      "license": "MIT"
    },
    "node_modules/tinyrainbow": {
      "version": "1.2.0",
      "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
      "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
      "license": "MIT",
      "engines": {
        "node": ">=14.0.0"
      }
    }
  }
}
package.json
{
  "name": "vitest-snapshot-sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "@vitest/snapshot": "2.1.9"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40vitest/snapshot@2.1.9",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/snapshot@2.1.9"
  ],
  "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/strict';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SnapshotState } from '@vitest/snapshot';
import { NodeSnapshotEnvironment } from '@vitest/snapshot/environment';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const tmpDir = path.join(__dirname, 'tmp_sandbox');

async function main() {
  await fs.mkdir(tmpDir, { recursive: true });
  const testFilePath = path.join(tmpDir, 'sample.test.js');
  const env = new NodeSnapshotEnvironment();

  try {
    // 1. SnapshotState.create initializes state with NodeSnapshotEnvironment and matches new snapshots when updateSnapshot is 'all'
    const stateUpdate = await SnapshotState.create(testFilePath, {
      updateSnapshot: 'all',
      snapshotEnvironment: env,
    });
    assert.ok(stateUpdate, 'SnapshotState instance should be created');

    const matchRes1 = stateUpdate.match({
      testId: 'test-user-profile',
      testName: 'renders user profile correctly',
      received: { id: 101, username: 'agent-alice', active: true },
      isInline: false,
    });
    assert.equal(matchRes1.pass, true, 'Matching new snapshot in all mode must pass');
    assert.equal(matchRes1.key, 'renders user profile correctly 1');

    // 2. SnapshotState.prototype.save writes snapshot files to disk with formatted serialized contents
    const saveResult = await stateUpdate.save();
    assert.equal(saveResult.saved, true, 'SnapshotState save should return saved: true');

    const packedUpdate = await stateUpdate.pack();
    assert.equal(packedUpdate.added, 1, 'Packed summary must show 1 snapshot added');
    assert.equal(packedUpdate.unmatched, 0);

    // 3. When updateSnapshot is 'none', SnapshotState.prototype.match passes for matching values and fails on mismatch
    const stateReadonly = await SnapshotState.create(testFilePath, {
      updateSnapshot: 'none',
      snapshotEnvironment: env,
    });

    const matchPass = stateReadonly.match({
      testId: 'test-user-profile',
      testName: 'renders user profile correctly',
      received: { id: 101, username: 'agent-alice', active: true },
      isInline: false,
    });
    assert.equal(matchPass.pass, true, 'Matching identical value against existing snapshot must pass');

    const matchFail = stateReadonly.match({
      testId: 'test-user-profile',
      testName: 'renders user profile correctly',
      received: { id: 101, username: 'agent-bob', active: false },
      isInline: false,
    });
    assert.equal(matchFail.pass, false, 'Matching modified value with updateSnapshot none must fail');
    assert.ok(matchFail.actual !== undefined, 'Mismatch result should include actual value');

    // 4. SnapshotState.prototype.pack returns matched and unmatched counters for executed snapshot assertions
    const packedReadonly = await stateReadonly.pack();
    assert.equal(packedReadonly.matched, 1, 'Matched count should be 1');
    assert.equal(packedReadonly.unmatched, 1, 'Unmatched count should be 1');
    assert.equal(packedReadonly.added, 0, 'Added count should be 0');

    console.log('All contract assertions passed successfully.');
  } finally {
    await fs.rm(tmpDir, { recursive: true, force: true });
  }
}

main().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

오리진 시더

익명