CodeSampleX

示例

fs-extra 10.1.0

已验证示例 — npm fs-extra 10.1.0. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: ensureDir creates nested directory structures if they do not exist

sha256:aeee8efab163cc48f0c9ce5b605150a575a12242bf464d59474ee660bd4597e4

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

案例

HOW
目标
verify pkg:npm/fs-extra@10.1.0
包
环境
node 22.23.2
创建时间
2026-08-20T00:51:28Z

契约

  1. ensureDir creates nested directory structures if they do not exist
  2. outputJson and readJson write and read JSON documents while automatically creating parent directories
  3. copy recursively copies directory hierarchies and supports custom filter functions
  4. emptyDir deletes all contents within a directory while leaving the directory itself intact
  5. pathExists accurately checks the existence of files and directories
  6. remove recursively removes directories and files without throwing if the target does not exist

文件

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

下载源代码构件 (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 pkg:npm/fs-extra@10.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/fs-extra@10.1.0
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:ae0ed3f3a42a723d120c0d66369dee464d0a4eb0ba30f9b2d4a1e5b72054dddc","constraints":{"executionContext":"node"},"contract":["ensureDir creates nested directory structures if they do not exist","outputJson and readJson write and read JSON documents while automatically creating parent directories","copy recursively copies directory hierarchies and supports custom filter functions","emptyDir deletes all contents within a directory while leaving the directory itself intact","pathExists accurately checks the existence of files and directories","remove recursively removes directories and files without throwing if the target does not exist"],"goal":"verify pkg:npm/fs-extra@10.1.0","kind":"HOW","packages":["pkg:npm/fs-extra@10.1.0"],"schemaVersion":1},"contractCommand":["node","test/contract.js"],"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/fs-extra@10.1.0"],"schemaVersion":1,"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "fs-extra-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "fs-extra-sample",
      "version": "1.0.0",
      "dependencies": {
        "fs-extra": "10.1.0"
      }
    },
    "node_modules/fs-extra": {
      "version": "10.1.0",
      "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
      "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==",
      "license": "MIT",
      "dependencies": {
        "graceful-fs": "^4.2.0",
        "jsonfile": "^6.0.1",
        "universalify": "^2.0.0"
      },
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/jsonfile": {
      "version": "6.2.1",
      "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.1.tgz",
      "integrity": "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==",
      "license": "MIT",
      "dependencies": {
        "universalify": "^2.0.0"
      },
      "optionalDependencies": {
        "graceful-fs": "^4.1.6"
      }
    },
    "node_modules/universalify": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
      "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
      "license": "MIT",
      "engines": {
        "node": ">= 10.0.0"
      }
    }
  }
}
package.json
{
  "name": "fs-extra-sample",
  "version": "1.0.0",
  "dependencies": {
    "fs-extra": "10.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/fs-extra@10.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/fs-extra@10.1.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const fse = require('fs-extra');

/**
 * Ensures that a directory exists. If the directory structure does not exist, it is created.
 *
 * @param {string} dirPath - Directory path to ensure.
 * @returns {Promise<void>}
 */
async function ensureDirectory(dirPath) {
  await fse.ensureDir(dirPath);
}

/**
 * Writes an object to a JSON file, automatically creating parent directories if they do not exist.
 *
 * @param {string} filePath - Path of JSON file.
 * @param {any} data - Data to serialize and write.
 * @param {object} [options] - Options for writeJson (e.g. { spaces: 2 }).
 * @returns {Promise<void>}
 */
async function outputJsonFile(filePath, data, options) {
  await fse.outputJson(filePath, data, options);
}

/**
 * Reads a JSON file and parses it into a JavaScript object.
 *
 * @param {string} filePath - Path of JSON file.
 * @returns {Promise<any>}
 */
async function readJsonFile(filePath) {
  return await fse.readJson(filePath);
}

/**
 * Copies a file or directory recursively.
 *
 * @param {string} src - Source file or directory path.
 * @param {string} dest - Destination file or directory path.
 * @param {object} [options] - Copy options such as overwrite and filter.
 * @returns {Promise<void>}
 */
async function copyDirectory(src, dest, options) {
  await fse.copy(src, dest, options);
}

/**
 * Ensures that a directory is empty by deleting all items inside it while preserving the directory itself.
 *
 * @param {string} dirPath - Directory path to empty.
 * @returns {Promise<void>}
 */
async function emptyDirectory(dirPath) {
  await fse.emptyDir(dirPath);
}

/**
 * Tests whether or not the given path exists.
 *
 * @param {string} targetPath - Path to test.
 * @returns {Promise<boolean>}
 */
async function checkPathExists(targetPath) {
  return await fse.pathExists(targetPath);
}

/**
 * Removes a file or directory recursively.
 *
 * @param {string} targetPath - Path to remove.
 * @returns {Promise<void>}
 */
async function removePath(targetPath) {
  await fse.remove(targetPath);
}

module.exports = {
  ensureDirectory,
  outputJsonFile,
  readJsonFile,
  copyDirectory,
  emptyDirectory,
  checkPathExists,
  removePath,
  fse,
};
test/contract.js
const assert = require('node:assert/strict');
const path = require('node:path');
const os = require('node:os');
const fs = require('node:fs');
const {
  ensureDirectory,
  outputJsonFile,
  readJsonFile,
  copyDirectory,
  emptyDirectory,
  checkPathExists,
  removePath,
} = require('../src/index.js');

async function main() {
  const testRoot = path.join(
    os.tmpdir(),
    `fs-extra-contract-test-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
  );

  try {
    // Contract 1: ensureDir creates nested directory structures if they do not exist
    {
      const nestedDir = path.join(testRoot, 'a', 'b', 'c', 'nested');
      assert.strictEqual(await checkPathExists(nestedDir), false);

      await ensureDirectory(nestedDir);
      assert.strictEqual(await checkPathExists(nestedDir), true);
      assert.strictEqual(fs.statSync(nestedDir).isDirectory(), true);

      // Calling ensureDir on an already existing directory should be a no-op
      await ensureDirectory(nestedDir);
      assert.strictEqual(await checkPathExists(nestedDir), true);
    }

    // Contract 2: outputJson and readJson write and read JSON documents while automatically creating parent directories
    {
      const jsonFile = path.join(testRoot, 'nested', 'config', 'app.json');
      const payload = { name: 'csx-test', count: 42, enabled: true, tags: ['node', 'fs'] };

      assert.strictEqual(await checkPathExists(jsonFile), false);
      await outputJsonFile(jsonFile, payload, { spaces: 2 });

      assert.strictEqual(await checkPathExists(jsonFile), true);
      const readBack = await readJsonFile(jsonFile);
      assert.deepStrictEqual(readBack, payload, 'readJson output must match the written object');
    }

    // Contract 3: copy recursively copies directory hierarchies and supports custom filter functions
    {
      const srcDir = path.join(testRoot, 'src_copy');
      const destDir = path.join(testRoot, 'dest_copy');

      await outputJsonFile(path.join(srcDir, 'file1.json'), { item: 1 });
      await outputJsonFile(path.join(srcDir, 'ignore_me.txt'), { item: 'skip' });
      await outputJsonFile(path.join(srcDir, 'sub', 'file2.json'), { item: 2 });

      // Copy with filter that excludes ignore_me.txt
      await copyDirectory(srcDir, destDir, {
        filter: (src) => !src.includes('ignore_me'),
      });

      assert.strictEqual(await checkPathExists(path.join(destDir, 'file1.json')), true);
      assert.strictEqual(await checkPathExists(path.join(destDir, 'sub', 'file2.json')), true);
      assert.strictEqual(await checkPathExists(path.join(destDir, 'ignore_me.txt')), false);

      const copiedContent = await readJsonFile(path.join(destDir, 'sub', 'file2.json'));
      assert.deepStrictEqual(copiedContent, { item: 2 });
    }

    // Contract 4: emptyDir deletes all contents within a directory while leaving the directory itself intact
    {
      const targetDir = path.join(testRoot, 'to_empty');
      await outputJsonFile(path.join(targetDir, 'sub1', 'a.json'), { a: 1 });
      await outputJsonFile(path.join(targetDir, 'sub2', 'b.json'), { b: 2 });

      assert.strictEqual(await checkPathExists(targetDir), true);
      assert.ok(fs.readdirSync(targetDir).length > 0);

      await emptyDirectory(targetDir);

      assert.strictEqual(await checkPathExists(targetDir), true);
      assert.strictEqual(fs.readdirSync(targetDir).length, 0);
    }

    // Contract 5: pathExists accurately checks the existence of files and directories
    {
      const nonExistent = path.join(testRoot, 'does_not_exist_' + Date.now());
      assert.strictEqual(await checkPathExists(nonExistent), false);

      const existingFile = path.join(testRoot, 'exists.json');
      await outputJsonFile(existingFile, { ok: true });
      assert.strictEqual(await checkPathExists(existingFile), true);
    }

    // Contract 6: remove recursively removes directories and files without throwing if the target does not exist
    {
      const toRemove = path.join(testRoot, 'to_remove');
      await outputJsonFile(path.join(toRemove, 'child', 'data.json'), { removed: false });
      assert.strictEqual(await checkPathExists(toRemove), true);

      await removePath(toRemove);
      assert.strictEqual(await checkPathExists(toRemove), false);

      // Removing non-existent path should succeed silently
      await removePath(toRemove);
    }

    console.log('All pkg:npm/fs-extra@10.1.0 contracts passed successfully.');
  } finally {
    try {
      await removePath(testRoot);
    } catch (_) {}
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

原始种子者

匿名