CodeSampleX

Exemplo

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

Amostra verificada para npm @humanfs/core 0.19.2: delegate file system operations and log method calls using Hfs from @humanfs/core. O contrato rodou em node…

sha256:500d0627789adbcff368a8c9dc31abb4a72f5259774a229000c5637ae2e9bc24

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
delegate file system operations and log method calls using Hfs from @humanfs/core
Pacotes
Símbolos
  • Hfs
  • Hfs.prototype.logEnd
  • Hfs.prototype.logStart
  • Hfs.prototype.resetImpl
  • Hfs.prototype.setImpl
  • Hfs.prototype.text
  • Hfs.prototype.walk
  • Hfs.prototype.write
Criado
2026-08-28T03:03:15Z

Contrato

  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

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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.');

Seeder de origem

anônimo