CodeSampleX

샘플

graceful-fs 4.2.11: promises

검증된 샘플 — npm graceful-fs 4.2.11: promises. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: promises property on graceful-fs provides…

sha256:fd5951b2932d80fb9bd90935076684927208ca399837b264970acf4834535cd5

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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-05

케이스

HOW
목표
verify graceful-fs.promises in pkg:npm/graceful-fs@4.2.11
패키지
심벌
  • graceful-fs.promises
환경
node 22.23.2
생성일
2026-09-05T21:54:13Z

컨트랙트

  1. promises property on graceful-fs provides promise-based filesystem methods
  2. promises.writeFile asynchronously writes data and promises.readFile reads back string and buffer content
  3. promises.readFile rejects with ENOENT when reading a non-existent file path
  4. promises.mkdir creates directories recursively and promises.readdir lists directory entries
  5. promises.stat retrieves file statistics and verifies file type
  6. promises.unlink deletes files and promises.rm removes directory trees

파일

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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: verify graceful-fs.promises in pkg:npm/graceful-fs@4.2.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/graceful-fs@4.2.11
Demonstrate these symbols/APIs:
  - graceful-fs.promises

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:187ceafa86e98fc3d2c0cd551617bcfe5d732d2d6c2d13cf03ecd2ad7d0843ab","contract":["promises property on graceful-fs provides promise-based filesystem methods","promises.writeFile asynchronously writes data and promises.readFile reads back string and buffer content","promises.readFile rejects with ENOENT when reading a non-existent file path","promises.mkdir creates directories recursively and promises.readdir lists directory entries","promises.stat retrieves file statistics and verifies file type","promises.unlink deletes files and promises.rm removes directory trees"],"goal":"verify graceful-fs.promises in pkg:npm/graceful-fs@4.2.11","kind":"HOW","packages":["pkg:npm/graceful-fs@4.2.11"],"schemaVersion":1,"symbols":["graceful-fs.promises"]},"contractCommand":["node","test/contract.mjs"],"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/graceful-fs@4.2.11"],"schemaVersion":1,"subject":"pkg:npm/graceful-fs@4.2.11","symbols":["graceful-fs.promises"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-graceful-fs-promises",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-graceful-fs-promises",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "graceful-fs": "4.2.11"
      }
    },
    "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"
    }
  }
}
package.json
{
  "name": "sample-graceful-fs-promises",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of graceful-fs.promises in pkg:npm/graceful-fs@4.2.11",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "graceful-fs": "4.2.11"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify graceful-fs.promises in pkg:npm/graceful-fs@4.2.11",
  "kind": "HOW",
  "packages": [
    "pkg:npm/graceful-fs@4.2.11"
  ],
  "symbols": [
    "graceful-fs.promises"
  ]
}
src/index.js
'use strict';

const gracefulFs = require('graceful-fs');

/**
 * Access the promises-based filesystem API provided by graceful-fs.
 * @returns {object} The fs.promises API object.
 */
function getPromisesFs() {
  return gracefulFs.promises;
}

/**
 * Write data to a file asynchronously using graceful-fs.promises.
 * @param {string} filePath - Path to the file.
 * @param {string|Buffer} data - Data to write.
 * @param {string|object} [options] - Encoding or options object.
 * @returns {Promise<void>}
 */
async function writeFileAsync(filePath, data, options = 'utf8') {
  return gracefulFs.promises.writeFile(filePath, data, options);
}

/**
 * Read data from a file asynchronously using graceful-fs.promises.
 * @param {string} filePath - Path to the file.
 * @param {string|object} [options] - Encoding or options object.
 * @returns {Promise<string|Buffer>}
 */
async function readFileAsync(filePath, options = 'utf8') {
  return gracefulFs.promises.readFile(filePath, options);
}

/**
 * Create a directory asynchronously using graceful-fs.promises.
 * @param {string} dirPath - Path to directory to create.
 * @param {object} [options] - mkdir options (e.g. recursive).
 * @returns {Promise<string|undefined>}
 */
async function makeDirectoryAsync(dirPath, options = { recursive: true }) {
  return gracefulFs.promises.mkdir(dirPath, options);
}

/**
 * Read contents of a directory asynchronously using graceful-fs.promises.
 * @param {string} dirPath - Path to directory.
 * @returns {Promise<string[]>} List of file names.
 */
async function readDirectoryAsync(dirPath) {
  return gracefulFs.promises.readdir(dirPath);
}

/**
 * Retrieve file metadata asynchronously using graceful-fs.promises.
 * @param {string} targetPath - Path to file or directory.
 * @returns {Promise<object>}
 */
async function getFileStatsAsync(targetPath) {
  return gracefulFs.promises.stat(targetPath);
}

/**
 * Remove a file asynchronously using graceful-fs.promises.
 * @param {string} filePath - Path to file to delete.
 * @returns {Promise<void>}
 */
async function removeFileAsync(filePath) {
  return gracefulFs.promises.unlink(filePath);
}

/**
 * Remove a directory tree asynchronously using graceful-fs.promises.
 * @param {string} dirPath - Path to directory to remove.
 * @returns {Promise<void>}
 */
async function removeDirectoryAsync(dirPath) {
  return gracefulFs.promises.rm(dirPath, { recursive: true, force: true });
}

module.exports = {
  gracefulFs,
  getPromisesFs,
  writeFileAsync,
  readFileAsync,
  makeDirectoryAsync,
  readDirectoryAsync,
  getFileStatsAsync,
  removeFileAsync,
  removeDirectoryAsync,
};
test/contract.mjs
import assert from 'node:assert/strict';
import path from 'node:path';
import os from 'node:os';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  gracefulFs,
  getPromisesFs,
  writeFileAsync,
  readFileAsync,
  makeDirectoryAsync,
  readDirectoryAsync,
  getFileStatsAsync,
  removeFileAsync,
  removeDirectoryAsync,
} = require('../src/index.js');

async function runContract() {
  const testRoot = path.join(
    os.tmpdir(),
    `gfs-promises-contract-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
  );
  await makeDirectoryAsync(testRoot, { recursive: true });

  try {
    // 1. Module export and promises property verification
    assert.ok(gracefulFs, 'gracefulFs module should be defined');
    assert.strictEqual(typeof gracefulFs.promises, 'object', 'graceful-fs should export promises object');
    assert.strictEqual(getPromisesFs(), gracefulFs.promises, 'getPromisesFs should return gracefulFs.promises');
    assert.strictEqual(typeof gracefulFs.promises.readFile, 'function', 'promises.readFile should be a function');
    assert.strictEqual(typeof gracefulFs.promises.writeFile, 'function', 'promises.writeFile should be a function');
    assert.strictEqual(typeof gracefulFs.promises.mkdir, 'function', 'promises.mkdir should be a function');
    assert.strictEqual(typeof gracefulFs.promises.readdir, 'function', 'promises.readdir should be a function');
    assert.strictEqual(typeof gracefulFs.promises.stat, 'function', 'promises.stat should be a function');
    assert.strictEqual(typeof gracefulFs.promises.unlink, 'function', 'promises.unlink should be a function');
    assert.strictEqual(typeof gracefulFs.promises.rm, 'function', 'promises.rm should be a function');

    // 2. Asynchronous writeFile and readFile with string and buffer encodings
    {
      const filePath = path.join(testRoot, 'payload.txt');
      const payload = 'Graceful filesystem promise-based content';
      await writeFileAsync(filePath, payload, 'utf8');

      const readText = await readFileAsync(filePath, 'utf8');
      assert.strictEqual(readText, payload, 'Read text should match written payload');

      const readBuffer = await readFileAsync(filePath, null);
      assert.ok(Buffer.isBuffer(readBuffer), 'Reading with null encoding should return a Buffer');
      assert.strictEqual(readBuffer.toString('utf8'), payload, 'Buffer content should match payload');
    }

    // 3. Rejection with ENOENT on non-existent file
    {
      const missingPath = path.join(testRoot, 'does_not_exist.txt');
      let caughtError = null;
      try {
        await readFileAsync(missingPath, 'utf8');
      } catch (err) {
        caughtError = err;
      }
      assert.ok(caughtError !== null, 'Reading non-existent file should reject');
      assert.strictEqual(caughtError.code, 'ENOENT', 'Error code should be ENOENT');
    }

    // 4. Directory creation and directory listing
    {
      const subDir = path.join(testRoot, 'nested', 'level');
      await makeDirectoryAsync(subDir, { recursive: true });

      const fileA = path.join(subDir, 'fileA.txt');
      const fileB = path.join(subDir, 'fileB.txt');
      await writeFileAsync(fileA, 'dataA');
      await writeFileAsync(fileB, 'dataB');

      const entries = await readDirectoryAsync(subDir);
      assert.ok(Array.isArray(entries), 'readdir should return an array');
      assert.ok(entries.includes('fileA.txt'), 'Directory should include fileA.txt');
      assert.ok(entries.includes('fileB.txt'), 'Directory should include fileB.txt');
    }

    // 5. File stats retrieval and type verification
    {
      const statsFile = path.join(testRoot, 'stats_test.txt');
      const content = '1234567890';
      await writeFileAsync(statsFile, content, 'utf8');

      const stats = await getFileStatsAsync(statsFile);
      assert.ok(stats.isFile(), 'stat should identify path as a file');
      assert.strictEqual(stats.size, 10, 'stat.size should match byte count');
    }

    // 6. File deletion and recursive directory removal
    {
      const deleteDir = path.join(testRoot, 'to_remove');
      await makeDirectoryAsync(deleteDir, { recursive: true });
      const deleteFile = path.join(deleteDir, 'temp.txt');
      await writeFileAsync(deleteFile, 'temp content', 'utf8');

      await removeFileAsync(deleteFile);
      let fileMissing = false;
      try {
        await getFileStatsAsync(deleteFile);
      } catch (err) {
        fileMissing = err.code === 'ENOENT';
      }
      assert.ok(fileMissing, 'File should be removed by unlink');

      await removeDirectoryAsync(deleteDir);
      let dirMissing = false;
      try {
        await getFileStatsAsync(deleteDir);
      } catch (err) {
        dirMissing = err.code === 'ENOENT';
      }
      assert.ok(dirMissing, 'Directory tree should be removed by rm');
    }

    console.log('All graceful-fs.promises contract assertions passed successfully.');
  } finally {
    try {
      await removeDirectoryAsync(testRoot);
    } catch (_) {}
  }
}

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

오리진 시더

익명