CodeSampleX

示例

dotenv 16.6.1

已验证示例 — npm dotenv 16.6.1. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and…

sha256:8a33b2b2c39e29aa246afb7822c10f89de4808af93e17b065b35f3cd8d6fd342

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

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
1
声明的环境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

验证运行环境

环境 契约 阶段 运行日期
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
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-08

案例

HOW
目标
verify pkg:npm/dotenv@16.6.1
包
环境
node 22.23.2
创建时间
2026-08-23T06:00:25Z

契约

  1. dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and double-quoted values
  2. dotenv.parse strips leading export keywords and inline comments on unquoted values
  3. dotenv.parse expands newline and carriage return escape sequences in double-quoted strings
  4. dotenv.populate sets environment variables on target object without overwriting existing keys by default
  5. dotenv.populate with override set to true overwrites existing target keys
  6. dotenv.populate throws an error when parsed argument is not an object
  7. dotenv.configDotenv loads variables from specified file paths into target processEnv
  8. dotenv.configDotenv returns an error object when target path does not exist

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 pkg:npm/dotenv@16.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/dotenv@16.6.1

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:03dd128a17047f836ab37087b7449633b59057548bac2eec8abc6587a4edfac8","contract":["dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and double-quoted values","dotenv.parse strips leading export keywords and inline comments on unquoted values","dotenv.parse expands newline and carriage return escape sequences in double-quoted strings","dotenv.populate sets environment variables on target object without overwriting existing keys by default","dotenv.populate with override set to true overwrites existing target keys","dotenv.populate throws an error when parsed argument is not an object","dotenv.configDotenv loads variables from specified file paths into target processEnv","dotenv.configDotenv returns an error object when target path does not exist"],"goal":"verify pkg:npm/dotenv@16.6.1","kind":"HOW","packages":["pkg:npm/dotenv@16.6.1"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","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/dotenv@16.6.1"],"schemaVersion":1,"subject":"pkg:npm/dotenv@16.6.1","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-dotenv",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-dotenv",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "dotenv": "16.6.1"
      }
    },
    "node_modules/dotenv": {
      "version": "16.6.1",
      "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
      "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://dotenvx.com"
      }
    }
  }
}
package.json
{
  "name": "sample-dotenv",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "dotenv": "16.6.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/dotenv@16.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/dotenv@16.6.1"
  ]
}
src/index.mjs
import dotenv from 'dotenv';

/**
 * Parses a string or buffer in .env format into an object.
 * @param {string|Buffer} src - The contents to parse.
 * @returns {Record<string, string>} Key-value object of environment variables.
 */
export function parseEnv(src) {
  return dotenv.parse(src);
}

/**
 * Populates a target object with values from a parsed environment object.
 * @param {Record<string, string>} target - The destination object (e.g., process.env).
 * @param {Record<string, string>} parsed - The source key-value object.
 * @param {object} [options] - Population options (e.g., { override: boolean }).
 */
export function populateEnv(target, parsed, options = {}) {
  return dotenv.populate(target, parsed, options);
}

/**
 * Loads and populates environment variables from a file into process.env or a custom object.
 * @param {object} [options] - Configuration options.
 * @returns {{ parsed?: Record<string, string>, error?: Error }}
 */
export function loadEnv(options = {}) {
  return dotenv.configDotenv(options);
}

export { dotenv };
export default dotenv;
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import dotenv from 'dotenv';
import { parseEnv, populateEnv, loadEnv } from '../src/index.mjs';

// 1. dotenv.parse parses basic key-value pairs with unquoted, single-quoted, and double-quoted values
{
  const envContent = [
    'PLAIN_KEY=plain_value',
    'SINGLE_QUOTED=\'single value\'',
    'DOUBLE_QUOTED="double value"',
    'BACKTICK_QUOTED=`backtick value`',
    'COLON_KEY: colon_value'
  ].join('\n');

  const parsed = dotenv.parse(envContent);
  assert.equal(parsed.PLAIN_KEY, 'plain_value');
  assert.equal(parsed.SINGLE_QUOTED, 'single value');
  assert.equal(parsed.DOUBLE_QUOTED, 'double value');
  assert.equal(parsed.BACKTICK_QUOTED, 'backtick value');
  assert.equal(parsed.COLON_KEY, 'colon_value');

  // Verify helper export
  const helperParsed = parseEnv('PORT=8080');
  assert.equal(helperParsed.PORT, '8080');
}

// 2. dotenv.parse strips leading export keywords and inline comments on unquoted values
{
  const envContent = [
    'export EXPORTED_VAR=active # this is an inline comment',
    'HASH_IN_DOUBLE="value # not a comment"',
    'HASH_IN_SINGLE=\'value # not a comment\''
  ].join('\n');

  const parsed = dotenv.parse(envContent);
  assert.equal(parsed.EXPORTED_VAR, 'active');
  assert.equal(parsed.HASH_IN_DOUBLE, 'value # not a comment');
  assert.equal(parsed.HASH_IN_SINGLE, 'value # not a comment');
}

// 3. dotenv.parse expands newline and carriage return escape sequences in double-quoted strings
{
  const envContent = [
    'DOUBLE_ESCAPED="line1\\nline2\\rline3"',
    'SINGLE_RAW=\'line1\\nline2\\rline3\''
  ].join('\n');

  const parsed = dotenv.parse(envContent);
  assert.equal(parsed.DOUBLE_ESCAPED, 'line1\nline2\rline3');
  assert.equal(parsed.SINGLE_RAW, 'line1\\nline2\\rline3');
}

// 4. dotenv.populate sets environment variables on target object without overwriting existing keys by default
{
  const target = { EXISTING_KEY: 'original_value' };
  const parsed = {
    EXISTING_KEY: 'new_value',
    NEW_KEY: 'created_value'
  };

  dotenv.populate(target, parsed);
  assert.equal(target.EXISTING_KEY, 'original_value');
  assert.equal(target.NEW_KEY, 'created_value');

  // Verify helper export
  const targetHelper = { A: '1' };
  populateEnv(targetHelper, { A: '2', B: '3' });
  assert.equal(targetHelper.A, '1');
  assert.equal(targetHelper.B, '3');
}

// 5. dotenv.populate with override set to true overwrites existing target keys
{
  const target = { KEY_TO_OVERRIDE: 'initial_value' };
  const parsed = { KEY_TO_OVERRIDE: 'updated_value' };

  dotenv.populate(target, parsed, { override: true });
  assert.equal(target.KEY_TO_OVERRIDE, 'updated_value');
}

// 6. dotenv.populate throws an error when parsed argument is not an object
{
  assert.throws(
    () => dotenv.populate({}, 'invalid_string'),
    (err) => err.code === 'OBJECT_REQUIRED'
  );
}

// 7. dotenv.configDotenv loads variables from specified file paths into target processEnv
{
  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'csx-dotenv-test-'));
  const tempFilePath = path.join(tempDir, 'custom.env');

  try {
    fs.writeFileSync(tempFilePath, 'APP_MODE=production\nAPP_PORT=3000\n', 'utf8');

    const customProcessEnv = {};
    const result = dotenv.configDotenv({
      path: tempFilePath,
      processEnv: customProcessEnv
    });

    assert.equal(result.error, undefined);
    assert.deepEqual(result.parsed, {
      APP_MODE: 'production',
      APP_PORT: '3000'
    });
    assert.equal(customProcessEnv.APP_MODE, 'production');
    assert.equal(customProcessEnv.APP_PORT, '3000');

    // Test loadEnv helper
    const helperTarget = {};
    const helperResult = loadEnv({
      path: tempFilePath,
      processEnv: helperTarget
    });
    assert.equal(helperResult.error, undefined);
    assert.equal(helperTarget.APP_MODE, 'production');
  } finally {
    fs.rmSync(tempDir, { recursive: true, force: true });
  }
}

// 8. dotenv.configDotenv returns an error object when target path does not exist
{
  const nonExistentPath = path.join(os.tmpdir(), 'non-existent-' + Date.now() + '.env');
  const customProcessEnv = {};
  const result = dotenv.configDotenv({
    path: nonExistentPath,
    processEnv: customProcessEnv
  });

  assert.notEqual(result.error, undefined);
  assert.equal(result.error.code, 'ENOENT');
  assert.deepEqual(result.parsed, {});
}

console.log('Contract tests passed successfully.');

原始种子者

匿名