CodeSampleX

示例

@humanfs/core 0.19.2: delegate file system operations and log method calls using Hfs from @humanfs/core

已验证示例 — npm @humanfs/core 0.19.2: delegate file system operations and log method calls using Hfs from @humanfs/core. contract 在 node 22 · linux alpine/x64 …

sha256:500d0627789adbcff368a8c9dc31abb4a72f5259774a229000c5637ae2e9bc24

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

案例

HOW
目标
delegate file system operations and log method calls using Hfs from @humanfs/core
包
符号
  • Hfs
  • Hfs.prototype.logEnd
  • Hfs.prototype.logStart
  • Hfs.prototype.resetImpl
  • Hfs.prototype.setImpl
  • Hfs.prototype.text
  • Hfs.prototype.walk
  • Hfs.prototype.write
创建时间
2026-08-28T03:03:15Z

契约

  1. Hfs creates an instance with a custom base implementation and confirms isBaseImpl
  2. Hfs write encodes string data and text decodes underlying bytes via the implementation
  3. Hfs logStart records method calls with arguments and logEnd retrieves the logged entries
  4. Hfs setImpl replaces active implementation and resetImpl restores the base implementation
  5. Hfs walk traverses directory structures depth-first and applies entry and directory filters
  6. Hfs rejects invalid path arguments and empty log names with TypeError

文件

  • 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: delegate file system operations and log method calls using Hfs from @humanfs/core
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40humanfs/core@0.19.2
Demonstrate these symbols/APIs:
  - Hfs
  - Hfs.prototype.logEnd
  - Hfs.prototype.logStart
  - Hfs.prototype.resetImpl
  - Hfs.prototype.setImpl
  - Hfs.prototype.text
  - Hfs.prototype.walk
  - Hfs.prototype.write

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:c9d751868113b7dce96ae4ed50b12556fcb28a52b15ef564b59b78c3dcb23c39","contract":["Hfs creates an instance with a custom base implementation and confirms isBaseImpl","Hfs write encodes string data and text decodes underlying bytes via the implementation","Hfs logStart records method calls with arguments and logEnd retrieves the logged entries","Hfs setImpl replaces active implementation and resetImpl restores the base implementation","Hfs walk traverses directory structures depth-first and applies entry and directory filters","Hfs rejects invalid path arguments and empty log names with TypeError"],"goal":"delegate file system operations and log method calls using Hfs from @humanfs/core","kind":"HOW","packages":["pkg:npm/%40humanfs/core@0.19.2"],"schemaVersion":1,"symbols":["Hfs","Hfs.prototype.logEnd","Hfs.prototype.logStart","Hfs.prototype.resetImpl","Hfs.prototype.setImpl","Hfs.prototype.text","Hfs.prototype.walk","Hfs.prototype.write"]},"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/%40humanfs/core@0.19.2"],"schemaVersion":1,"subject":"pkg:npm/%40humanfs/core@0.19.2","symbols":["Hfs","Hfs.prototype.logEnd","Hfs.prototype.logStart","Hfs.prototype.resetImpl","Hfs.prototype.setImpl","Hfs.prototype.text","Hfs.prototype.walk","Hfs.prototype.write"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-humanfs-core-hfs",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-humanfs-core-hfs",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@humanfs/core": "0.19.2"
      }
    },
    "node_modules/@humanfs/core": {
      "version": "0.19.2",
      "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz",
      "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==",
      "license": "Apache-2.0",
      "dependencies": {
        "@humanfs/types": "^0.15.0"
      },
      "engines": {
        "node": ">=18.18.0"
      }
    },
    "node_modules/@humanfs/types": {
      "version": "0.15.0",
      "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz",
      "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==",
      "license": "Apache-2.0",
      "engines": {
        "node": ">=18.18.0"
      }
    }
  }
}
package.json
{
  "name": "sample-humanfs-core-hfs",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for Hfs from @humanfs/core",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@humanfs/core": "0.19.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "delegate file system operations and log method calls using Hfs from @humanfs/core",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40humanfs/core@0.19.2"
  ],
  "symbols": [
    "Hfs",
    "Hfs.prototype.logEnd",
    "Hfs.prototype.logStart",
    "Hfs.prototype.resetImpl",
    "Hfs.prototype.setImpl",
    "Hfs.prototype.text",
    "Hfs.prototype.walk",
    "Hfs.prototype.write"
  ]
}
src/index.js
/**
 * @fileoverview In-memory implementation and helper for @humanfs/core Hfs.
 */

/**
 * Loads Hfs from @humanfs/core via dynamic import.
 * @returns {Promise<typeof import('@humanfs/core').Hfs>}
 */
async function loadHfs() {
  const { Hfs } = await import('@humanfs/core');
  return Hfs;
}

/**
 * A minimal in-memory file system implementation satisfying HfsImpl.
 */
class MemoryHfsImpl {
  constructor() {
    /** @type {Map<string, Uint8Array>} */
    this.files = new Map();
    /** @type {Set<string>} */
    this.directories = new Set(['/']);
  }

  /**
   * Writes byte contents to a file path.
   * @param {string} filePath
   * @param {Uint8Array} contents
   */
  async write(filePath, contents) {
    const normalized = normalizePath(filePath);
    this.files.set(normalized, contents);
    ensureParentDirs(this.directories, normalized);
  }

  /**
   * Reads byte contents of a file path.
   * @param {string} filePath
   * @returns {Promise<Uint8Array|undefined>}
   */
  async bytes(filePath) {
    const normalized = normalizePath(filePath);
    return this.files.get(normalized);
  }

  /**
   * Checks if a file exists.
   * @param {string} filePath
   * @returns {Promise<boolean>}
   */
  async isFile(filePath) {
    const normalized = normalizePath(filePath);
    return this.files.has(normalized);
  }

  /**
   * Checks if a directory exists.
   * @param {string} dirPath
   * @returns {Promise<boolean>}
   */
  async isDirectory(dirPath) {
    const normalized = normalizePath(dirPath);
    return this.directories.has(normalized);
  }

  /**
   * Creates a directory.
   * @param {string} dirPath
   */
  async createDirectory(dirPath) {
    const normalized = normalizePath(dirPath);
    this.directories.add(normalized);
    ensureParentDirs(this.directories, normalized);
  }

  /**
   * Deletes a file.
   * @param {string} filePath
   * @returns {Promise<boolean>}
   */
  async delete(filePath) {
    const normalized = normalizePath(filePath);
    return this.files.delete(normalized) || this.directories.delete(normalized);
  }

  /**
   * Lists entries in a directory.
   * @param {string} dirPath
   * @returns {Promise<Array<{name: string, isDirectory: boolean, isFile: boolean, isSymlink: boolean}>>}
   */
  async list(dirPath) {
    const normalized = normalizePath(dirPath);
    const prefix = normalized === '/' ? '/' : `${normalized}/`;
    const entries = new Map();

    for (const d of this.directories) {
      if (d !== normalized && d.startsWith(prefix)) {
        const rest = d.slice(prefix.length);
        const top = rest.split('/')[0];
        if (top && !entries.has(top)) {
          entries.set(top, {
            name: top,
            isDirectory: true,
            isFile: false,
            isSymlink: false
          });
        }
      }
    }

    for (const f of this.files.keys()) {
      if (f.startsWith(prefix)) {
        const rest = f.slice(prefix.length);
        const parts = rest.split('/');
        if (parts.length === 1) {
          entries.set(parts[0], {
            name: parts[0],
            isDirectory: false,
            isFile: true,
            isSymlink: false
          });
        } else {
          const top = parts[0];
          if (!entries.has(top)) {
            entries.set(top, {
              name: top,
              isDirectory: true,
              isFile: false,
              isSymlink: false
            });
          }
        }
      }
    }

    return Array.from(entries.values());
  }
}

/**
 * Normalizes a path string.
 * @param {string|URL} p
 * @returns {string}
 */
function normalizePath(p) {
  const str = p instanceof URL ? p.pathname : String(p);
  const clean = str.replace(/\\/g, '/').replace(/\/+/g, '/');
  return clean.startsWith('/') ? clean : `/${clean}`;
}

/**
 * Ensures parent directories are tracked.
 * @param {Set<string>} dirSet
 * @param {string} path
 */
function ensureParentDirs(dirSet, path) {
  const parts = path.split('/').filter(Boolean);
  let cur = '';
  for (let i = 0; i < parts.length - 1; i++) {
    cur += `/${parts[i]}`;
    dirSet.add(cur);
  }
}

/**
 * Creates an Hfs instance backed by an in-memory implementation.
 * @returns {Promise<Hfs>}
 */
async function createMemoryHfs() {
  const Hfs = await loadHfs();
  const impl = new MemoryHfsImpl();
  return new Hfs({ impl });
}

module.exports = {
  loadHfs,
  MemoryHfsImpl,
  createMemoryHfs
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { Hfs } from '@humanfs/core';

const require = createRequire(import.meta.url);
const { loadHfs, MemoryHfsImpl, createMemoryHfs } = require('../src/index.js');

// 1. Hfs creates an instance with a custom base implementation and confirms isBaseImpl
{
  const hfs = await createMemoryHfs();
  assert.equal(typeof hfs, 'object');
  assert.equal(hfs.isBaseImpl(), true);

  const directHfs = new Hfs({ impl: new MemoryHfsImpl() });
  assert.equal(directHfs.isBaseImpl(), true);
}

// 2. Hfs write encodes string data and text decodes underlying bytes via the implementation
{
  const hfs = await createMemoryHfs();
  await hfs.write('/docs/hello.txt', 'Hello HumanFS!');
  const content = await hfs.text('/docs/hello.txt');
  assert.equal(content, 'Hello HumanFS!');

  const bytes = await hfs.bytes('/docs/hello.txt');
  assert.equal(new TextDecoder().decode(bytes), 'Hello HumanFS!');
}

// 3. Hfs logStart records method calls with arguments and logEnd retrieves the logged entries
{
  const hfs = await createMemoryHfs();
  hfs.logStart('session');

  await hfs.write('/logs/app.log', 'event: ready');
  const readBack = await hfs.text('/logs/app.log');
  assert.equal(readBack, 'event: ready');

  const logs = hfs.logEnd('session');
  assert.equal(Array.isArray(logs), true);
  assert.equal(logs.length >= 2, true);

  const writeCall = logs.find(entry => entry.data.methodName === 'write');
  assert.ok(writeCall);
  assert.equal(writeCall.data.args[0], '/logs/app.log');

  const textCall = logs.find(entry => entry.data.methodName === 'text');
  assert.ok(textCall);
  assert.equal(textCall.data.args[0], '/logs/app.log');

  assert.throws(() => hfs.logEnd('session'), Error);
}

// 4. Hfs setImpl replaces active implementation and resetImpl restores the base implementation
{
  const hfs = await createMemoryHfs();
  await hfs.write('/shared.txt', 'base data');
  assert.equal(await hfs.text('/shared.txt'), 'base data');

  const altImpl = new MemoryHfsImpl();
  hfs.setImpl(altImpl);
  assert.equal(hfs.isBaseImpl(), false);

  assert.equal(await hfs.text('/shared.txt'), undefined);
  await hfs.write('/alt-file.txt', 'alt data');
  assert.equal(await hfs.text('/alt-file.txt'), 'alt data');

  hfs.resetImpl();
  assert.equal(hfs.isBaseImpl(), true);
  assert.equal(await hfs.text('/shared.txt'), 'base data');
  assert.equal(await hfs.text('/alt-file.txt'), undefined);
}

// 5. Hfs walk traverses directory structures depth-first and applies entry and directory filters
{
  const hfs = await createMemoryHfs();
  await hfs.write('/project/src/index.js', 'console.log("index");');
  await hfs.write('/project/src/util.js', 'console.log("util");');
  await hfs.write('/project/tests/test.js', 'console.log("test");');
  await hfs.write('/project/docs/readme.md', '# Readme');

  const allWalked = [];
  for await (const entry of hfs.walk('/project')) {
    allWalked.push(entry.path);
  }
  assert.ok(allWalked.includes('src'));
  assert.ok(allWalked.includes('src/index.js'));
  assert.ok(allWalked.includes('src/util.js'));
  assert.ok(allWalked.includes('tests/test.js'));
  assert.ok(allWalked.includes('docs/readme.md'));

  const filteredEntries = [];
  for await (const entry of hfs.walk('/project', {
    entryFilter: e => e.path.endsWith('.js')
  })) {
    filteredEntries.push(entry.path);
  }
  assert.deepEqual(
    filteredEntries.sort(),
    ['src/index.js', 'src/util.js', 'tests/test.js'].sort()
  );

  const skippedDocs = [];
  for await (const entry of hfs.walk('/project', {
    directoryFilter: e => e.name !== 'docs'
  })) {
    skippedDocs.push(entry.path);
  }
  assert.equal(skippedDocs.includes('docs/readme.md'), false);
}

// 6. Hfs rejects invalid path arguments and empty log names with TypeError
{
  const hfs = await createMemoryHfs();
  await assert.rejects(async () => hfs.write('', 'content'), TypeError);
  await assert.rejects(async () => hfs.text(null), TypeError);
  assert.throws(() => hfs.logStart(''), TypeError);
}

// 7. Helper loadHfs resolves Hfs class
{
  const LoadedHfs = await loadHfs();
  assert.equal(LoadedHfs, Hfs);
}

console.log('All contract assertions passed.');

原始种子者

匿名