CodeSampleX

示例

tar-fs 3.1.3: extract

已验证示例 — npm tar-fs 3.1.3: extract. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: tar.extract unpacks directory contents, subdirectories, and files…

sha256:2feda78fa96bc2da9a42d5ec17f95db629d79e34fe1c76c3751dad842a5d0644

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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-23

案例

HOW
目标
verify tar-fs.extract in pkg:npm/tar-fs@3.1.3
包
符号
  • tar-fs.extract
环境
node 22.23.2
创建时间
2026-08-23T17:48:54Z

契约

  1. tar.extract unpacks directory contents, subdirectories, and files preserving file contents and relative symlinks
  2. tar.extract ignores matching files and directories when custom ignore function is provided
  3. tar.extract strips leading directory levels according to strip option
  4. tar.extract modifies header metadata and file names using map transform function
  5. tar.extract transforms stream data on the fly using mapStream transform stream
  6. tar.extract emits entry and finish events during extraction lifecycle

文件

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

下载源代码构件 (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 tar-fs.extract in pkg:npm/tar-fs@3.1.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tar-fs@3.1.3
Demonstrate these symbols/APIs:
  - tar-fs.extract
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:21c3e118f5b20ef6702ef62a90a2a037efaf6ad062a964b15e9de339d7ddb26d","constraints":{"executionContext":"node"},"contract":["tar.extract unpacks directory contents, subdirectories, and files preserving file contents and relative symlinks","tar.extract ignores matching files and directories when custom ignore function is provided","tar.extract strips leading directory levels according to strip option","tar.extract modifies header metadata and file names using map transform function","tar.extract transforms stream data on the fly using mapStream transform stream","tar.extract emits entry and finish events during extraction lifecycle"],"goal":"verify tar-fs.extract in pkg:npm/tar-fs@3.1.3","kind":"HOW","packages":["pkg:npm/tar-fs@3.1.3"],"schemaVersion":1,"symbols":["tar-fs.extract"]},"contractCommand":["node","test/contract.cjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/tar-fs@3.1.3"],"schemaVersion":1,"subject":"pkg:npm/tar-fs@3.1.3","symbols":["tar-fs.extract"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const fs = require('fs');
const path = require('path');
const tar = require('tar-fs');

/**
 * Extracts a tar stream into a target destination directory.
 * @param {ReadableStream} stream - Readable tar stream or stream producer.
 * @param {string} destination - Path to destination directory.
 * @param {object} [options] - Options passed directly to tar.extract.
 * @returns {Promise<void>} Resolves when extraction finishes.
 */
function extractStream(stream, destination, options = {}) {
  return new Promise((resolve, reject) => {
    const extractor = tar.extract(destination, options);
    extractor.on('finish', resolve);
    extractor.on('error', reject);
    stream.on('error', reject);
    stream.pipe(extractor);
  });
}

/**
 * Packs a source directory and extracts it directly into a destination directory.
 * @param {string} sourceDir - Path to source directory to pack.
 * @param {string} destDir - Path to destination directory to extract into.
 * @param {object} [options] - Options for tar.extract.
 * @returns {Promise<void>} Resolves when extraction finishes.
 */
function extractFromDirectory(sourceDir, destDir, options = {}) {
  const packStream = tar.pack(sourceDir);
  return extractStream(packStream, destDir, options);
}

module.exports = {
  extractStream,
  extractFromDirectory,
  tar
};
package-lock.json
{
  "name": "sample-tar-fs-extract",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tar-fs-extract",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tar-fs": "3.1.3"
      }
    },
    "node_modules/b4a": {
      "version": "1.8.1",
      "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz",
      "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "react-native-b4a": "*"
      },
      "peerDependenciesMeta": {
        "react-native-b4a": {
          "optional": true
        }
      }
    },
    "node_modules/bare-events": {
      "version": "2.9.1",
      "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.1.tgz",
      "integrity": "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "bare-abort-controller": "*"
      },
      "peerDependenciesMeta": {
        "bare-abort-controller": {
          "optional": true
        }
      }
    },
    "node_modules/bare-fs": {
      "version": "4.8.0",
      "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.0.tgz",
      "integrity": "sha512-fM+MhCvdQhZ7NV6S95a07gPSqjIYKn6mFaXfx266wN3ajZGl/+1AzH+ubkXQ0fFZvOe2nk9VHkzdYkQE5zMV3Q==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.5.4",
        "bare-path": "^3.0.0",
        "bare-stream": "^2.6.4",
        "bare-url": "^2.2.2",
        "fast-fifo": "^1.3.2"
      },
      "engines": {
        "bare": ">=1.28.0"
      },
      "peerDependencies": {
        "bare-buffer": "*"
      },
      "peerDependenciesMeta": {
        "bare-buffer": {
          "optional": true
        }
      }
    },
    "node_modules/bare-path": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.1.tgz",
      "integrity": "sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ==",
      "license": "Apache-2.0"
    },
    "node_modules/bare-stream": {
      "version": "2.13.3",
      "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.3.tgz",
      "integrity": "sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==",
      "license": "Apache-2.0",
      "dependencies": {
        "b4a": "^1.8.1",
        "streamx": "^2.25.0",
        "teex": "^1.0.1"
      },
      "peerDependencies": {
        "bare-abort-controller": "*",
        "bare-buffer": "*",
        "bare-events": "*"
      },
      "peerDependenciesMeta": {
        "bare-abort-controller": {
          "optional": true
        },
        "bare-buffer": {
          "optional": true
        },
        "bare-events": {
          "optional": true
        }
      }
    },
    "node_modules/bare-url": {
      "version": "2.5.2",
      "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.2.tgz",
      "integrity": "sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-path": "^3.0.0"
      }
    },
    "node_modules/end-of-stream": {
      "version": "1.4.5",
      "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
      "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
      "license": "MIT",
      "dependencies": {
        "once": "^1.4.0"
      }
    },
    "node_modules/events-universal": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
      "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.7.0"
      }
    },
    "node_modules/fast-fifo": {
      "version": "1.3.2",
      "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
      "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
      "license": "MIT"
    },
    "node_modules/once": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
      "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
      "license": "ISC",
      "dependencies": {
        "wrappy": "1"
      }
    },
    "node_modules/pump": {
      "version": "3.0.4",
      "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
      "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
      "license": "MIT",
      "dependencies": {
        "end-of-stream": "^1.1.0",
        "once": "^1.3.1"
      }
    },
    "node_modules/streamx": {
      "version": "2.28.0",
      "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz",
      "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==",
      "license": "MIT",
      "dependencies": {
        "events-universal": "^1.0.0",
        "fast-fifo": "^1.3.2",
        "text-decoder": "^1.1.0"
      }
    },
    "node_modules/tar-fs": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz",
      "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==",
      "license": "MIT",
      "dependencies": {
        "pump": "^3.0.0",
        "tar-stream": "^3.1.5"
      },
      "optionalDependencies": {
        "bare-fs": "^4.0.1",
        "bare-path": "^3.0.0"
      }
    },
    "node_modules/tar-stream": {
      "version": "3.2.0",
      "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz",
      "integrity": "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==",
      "license": "MIT",
      "dependencies": {
        "b4a": "^1.6.4",
        "bare-fs": "^4.5.5",
        "fast-fifo": "^1.2.0",
        "streamx": "^2.15.0"
      }
    },
    "node_modules/teex": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
      "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
      "license": "MIT",
      "dependencies": {
        "streamx": "^2.12.5"
      }
    },
    "node_modules/text-decoder": {
      "version": "1.2.7",
      "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
      "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
      "license": "Apache-2.0",
      "dependencies": {
        "b4a": "^1.6.4"
      }
    },
    "node_modules/wrappy": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
      "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "sample-tar-fs-extract",
  "version": "1.0.0",
  "private": true,
  "description": "verify tar-fs.extract in pkg:npm/tar-fs@3.1.3",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.cjs"
  },
  "dependencies": {
    "tar-fs": "3.1.3"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tar-fs.extract in pkg:npm/tar-fs@3.1.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tar-fs@3.1.3"
  ],
  "symbols": [
    "tar-fs.extract"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.cjs
'use strict';

const assert = require('assert');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { Transform } = require('stream');
const tar = require('tar-fs');
const { extractStream, extractFromDirectory } = require('../index.js');

async function main() {
  const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'tar-fs-extract-test-'));

  try {
    const srcDir = path.join(tmpRoot, 'source');
    const outDir = path.join(tmpRoot, 'output');
    fs.mkdirSync(srcDir, { recursive: true });
    fs.mkdirSync(outDir, { recursive: true });

    // Populate test source files and directories
    fs.writeFileSync(path.join(srcDir, 'file1.txt'), 'Hello tar-fs extract!', 'utf8');
    fs.mkdirSync(path.join(srcDir, 'sub'), { recursive: true });
    fs.writeFileSync(path.join(srcDir, 'sub', 'file2.txt'), 'Nested content', 'utf8');
    fs.writeFileSync(path.join(srcDir, 'sub', 'skip-me.log'), 'Log to ignore', 'utf8');

    // Create a symlink in source if platform supports it
    let hasSymlink = false;
    if (process.platform !== 'win32') {
      try {
        fs.symlinkSync('file1.txt', path.join(srcDir, 'link-to-file1.txt'));
        hasSymlink = true;
      } catch (err) {
        // Ignore symlink creation failure if filesystem restricts
      }
    }

    // 1. Test basic extraction using extractFromDirectory
    const basicDest = path.join(outDir, 'basic');
    await extractFromDirectory(srcDir, basicDest);

    assert.strictEqual(
      fs.readFileSync(path.join(basicDest, 'file1.txt'), 'utf8'),
      'Hello tar-fs extract!',
      'extracted file1.txt content must match'
    );
    assert.strictEqual(
      fs.readFileSync(path.join(basicDest, 'sub', 'file2.txt'), 'utf8'),
      'Nested content',
      'extracted nested file2.txt content must match'
    );
    if (hasSymlink) {
      const linkStat = fs.lstatSync(path.join(basicDest, 'link-to-file1.txt'));
      assert.strictEqual(linkStat.isSymbolicLink(), true, 'extracted link must be a symbolic link');
      const readTarget = fs.readlinkSync(path.join(basicDest, 'link-to-file1.txt'));
      assert.strictEqual(readTarget, 'file1.txt', 'symlink target must point to relative file1.txt');
    }

    // 2. Test tar.extract with ignore filter
    const filteredDest = path.join(outDir, 'filtered');
    await extractStream(tar.pack(srcDir), filteredDest, {
      ignore: (name) => name.endsWith('.log')
    });

    assert.strictEqual(
      fs.existsSync(path.join(filteredDest, 'file1.txt')),
      true,
      'non-ignored file must exist'
    );
    assert.strictEqual(
      fs.existsSync(path.join(filteredDest, 'sub', 'skip-me.log')),
      false,
      'ignored file must not be extracted'
    );

    // 3. Test tar.extract with strip option
    const strippedDest = path.join(outDir, 'stripped');
    await extractStream(tar.pack(srcDir, { entries: ['sub'] }), strippedDest, {
      strip: 1
    });

    assert.strictEqual(
      fs.existsSync(path.join(strippedDest, 'file2.txt')),
      true,
      'stripped sub/file2.txt must be extracted directly to root of destination'
    );
    assert.strictEqual(
      fs.readFileSync(path.join(strippedDest, 'file2.txt'), 'utf8'),
      'Nested content',
      'stripped file content must match'
    );

    // 4. Test tar.extract with header map function (renaming)
    const mappedDest = path.join(outDir, 'mapped');
    await extractStream(tar.pack(srcDir, { entries: ['file1.txt'] }), mappedDest, {
      map: (header) => {
        if (header.name === 'file1.txt') {
          header.name = 'renamed.txt';
        }
        return header;
      }
    });

    assert.strictEqual(
      fs.existsSync(path.join(mappedDest, 'renamed.txt')),
      true,
      'mapped file must be renamed according to header.name transformation'
    );
    assert.strictEqual(
      fs.readFileSync(path.join(mappedDest, 'renamed.txt'), 'utf8'),
      'Hello tar-fs extract!',
      'renamed file content must match original'
    );

    // 5. Test tar.extract with mapStream content transformation
    const transformedDest = path.join(outDir, 'transformed');
    await extractStream(tar.pack(srcDir, { entries: ['file1.txt'] }), transformedDest, {
      mapStream: (stream, header) => {
        const uppercaseTransform = new Transform({
          transform(chunk, encoding, callback) {
            callback(null, Buffer.from(chunk.toString('utf8').toUpperCase()));
          }
        });
        return stream.pipe(uppercaseTransform);
      }
    });

    assert.strictEqual(
      fs.readFileSync(path.join(transformedDest, 'file1.txt'), 'utf8'),
      'HELLO TAR-FS EXTRACT!',
      'mapStream transformation must modify file content during extraction'
    );

    // 6. Test direct tar.extract stream event handling
    const directDest = path.join(outDir, 'direct');
    let finishFired = false;
    let entryCount = 0;

    await new Promise((resolve, reject) => {
      const extractor = tar.extract(directDest);
      extractor.on('entry', (header, stream, next) => {
        entryCount++;
        next();
      });
      extractor.on('finish', () => {
        finishFired = true;
        resolve();
      });
      extractor.on('error', reject);

      tar.pack(srcDir, { entries: ['file1.txt', 'sub'] }).pipe(extractor);
    });

    assert.strictEqual(finishFired, true, 'tar.extract must emit finish event on completion');
    assert(entryCount >= 2, 'tar.extract entry event must fire for processed entries');
    assert.strictEqual(
      fs.readFileSync(path.join(directDest, 'file1.txt'), 'utf8'),
      'Hello tar-fs extract!',
      'direct extract file content must match'
    );

    console.log('Contract tests passed successfully.');
    process.exit(0);
  } finally {
    try {
      if (fs.existsSync(tmpRoot)) {
        fs.rmSync(tmpRoot, { recursive: true, force: true });
      }
    } catch (e) {
      // Ignore cleanup error
    }
  }
}

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

原始种子者

匿名