CodeSampleX

Пример

semver 7.8.5: Parse and validate semantic version strings into SemVer objects, increment release versions and prereleases with custom identifier bases, classify version transitions with diff, clean formatted strings, and compare versions including build metadata with compareBuild in semver

Проверенный пример — npm semver 7.8.5: Parse and validate semantic version strings into SemVer objects, increment release versions and prereleases with…

sha256:d0e9f30e1aa5f177719559fd74ad0f3c6ff4be338e10b7ca51fcb0e8f39ba22d

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19
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
Цель
Parse and validate semantic version strings into SemVer objects, increment release versions and prereleases with custom identifier bases, classify version transitions with diff, clean formatted strings, and compare versions including build metadata with compareBuild in semver
Пакеты
Символы
  • clean
  • compareBuild
  • diff
  • inc
  • parse
  • valid
Создан
2026-08-18T21:21:47Z

Контракт

  1. assert semver.valid validates and normalizes semver strings or returns null for invalid inputs
  2. assert semver.clean sanitizes version strings by trimming whitespace, stripping prefixes, and removing build metadata
  3. assert semver.parse constructs a SemVer object containing major, minor, patch, prerelease, and build fields
  4. assert semver.inc increments release numbers, manages prerelease tags, and respects identifierBase options
  5. assert semver.diff identifies the difference type between two versions or returns null for equal versions
  6. assert semver.compareBuild differentiates build metadata whereas standard compare treats them as equal

Файлы

  • 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: Parse and validate semantic version strings into SemVer objects, increment release versions and prereleases with custom identifier bases, classify version transitions with diff, clean formatted strings, and compare versions including build metadata with compareBuild in semver
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/semver@7.8.5
Demonstrate these symbols/APIs:
  - clean
  - compareBuild
  - diff
  - inc
  - parse
  - valid

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:7f3a6f8d941f132e120dd42e8029bf2482f9fdd1b7ce0194faf3cf8660f2a34a","contract":["assert semver.valid validates and normalizes semver strings or returns null for invalid inputs","assert semver.clean sanitizes version strings by trimming whitespace, stripping prefixes, and removing build metadata","assert semver.parse constructs a SemVer object containing major, minor, patch, prerelease, and build fields","assert semver.inc increments release numbers, manages prerelease tags, and respects identifierBase options","assert semver.diff identifies the difference type between two versions or returns null for equal versions","assert semver.compareBuild differentiates build metadata whereas standard compare treats them as equal"],"goal":"Parse and validate semantic version strings into SemVer objects, increment release versions and prereleases with custom identifier bases, classify version transitions with diff, clean formatted strings, and compare versions including build metadata with compareBuild in semver","kind":"HOW","packages":["pkg:npm/semver@7.8.5"],"schemaVersion":1,"symbols":["clean","compareBuild","diff","inc","parse","valid"]},"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,"virtualization":"wsl"},"license":"MIT-0","packages":["pkg:npm/semver@7.8.5"],"schemaVersion":1,"symbols":["clean","compareBuild","diff","inc","parse","valid"],"verifierAdapter":"node-typescript@1"}
index.mjs
import semver from 'semver';

/**
 * Validate a version string and return the normalized version or null.
 */
export function validateVersion(version, options = {}) {
  return semver.valid(version, options);
}

/**
 * Clean and sanitize a version string, stripping leading characters and build metadata.
 */
export function cleanVersion(version, options = {}) {
  return semver.clean(version, options);
}

/**
 * Parse a version string into a SemVer object with detailed components.
 */
export function parseVersion(version, options = {}) {
  return semver.parse(version, options);
}

/**
 * Increment a version string by release type with optional identifier and base.
 */
export function incrementVersion(version, release, identifier, identifierBase) {
  return semver.inc(version, release, identifier, identifierBase);
}

/**
 * Classify the difference or transition type between two versions.
 */
export function difference(v1, v2) {
  return semver.diff(v1, v2);
}

/**
 * Compare two version strings including their build metadata.
 */
export function compareWithBuild(v1, v2) {
  return semver.compareBuild(v1, v2);
}
package-lock.json
{
  "name": "sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample",
      "version": "1.0.0",
      "dependencies": {
        "semver": "7.8.5"
      }
    },
    "node_modules/semver": {
      "version": "7.8.5",
      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="
    }
  }
}
package.json
{
  "name": "sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "semver": "7.8.5"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Parse and validate semantic version strings into SemVer objects, increment release versions and prereleases with custom identifier bases, classify version transitions with diff, clean formatted strings, and compare versions including build metadata with compareBuild in semver",
  "kind": "HOW",
  "packages": [
    "pkg:npm/semver@7.8.5"
  ],
  "symbols": [
    "clean",
    "compareBuild",
    "diff",
    "inc",
    "parse",
    "valid"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import semver from 'semver';
import {
  validateVersion,
  cleanVersion,
  parseVersion,
  incrementVersion,
  difference,
  compareWithBuild
} from '../index.mjs';

// 1. assert semver.valid validates and normalizes semver strings or returns null for invalid inputs
{
  assert.equal(validateVersion('1.2.3'), '1.2.3');
  assert.equal(validateVersion('v2.0.1-rc.1'), '2.0.1-rc.1');
  assert.equal(validateVersion('  1.2.3  '), '1.2.3');
  assert.equal(validateVersion('1.0.0+20130313144700'), '1.0.0');
  assert.equal(validateVersion('invalid-version'), null);
  assert.equal(validateVersion('1.2.3.4'), null);
}

// 2. assert semver.clean sanitizes version strings by trimming whitespace, stripping prefixes, and removing build metadata
{
  assert.equal(cleanVersion('  =v1.2.3   '), '1.2.3');
  assert.equal(cleanVersion('  v1.0.0-beta.1+build.123  '), '1.0.0-beta.1');
  assert.equal(cleanVersion('1.2.3+exp.sha.5114f85'), '1.2.3');
  assert.equal(cleanVersion('~1.2.3'), null);
  assert.equal(cleanVersion('not-a-version'), null);
}

// 3. assert semver.parse constructs a SemVer object containing major, minor, patch, prerelease, and build fields
{
  const parsed = parseVersion('2.4.1-beta.3+exp.sha.5114f85');
  assert.ok(parsed instanceof semver.SemVer);
  assert.equal(parsed.major, 2);
  assert.equal(parsed.minor, 4);
  assert.equal(parsed.patch, 1);
  assert.deepEqual(parsed.prerelease, ['beta', 3]);
  assert.deepEqual(parsed.build, ['exp', 'sha', '5114f85']);
  assert.equal(parsed.version, '2.4.1-beta.3');
  assert.equal(parsed.raw, '2.4.1-beta.3+exp.sha.5114f85');
  assert.equal(parseVersion('invalid'), null);
}

// 4. assert semver.inc increments release numbers, manages prerelease tags, and respects identifierBase options
{
  assert.equal(incrementVersion('1.2.3', 'major'), '2.0.0');
  assert.equal(incrementVersion('1.2.3', 'minor'), '1.3.0');
  assert.equal(incrementVersion('1.2.3', 'patch'), '1.2.4');
  assert.equal(incrementVersion('1.2.3', 'prerelease', 'alpha'), '1.2.4-alpha.0');
  assert.equal(incrementVersion('1.2.3-alpha.0', 'prerelease'), '1.2.3-alpha.1');
  assert.equal(incrementVersion('1.2.3-alpha.1', 'patch'), '1.2.3');
  assert.equal(incrementVersion('1.0.0', 'prerelease', 'rc', '1'), '1.0.1-rc.1');
  assert.equal(incrementVersion('1.0.0', 'prerelease', 'beta', false), '1.0.1-beta');
}

// 5. assert semver.diff identifies the difference type between two versions or returns null for equal versions
{
  assert.equal(difference('1.2.3', '2.0.0'), 'major');
  assert.equal(difference('1.2.3', '1.3.0'), 'minor');
  assert.equal(difference('1.2.3', '1.2.4'), 'patch');
  assert.equal(difference('1.2.3-alpha.1', '1.2.3-alpha.2'), 'prerelease');
  assert.equal(difference('1.2.3', '1.2.3'), null);
}

// 6. assert semver.compareBuild differentiates build metadata whereas standard compare treats them as equal
{
  assert.equal(semver.compare('1.2.3+build.1', '1.2.3+build.2'), 0);
  assert.equal(compareWithBuild('1.2.3+build.1', '1.2.3+build.2'), -1);
  assert.equal(compareWithBuild('1.2.3+build.2', '1.2.3+build.1'), 1);
  assert.equal(compareWithBuild('1.2.3', '1.2.3+build.1'), -1);
  assert.equal(compareWithBuild('1.2.3+build.1', '1.2.3+build.1'), 0);
}

console.log('PASS: all contract assertions satisfied');

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

аноним