CodeSampleX

Beispiel

pkg-dir 4.2.0: find root directory of a node package using pkg-dir

Verifiziertes Beispiel für npm pkg-dir 4.2.0: find root directory of a node package using pkg-dir. Der Vertrag lief auf node 22 · linux alpine/x64 · docker…

sha256:d55c898967ba062e3d26725db337e936885696b27f5ddbe862106cf5b974a8d5

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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-27

Fall

HOW
Ziel
find root directory of a node package using pkg-dir
Pakete
Symbole
  • pkgDir
  • pkgDir.sync
Umgebung
node 22.23.2
Erstellt
2026-08-27T14:09:33Z

Contract

  1. pkgDir asynchronously finds the root directory of a Node.js package containing package.json from a nested directory
  2. pkgDir.sync synchronously finds the root directory of a Node.js package containing package.json from a nested directory
  3. pkgDir resolves to undefined when no package.json exists in the directory hierarchy
  4. pkgDir.sync returns undefined when no package.json exists in the directory hierarchy
  5. pkgDir and pkgDir.sync resolve the current package root when cwd is omitted

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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: find root directory of a node package using pkg-dir
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/pkg-dir@4.2.0
Demonstrate these symbols/APIs:
  - pkgDir
  - pkgDir.sync

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:06505393dbe6dd4751911f3dad9231bf93f91dd33925b869305674cd70ced682","contract":["pkgDir asynchronously finds the root directory of a Node.js package containing package.json from a nested directory","pkgDir.sync synchronously finds the root directory of a Node.js package containing package.json from a nested directory","pkgDir resolves to undefined when no package.json exists in the directory hierarchy","pkgDir.sync returns undefined when no package.json exists in the directory hierarchy","pkgDir and pkgDir.sync resolve the current package root when cwd is omitted"],"goal":"find root directory of a node package using pkg-dir","kind":"HOW","packages":["pkg:npm/pkg-dir@4.2.0"],"schemaVersion":1,"symbols":["pkgDir","pkgDir.sync"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/pkg-dir@4.2.0"],"schemaVersion":1,"subject":"pkg:npm/pkg-dir@4.2.0","symbols":["pkgDir","pkgDir.sync"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-pkg-dir",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-pkg-dir",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "pkg-dir": "4.2.0"
      }
    },
    "node_modules/find-up": {
      "version": "4.1.0",
      "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
      "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
      "license": "MIT",
      "dependencies": {
        "locate-path": "^5.0.0",
        "path-exists": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/locate-path": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
      "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
      "license": "MIT",
      "dependencies": {
        "p-locate": "^4.1.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/p-limit": {
      "version": "2.3.0",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
      "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
      "license": "MIT",
      "dependencies": {
        "p-try": "^2.0.0"
      },
      "engines": {
        "node": ">=6"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/p-locate": {
      "version": "4.1.0",
      "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
      "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
      "license": "MIT",
      "dependencies": {
        "p-limit": "^2.2.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/p-try": {
      "version": "2.2.0",
      "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
      "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/path-exists": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
      "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/pkg-dir": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
      "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
      "license": "MIT",
      "dependencies": {
        "find-up": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    }
  }
}
package.json
{
  "name": "sample-pkg-dir",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "pkg-dir": "4.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "find root directory of a node package using pkg-dir",
  "kind": "HOW",
  "packages": [
    "pkg:npm/pkg-dir@4.2.0"
  ],
  "symbols": [
    "pkgDir",
    "pkgDir.sync"
  ]
}
src/index.mjs
import pkgDir from 'pkg-dir';

/**
 * Asynchronously finds the root directory of a Node.js project or npm package.
 * @param {string} [cwd] - Directory to start searching from (defaults to process.cwd()).
 * @returns {Promise<string | undefined>}
 */
export async function findPackageRoot(cwd) {
  return await pkgDir(cwd);
}

/**
 * Synchronously finds the root directory of a Node.js project or npm package.
 * @param {string} [cwd] - Directory to start searching from (defaults to process.cwd()).
 * @returns {string | undefined}
 */
export function findPackageRootSync(cwd) {
  return pkgDir.sync(cwd);
}

export { pkgDir };
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import pkgDir from 'pkg-dir';
import { findPackageRoot, findPackageRootSync } from '../src/index.mjs';

const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'csx-pkg-dir-contract-'));
const projectDir = path.join(tempRoot, 'nested-project');
const deepDir = path.join(projectDir, 'src', 'features', 'deep');
const emptyDir = path.join(tempRoot, 'isolated-empty', 'deep');

try {
  // Create nested project directory structure with package.json
  fs.mkdirSync(deepDir, { recursive: true });
  fs.writeFileSync(
    path.join(projectDir, 'package.json'),
    JSON.stringify({ name: 'nested-dummy-pkg', version: '1.0.0' }, null, 2),
    'utf8'
  );

  // Create isolated empty directory structure with no package.json
  fs.mkdirSync(emptyDir, { recursive: true });

  const canonicalProjectDir = fs.realpathSync(projectDir);

  // Contract 1: pkgDir asynchronously finds the root directory of a Node.js package containing package.json from a nested directory
  {
    const rootFromDeep = await pkgDir(deepDir);
    assert.notEqual(rootFromDeep, undefined, 'pkgDir should find root from deep subdirectory');
    assert.equal(fs.realpathSync(rootFromDeep), canonicalProjectDir);

    const rootFromProject = await pkgDir(projectDir);
    assert.notEqual(rootFromProject, undefined, 'pkgDir should find root from project directory');
    assert.equal(fs.realpathSync(rootFromProject), canonicalProjectDir);
  }

  // Contract 2: pkgDir.sync synchronously finds the root directory of a Node.js package containing package.json from a nested directory
  {
    const rootSyncFromDeep = pkgDir.sync(deepDir);
    assert.notEqual(rootSyncFromDeep, undefined, 'pkgDir.sync should find root from deep subdirectory');
    assert.equal(fs.realpathSync(rootSyncFromDeep), canonicalProjectDir);

    const rootSyncFromProject = pkgDir.sync(projectDir);
    assert.notEqual(rootSyncFromProject, undefined, 'pkgDir.sync should find root from project directory');
    assert.equal(fs.realpathSync(rootSyncFromProject), canonicalProjectDir);
  }

  // Contract 3: pkgDir resolves to undefined when no package.json exists in the directory hierarchy
  {
    const noRootAsync = await pkgDir(emptyDir);
    assert.equal(noRootAsync, undefined, 'pkgDir should resolve undefined when no package.json is present');
  }

  // Contract 4: pkgDir.sync returns undefined when no package.json exists in the directory hierarchy
  {
    const noRootSync = pkgDir.sync(emptyDir);
    assert.equal(noRootSync, undefined, 'pkgDir.sync should return undefined when no package.json is present');
  }

  // Contract 5: pkgDir and pkgDir.sync resolve the current package root when cwd is omitted
  {
    const currentRootAsync = await pkgDir();
    assert.notEqual(currentRootAsync, undefined, 'pkgDir() should find current project root');
    assert.equal(typeof currentRootAsync, 'string');
    assert.equal(fs.existsSync(path.join(currentRootAsync, 'package.json')), true);

    const currentRootSync = pkgDir.sync();
    assert.notEqual(currentRootSync, undefined, 'pkgDir.sync() should find current project root');
    assert.equal(typeof currentRootSync, 'string');
    assert.equal(currentRootAsync, currentRootSync);
    assert.equal(fs.existsSync(path.join(currentRootSync, 'package.json')), true);

    // Helper functions from src/index.mjs
    const helperAsync = await findPackageRoot(deepDir);
    assert.equal(fs.realpathSync(helperAsync), canonicalProjectDir);

    const helperSync = findPackageRootSync(deepDir);
    assert.equal(fs.realpathSync(helperSync), canonicalProjectDir);
  }

  console.log('All pkg-dir contract tests passed successfully.');
} finally {
  try {
    fs.rmSync(tempRoot, { recursive: true, force: true });
  } catch {
    // Ignore cleanup error
  }
}

Ursprungs-Seeder

anonym