CodeSampleX

Пример

tar 7.5.22: create and extract tar archive

Проверенный пример — npm tar 7.5.22: create and extract tar archive. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:19fdcec6aecbdc8d26ed78e2c636917ae93819c549013a8c1c2abc1e716069e0

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

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

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

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

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

Окружение Контракт Этапы Запуск
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
Цель
create and extract tar archive
Пакеты
Символы
  • tar.create
  • tar.extract
Создан
2026-08-26T09:32:29Z

Контракт

  1. tar.create packages files and nested directories into uncompressed and gzip-compressed tar archives
  2. tar.extract unpacks archive contents restoring file hierarchy and data integrity
  3. tar.create and tar.extract support synchronous operations via the sync option
  4. tar.create and tar.extract filter entries using custom predicate functions
  5. tar.extract supports stripping leading path components using the strip option

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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: create and extract tar archive
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tar@7.5.22
Demonstrate these symbols/APIs:
  - tar.create
  - tar.extract

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:a6d30b6ddf0f0883febd82f2803b9d76c18f1078d5a10cdafd3dfb835821066b","contract":["tar.create packages files and nested directories into uncompressed and gzip-compressed tar archives","tar.extract unpacks archive contents restoring file hierarchy and data integrity","tar.create and tar.extract support synchronous operations via the sync option","tar.create and tar.extract filter entries using custom predicate functions","tar.extract supports stripping leading path components using the strip option"],"goal":"create and extract tar archive","kind":"HOW","packages":["pkg:npm/tar@7.5.22"],"schemaVersion":1,"symbols":["tar.create","tar.extract"]},"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/tar@7.5.22"],"schemaVersion":1,"subject":"pkg:npm/tar@7.5.22","symbols":["tar.create","tar.extract"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tar",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tar",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tar": "7.5.22"
      }
    },
    "node_modules/@isaacs/fs-minipass": {
      "version": "4.0.1",
      "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz",
      "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==",
      "license": "ISC",
      "dependencies": {
        "minipass": "^7.0.4"
      },
      "engines": {
        "node": ">=18.0.0"
      }
    },
    "node_modules/chownr": {
      "version": "3.0.0",
      "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz",
      "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/minipass": {
      "version": "7.1.3",
      "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
      "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": ">=16 || 14 >=14.17"
      }
    },
    "node_modules/minizlib": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz",
      "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==",
      "license": "MIT",
      "dependencies": {
        "minipass": "^7.1.2"
      },
      "engines": {
        "node": ">= 18"
      }
    },
    "node_modules/tar": {
      "version": "7.5.22",
      "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
      "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
      "license": "BlueOak-1.0.0",
      "dependencies": {
        "@isaacs/fs-minipass": "^4.0.0",
        "chownr": "^3.0.0",
        "minipass": "^7.1.2",
        "minizlib": "^3.1.0",
        "yallist": "^5.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/yallist": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
      "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": ">=18"
      }
    }
  }
}
package.json
{
  "name": "sample-tar",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for tar",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "tar": "7.5.22"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "create and extract tar archive",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tar@7.5.22"
  ],
  "symbols": [
    "tar.create",
    "tar.extract"
  ]
}
src/index.mjs
import * as tar from 'tar';

/**
 * Create a tar archive asynchronously.
 * @param {string} archivePath - Output path of the archive file.
 * @param {string[]} fileList - List of files or directories to include.
 * @param {object} [options={}] - Options for tar.create (cwd, gzip, filter, etc.).
 * @returns {Promise<void>}
 */
export async function createArchive(archivePath, fileList, options = {}) {
  return tar.create(
    {
      file: archivePath,
      ...options,
    },
    fileList
  );
}

/**
 * Extract a tar archive asynchronously.
 * @param {string} archivePath - Path to the tar archive.
 * @param {string} targetDir - Destination directory to extract into.
 * @param {object} [options={}] - Options for tar.extract (strip, filter, etc.).
 * @returns {Promise<void>}
 */
export async function extractArchive(archivePath, targetDir, options = {}) {
  return tar.extract({
    file: archivePath,
    cwd: targetDir,
    ...options,
  });
}

/**
 * Create a tar archive synchronously.
 * @param {string} archivePath - Output path of the archive file.
 * @param {string[]} fileList - List of files or directories to include.
 * @param {object} [options={}] - Options for tar.create.
 */
export function createSyncArchive(archivePath, fileList, options = {}) {
  return tar.create(
    {
      file: archivePath,
      sync: true,
      ...options,
    },
    fileList
  );
}

/**
 * Extract a tar archive synchronously.
 * @param {string} archivePath - Path to the tar archive.
 * @param {string} targetDir - Destination directory to extract into.
 * @param {object} [options={}] - Options for tar.extract.
 */
export function extractSyncArchive(archivePath, targetDir, options = {}) {
  return tar.extract({
    file: archivePath,
    cwd: targetDir,
    sync: true,
    ...options,
  });
}
test/contract.mjs
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import * as tar from 'tar';
import {
  createArchive,
  extractArchive,
  createSyncArchive,
  extractSyncArchive
} from '../src/index.mjs';

const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tar-contract-test-'));

try {
  // Setup sample source files
  const fixturesDir = path.join(tempDir, 'fixtures');
  fs.mkdirSync(fixturesDir, { recursive: true });
  fs.writeFileSync(path.join(fixturesDir, 'hello.txt'), 'Hello, World!');
  fs.writeFileSync(path.join(fixturesDir, 'data.json'), JSON.stringify({ name: 'tar', version: '7.5.22' }));
  const subDir = path.join(fixturesDir, 'nested');
  fs.mkdirSync(subDir, { recursive: true });
  fs.writeFileSync(path.join(subDir, 'nested.txt'), 'Nested file content');

  // 1. Direct tar.create and tar.extract (Async uncompressed)
  const directArchive = path.join(tempDir, 'direct.tar');
  const directExtractDir = path.join(tempDir, 'direct-extract');
  fs.mkdirSync(directExtractDir, { recursive: true });

  await tar.create({ file: directArchive, cwd: fixturesDir }, ['hello.txt', 'data.json', 'nested']);
  assert.strictEqual(fs.existsSync(directArchive), true, 'direct.tar should be created');

  await tar.extract({ file: directArchive, cwd: directExtractDir });
  assert.strictEqual(fs.readFileSync(path.join(directExtractDir, 'hello.txt'), 'utf8'), 'Hello, World!');
  assert.strictEqual(fs.readFileSync(path.join(directExtractDir, 'nested', 'nested.txt'), 'utf8'), 'Nested file content');

  // 2. Direct tar.create and tar.extract with gzip compression
  const directGzipArchive = path.join(tempDir, 'direct.tar.gz');
  const directGzipExtractDir = path.join(tempDir, 'direct-gzip-extract');
  fs.mkdirSync(directGzipExtractDir, { recursive: true });

  await tar.create({ file: directGzipArchive, gzip: true, cwd: fixturesDir }, ['hello.txt', 'nested']);
  assert.strictEqual(fs.existsSync(directGzipArchive), true, 'direct.tar.gz should be created');

  await tar.extract({ file: directGzipArchive, cwd: directGzipExtractDir });
  assert.strictEqual(fs.readFileSync(path.join(directGzipExtractDir, 'hello.txt'), 'utf8'), 'Hello, World!');
  assert.strictEqual(fs.readFileSync(path.join(directGzipExtractDir, 'nested', 'nested.txt'), 'utf8'), 'Nested file content');

  // 3. Helper async createArchive and extractArchive
  const helperArchive = path.join(tempDir, 'helper.tar.gz');
  const helperExtractDir = path.join(tempDir, 'helper-extract');
  fs.mkdirSync(helperExtractDir, { recursive: true });

  await createArchive(helperArchive, ['hello.txt', 'data.json'], { cwd: fixturesDir, gzip: true });
  assert.strictEqual(fs.existsSync(helperArchive), true, 'helper.tar.gz should exist');

  await extractArchive(helperArchive, helperExtractDir);
  assert.strictEqual(fs.readFileSync(path.join(helperExtractDir, 'hello.txt'), 'utf8'), 'Hello, World!');
  const data = JSON.parse(fs.readFileSync(path.join(helperExtractDir, 'data.json'), 'utf8'));
  assert.strictEqual(data.name, 'tar');
  assert.strictEqual(data.version, '7.5.22');

  // 4. Synchronous tar.create and tar.extract with sync wrappers
  const syncArchive = path.join(tempDir, 'sync.tar');
  const syncExtractDir = path.join(tempDir, 'sync-extract');
  fs.mkdirSync(syncExtractDir, { recursive: true });

  createSyncArchive(syncArchive, ['hello.txt'], { cwd: fixturesDir });
  assert.strictEqual(fs.existsSync(syncArchive), true, 'sync.tar should exist');

  extractSyncArchive(syncArchive, syncExtractDir);
  assert.strictEqual(fs.readFileSync(path.join(syncExtractDir, 'hello.txt'), 'utf8'), 'Hello, World!');

  // 5. Filtering entries during creation and extraction
  const filteredArchive = path.join(tempDir, 'filtered.tar');
  const filteredExtractDir = path.join(tempDir, 'filtered-extract');
  fs.mkdirSync(filteredExtractDir, { recursive: true });

  await tar.create(
    {
      file: filteredArchive,
      cwd: fixturesDir,
      filter: (p) => !p.endsWith('data.json')
    },
    ['hello.txt', 'data.json']
  );

  await tar.extract({ file: filteredArchive, cwd: filteredExtractDir });
  assert.strictEqual(fs.existsSync(path.join(filteredExtractDir, 'hello.txt')), true);
  assert.strictEqual(fs.existsSync(path.join(filteredExtractDir, 'data.json')), false, 'filtered file should not be archived');

  // 6. Extraction with strip option
  const stripExtractDir = path.join(tempDir, 'strip-extract');
  fs.mkdirSync(stripExtractDir, { recursive: true });

  const nestedArchive = path.join(tempDir, 'nested.tar');
  await tar.create({ file: nestedArchive, cwd: fixturesDir }, ['nested/nested.txt']);

  await tar.extract({ file: nestedArchive, cwd: stripExtractDir, strip: 1 });
  assert.strictEqual(fs.existsSync(path.join(stripExtractDir, 'nested.txt')), true, 'strip 1 should extract nested.txt at root of target');

  console.log('Contract tests passed successfully.');
} finally {
  fs.rmSync(tempDir, { recursive: true, force: true });
}

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

аноним