CodeSampleX

Exemplo

cosmiconfig 9.0.2: search and load configuration file using cosmiconfig

Amostra verificada para npm cosmiconfig 9.0.2: search and load configuration file using cosmiconfig. O contrato rodou em node 22 · linux alpine/x64 · docker…

sha256:26b7509992f940548573383616ac6d1641f47af2e96d95ce95cbd6beb7bc049c

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-23

Caso

HOW
Objetivo
search and load configuration file using cosmiconfig
Pacotes
Símbolos
  • cosmiconfig
  • cosmiconfigSync
Criado
2026-08-23T15:50:54Z

Contrato

  1. cosmiconfig and cosmiconfigSync return explorer instances with search, load, clearLoadCache, clearSearchCache, and clearCaches methods
  2. default searchStrategy is none which searches only the starting directory without parent directory traversal
  3. searchStrategy project searches upward through parent directories until configuration is found
  4. cosmiconfigSync search with searchStrategy project synchronously searches upward through parent directories
  5. specifying stopDir implicitly sets searchStrategy to global and traverses parent directories up to stopDir
  6. specifying stopDir with searchStrategy project or none throws an error
  7. cosmiconfig load parses YAML configuration files asynchronously
  8. cosmiconfigSync load parses CommonJS configuration files synchronously
  9. cosmiconfig load supports custom loaders for non-standard file extensions
  10. cosmiconfig search returns null when no configuration file is found
  11. cosmiconfig caches loaded configuration and returns fresh copies after clearCaches

Arquivos

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.mjs
  • test/fixtures/custom.conf
  • test/fixtures/js-config/sampleapp.config.cjs
  • test/fixtures/json-config/.sampleapprc.json
  • test/fixtures/nested/.sampleapprc.json
  • test/fixtures/yaml-config/.sampleapprc.yaml

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: search and load configuration file using cosmiconfig
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/cosmiconfig@9.0.2
Demonstrate these symbols/APIs:
  - cosmiconfig
  - cosmiconfigSync

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:0d10841381d388240bf5b39447d199fd763f14841e259f27500d0b69c4f98dc2","contract":["cosmiconfig and cosmiconfigSync return explorer instances with search, load, clearLoadCache, clearSearchCache, and clearCaches methods","default searchStrategy is none which searches only the starting directory without parent directory traversal","searchStrategy project searches upward through parent directories until configuration is found","cosmiconfigSync search with searchStrategy project synchronously searches upward through parent directories","specifying stopDir implicitly sets searchStrategy to global and traverses parent directories up to stopDir","specifying stopDir with searchStrategy project or none throws an error","cosmiconfig load parses YAML configuration files asynchronously","cosmiconfigSync load parses CommonJS configuration files synchronously","cosmiconfig load supports custom loaders for non-standard file extensions","cosmiconfig search returns null when no configuration file is found","cosmiconfig caches loaded configuration and returns fresh copies after clearCaches"],"goal":"search and load configuration file using cosmiconfig","kind":"HOW","packages":["pkg:npm/cosmiconfig@9.0.2"],"schemaVersion":1,"symbols":["cosmiconfig","cosmiconfigSync"]},"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/cosmiconfig@9.0.2"],"schemaVersion":1,"subject":"pkg:npm/cosmiconfig@9.0.2","symbols":["cosmiconfig","cosmiconfigSync"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-cosmiconfig",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-cosmiconfig",
      "version": "1.0.0",
      "dependencies": {
        "cosmiconfig": "9.0.2"
      }
    },
    "node_modules/@babel/code-frame": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
      "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-validator-identifier": "^7.29.7",
        "js-tokens": "^4.0.0",
        "picocolors": "^1.1.1"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-validator-identifier": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/argparse": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
      "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
      "license": "Python-2.0"
    },
    "node_modules/callsites": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
      "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/cosmiconfig": {
      "version": "9.0.2",
      "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz",
      "integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==",
      "license": "MIT",
      "dependencies": {
        "env-paths": "^2.2.1",
        "import-fresh": "^3.3.0",
        "js-yaml": "^4.1.0",
        "parse-json": "^5.2.0"
      },
      "engines": {
        "node": ">=14"
      },
      "funding": {
        "url": "https://github.com/sponsors/d-fischer"
      },
      "peerDependencies": {
        "typescript": ">=4.9.5"
      },
      "peerDependenciesMeta": {
        "typescript": {
          "optional": true
        }
      }
    },
    "node_modules/env-paths": {
      "version": "2.2.1",
      "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
      "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/error-ex": {
      "version": "1.3.4",
      "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",
      "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==",
      "license": "MIT",
      "dependencies": {
        "is-arrayish": "^0.2.1"
      }
    },
    "node_modules/import-fresh": {
      "version": "3.3.1",
      "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
      "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
      "license": "MIT",
      "dependencies": {
        "parent-module": "^1.0.0",
        "resolve-from": "^4.0.0"
      },
      "engines": {
        "node": ">=6"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/is-arrayish": {
      "version": "0.2.1",
      "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
      "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",
      "license": "MIT"
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/js-yaml": {
      "version": "4.3.1",
      "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
      "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/puzrin"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/nodeca"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "argparse": "^2.0.1"
      },
      "bin": {
        "js-yaml": "bin/js-yaml.js"
      }
    },
    "node_modules/json-parse-even-better-errors": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
      "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
      "license": "MIT"
    },
    "node_modules/lines-and-columns": {
      "version": "1.2.4",
      "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
      "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
      "license": "MIT"
    },
    "node_modules/parent-module": {
      "version": "1.0.1",
      "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
      "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
      "license": "MIT",
      "dependencies": {
        "callsites": "^3.0.0"
      },
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/parse-json": {
      "version": "5.2.0",
      "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
      "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",
      "license": "MIT",
      "dependencies": {
        "@babel/code-frame": "^7.0.0",
        "error-ex": "^1.3.1",
        "json-parse-even-better-errors": "^2.3.0",
        "lines-and-columns": "^1.1.6"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    },
    "node_modules/resolve-from": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
      "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
      "license": "MIT",
      "engines": {
        "node": ">=4"
      }
    }
  }
}
package.json
{
  "name": "sample-cosmiconfig",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "cosmiconfig": "9.0.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "search and load configuration file using cosmiconfig",
  "kind": "HOW",
  "packages": [
    "pkg:npm/cosmiconfig@9.0.2"
  ],
  "symbols": [
    "cosmiconfig",
    "cosmiconfigSync"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { cosmiconfig, cosmiconfigSync } from 'cosmiconfig';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const fixturesDir = path.join(__dirname, 'fixtures');

// 1. cosmiconfig and cosmiconfigSync return explorer instances with search, load, clearLoadCache, clearSearchCache, and clearCaches methods
{
  const explorer = cosmiconfig('sampleapp');
  assert.equal(typeof explorer.search, 'function');
  assert.equal(typeof explorer.load, 'function');
  assert.equal(typeof explorer.clearLoadCache, 'function');
  assert.equal(typeof explorer.clearSearchCache, 'function');
  assert.equal(typeof explorer.clearCaches, 'function');

  const explorerSync = cosmiconfigSync('sampleapp');
  assert.equal(typeof explorerSync.search, 'function');
  assert.equal(typeof explorerSync.load, 'function');
  assert.equal(typeof explorerSync.clearLoadCache, 'function');
  assert.equal(typeof explorerSync.clearSearchCache, 'function');
  assert.equal(typeof explorerSync.clearCaches, 'function');
}

// 2. default searchStrategy is none which searches only the starting directory without parent directory traversal
{
  const explorer = cosmiconfig('sampleapp');
  const deepDir = path.join(fixturesDir, 'nested', 'sub', 'sub2');
  const directDir = path.join(fixturesDir, 'nested');

  const deepResult = await explorer.search(deepDir);
  assert.equal(deepResult, null);

  const directResult = await explorer.search(directDir);
  assert.ok(directResult !== null);
  assert.equal(typeof directResult.filepath, 'string');
  assert.ok(directResult.filepath.endsWith(path.join('nested', '.sampleapprc.json')));
  assert.deepEqual(directResult.config, {
    name: 'nested-app',
    port: 5000
  });
}

// 3. searchStrategy project searches upward through parent directories until configuration is found
{
  const explorer = cosmiconfig('sampleapp', { searchStrategy: 'project' });
  const deepDir = path.join(fixturesDir, 'nested', 'sub', 'sub2');
  const result = await explorer.search(deepDir);

  assert.ok(result !== null);
  assert.deepEqual(result.config, {
    name: 'nested-app',
    port: 5000
  });
}

// 4. cosmiconfigSync search with searchStrategy project synchronously searches upward through parent directories
{
  const explorerSync = cosmiconfigSync('sampleapp', { searchStrategy: 'project' });
  const deepDir = path.join(fixturesDir, 'nested', 'sub', 'sub2');
  const result = explorerSync.search(deepDir);

  assert.ok(result !== null);
  assert.deepEqual(result.config, {
    name: 'nested-app',
    port: 5000
  });
}

// 5. specifying stopDir implicitly sets searchStrategy to global and traverses parent directories up to stopDir
{
  const explorer = cosmiconfig('sampleapp', { stopDir: fixturesDir });
  const deepDir = path.join(fixturesDir, 'nested', 'sub', 'sub2');
  const result = await explorer.search(deepDir);

  assert.ok(result !== null);
  assert.deepEqual(result.config, {
    name: 'nested-app',
    port: 5000
  });
}

// 6. specifying stopDir with searchStrategy project or none throws an error
{
  assert.throws(
    () => {
      cosmiconfig('sampleapp', { searchStrategy: 'project', stopDir: fixturesDir });
    },
    {
      name: 'Error',
      message: 'Can not supply `stopDir` option with `searchStrategy` other than "global"'
    }
  );

  assert.throws(
    () => {
      cosmiconfigSync('sampleapp', { searchStrategy: 'none', stopDir: fixturesDir });
    },
    {
      name: 'Error',
      message: 'Can not supply `stopDir` option with `searchStrategy` other than "global"'
    }
  );
}

// 7. cosmiconfig load parses YAML configuration files asynchronously
{
  const explorer = cosmiconfig('sampleapp');
  const yamlPath = path.join(fixturesDir, 'yaml-config', '.sampleapprc.yaml');
  const result = await explorer.load(yamlPath);

  assert.ok(result !== null);
  assert.equal(result.filepath, yamlPath);
  assert.deepEqual(result.config, {
    name: 'yaml-app',
    port: 3000,
    features: {
      auth: false
    }
  });
}

// 8. cosmiconfigSync load parses CommonJS configuration files synchronously
{
  const explorerSync = cosmiconfigSync('sampleapp');
  const cjsPath = path.join(fixturesDir, 'js-config', 'sampleapp.config.cjs');
  const result = explorerSync.load(cjsPath);

  assert.ok(result !== null);
  assert.equal(result.filepath, cjsPath);
  assert.deepEqual(result.config, {
    name: 'cjs-app',
    port: 9000,
    features: {
      auth: true
    }
  });
}

// 9. cosmiconfig load supports custom loaders for non-standard file extensions
{
  const customLoader = (filepath, content) => {
    const lines = content.trim().split('\n');
    const parsed = {};
    for (const line of lines) {
      const [k, v] = line.split('=');
      parsed[k.trim()] = v.trim();
    }
    return parsed;
  };

  const explorer = cosmiconfig('sampleapp', {
    loaders: {
      '.conf': customLoader
    }
  });

  const customConfPath = path.join(fixturesDir, 'custom.conf');
  const result = await explorer.load(customConfPath);

  assert.ok(result !== null);
  assert.equal(result.filepath, customConfPath);
  assert.deepEqual(result.config, {
    key: 'custom-value'
  });
}

// 10. cosmiconfig search returns null when no configuration file is found
{
  const explorer = cosmiconfig('sampleapp');
  const emptyDir = path.join(fixturesDir, 'empty-dir');
  const result = await explorer.search(emptyDir);

  assert.equal(result, null);
}

// 11. cosmiconfig caches loaded configuration and returns fresh copies after clearCaches
{
  const explorer = cosmiconfig('sampleapp');
  const jsonPath = path.join(fixturesDir, 'json-config', '.sampleapprc.json');
  const result1 = await explorer.load(jsonPath);
  const result2 = await explorer.load(jsonPath);

  assert.equal(result1, result2);

  explorer.clearCaches();
  const result3 = await explorer.load(jsonPath);

  assert.notEqual(result1, result3);
  assert.deepEqual(result1.config, result3.config);
}
test/fixtures/custom.conf
key=custom-value
test/fixtures/js-config/sampleapp.config.cjs
module.exports = {
  name: "cjs-app",
  port: 9000,
  features: {
    auth: true
  }
};
test/fixtures/json-config/.sampleapprc.json
{
  "name": "json-app",
  "port": 8080,
  "features": {
    "auth": true
  }
}
test/fixtures/nested/.sampleapprc.json
{
  "name": "nested-app",
  "port": 5000
}
test/fixtures/yaml-config/.sampleapprc.yaml
name: yaml-app
port: 3000
features:
  auth: false

Seeder de origem

anônimo