CodeSampleX

샘플

loose-envify 1.4.0: loose-envify

검증된 샘플 — npm loose-envify 1.4.0: loose-envify. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: looseEnvify exports transform stream replacing…

sha256:252adfac65d0e0a3f513fc7b4e426baf75b82a4eef727850ffae093b1671308c

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
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-01

케이스

HOW
목표
verify loose-envify in pkg:npm/loose-envify@1.4.0
패키지
심벌
  • loose-envify
환경
node 22.23.2
생성일
2026-09-01T22:49:41Z

컨트랙트

  1. looseEnvify exports transform stream replacing process.env references with literal values
  2. createCustomEnvTransformer uses looseEnvify/custom to replace custom variables including numbers and booleans
  3. purge option replaces undefined environment variables with literal undefined
  4. looseEnvify passes through .json files unmodified
  5. looseEnvify preserves assignments and property chains on process.env

파일

  • 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: verify loose-envify in pkg:npm/loose-envify@1.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/loose-envify@1.4.0
Demonstrate these symbols/APIs:
  - loose-envify

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:5f4daa86b33e5a1befa1d84920f638b8f5f2ae4f9493a53902b708467b39c147","contract":["looseEnvify exports transform stream replacing process.env references with literal values","createCustomEnvTransformer uses looseEnvify/custom to replace custom variables including numbers and booleans","purge option replaces undefined environment variables with literal undefined","looseEnvify passes through .json files unmodified","looseEnvify preserves assignments and property chains on process.env"],"goal":"verify loose-envify in pkg:npm/loose-envify@1.4.0","kind":"HOW","packages":["pkg:npm/loose-envify@1.4.0"],"schemaVersion":1,"symbols":["loose-envify"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/loose-envify@1.4.0"],"schemaVersion":1,"subject":"pkg:npm/loose-envify@1.4.0","symbols":["loose-envify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-loose-envify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-loose-envify",
      "version": "1.0.0",
      "dependencies": {
        "loose-envify": "1.4.0"
      }
    },
    "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/loose-envify": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
      "license": "MIT",
      "dependencies": {
        "js-tokens": "^3.0.0 || ^4.0.0"
      },
      "bin": {
        "loose-envify": "cli.js"
      }
    }
  }
}
package.json
{
  "name": "sample-loose-envify",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of loose-envify",
  "main": "src/index.js",
  "dependencies": {
    "loose-envify": "1.4.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify loose-envify in pkg:npm/loose-envify@1.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/loose-envify@1.4.0"
  ],
  "symbols": [
    "loose-envify"
  ]
}
src/index.js
const looseEnvify = require('loose-envify');
const looseEnvifyCustom = require('loose-envify/custom');
const { Readable } = require('node:stream');

/**
 * Transforms JavaScript code by replacing process.env references using loose-envify stream.
 * @param {string} code - Source code string.
 * @param {string} [filename='index.js'] - File name for transform stream.
 * @param {object} [env=process.env] - Environment variable overrides.
 * @returns {Promise<string>} Transformed code.
 */
function replaceEnvCode(code, filename = 'index.js', env = process.env) {
  return new Promise((resolve, reject) => {
    const transformStream = looseEnvify(filename, env);
    let result = '';

    transformStream.on('data', (chunk) => {
      result += chunk.toString();
    });
    transformStream.on('end', () => {
      resolve(result);
    });
    transformStream.on('error', (err) => {
      reject(err);
    });

    const readable = new Readable();
    readable.push(code);
    readable.push(null);
    readable.pipe(transformStream);
  });
}

/**
 * Creates a custom environment replacer function using loose-envify/custom.
 * @param {object} customEnv - Custom environment dictionary.
 * @returns {(code: string, filename?: string, trOpts?: object) => Promise<string>}
 */
function createCustomEnvTransformer(customEnv) {
  const transformFactory = looseEnvifyCustom(customEnv);
  return function transform(code, filename = 'index.js', trOpts) {
    return new Promise((resolve, reject) => {
      const transformStream = transformFactory(filename, trOpts);
      let result = '';

      transformStream.on('data', (chunk) => {
        result += chunk.toString();
      });
      transformStream.on('end', () => {
        resolve(result);
      });
      transformStream.on('error', (err) => {
        reject(err);
      });

      const readable = new Readable();
      readable.push(code);
      readable.push(null);
      readable.pipe(transformStream);
    });
  };
}

module.exports = {
  looseEnvify,
  looseEnvifyCustom,
  replaceEnvCode,
  createCustomEnvTransformer
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  looseEnvify,
  looseEnvifyCustom,
  replaceEnvCode,
  createCustomEnvTransformer
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof looseEnvify, 'function', 'looseEnvify should be a function');
assert.strictEqual(typeof looseEnvifyCustom, 'function', 'looseEnvifyCustom should be a function');
assert.strictEqual(typeof replaceEnvCode, 'function', 'replaceEnvCode should be a function');
assert.strictEqual(typeof createCustomEnvTransformer, 'function', 'createCustomEnvTransformer should be a function');

// 2. Default looseEnvify transform replacing process.env references with literal values
const sampleCode = `
if (process.env.NODE_ENV === "production") {
  console.log("Running in production mode");
}
const api = process.env.API_ENDPOINT;
`;
const transformed = await replaceEnvCode(sampleCode, 'app.js', {
  NODE_ENV: 'production',
  API_ENDPOINT: 'https://example.com/api'
});
assert.ok(transformed.includes('if ("production" === "production")'), 'NODE_ENV should be replaced with "production"');
assert.ok(transformed.includes('const api = "https://example.com/api";'), 'API_ENDPOINT should be replaced');
assert.ok(!transformed.includes('process.env.NODE_ENV'), 'process.env.NODE_ENV should not remain');
assert.ok(!transformed.includes('process.env.API_ENDPOINT'), 'process.env.API_ENDPOINT should not remain');

// 3. Custom envify factory replaces custom variables including numbers and booleans
const customTransformer = createCustomEnvTransformer({
  APP_PORT: 8080,
  FEATURE_FLAG: true,
  DEBUG: false,
  NAME: 'SampleApp'
});
const customCode = `
const port = process.env.APP_PORT;
const enabled = process.env.FEATURE_FLAG;
const debug = process.env.DEBUG;
const name = process.env.NAME;
`;
const customResult = await customTransformer(customCode, 'server.js');
assert.ok(customResult.includes('const port = 8080;'), 'Number environment variable should be replaced with numeric literal');
assert.ok(customResult.includes('const enabled = true;'), 'Boolean environment variable should be replaced with true');
assert.ok(customResult.includes('const debug = false;'), 'Boolean environment variable should be replaced with false');
assert.ok(customResult.includes('const name = "SampleApp";'), 'String environment variable should be replaced with string literal');

// 4. Purge option replaces undefined environment variables with literal 'undefined'
const purgeTransformer = createCustomEnvTransformer({
  KNOWN_VAR: 'known',
  _: ['purge']
});
const purgeCode = `
const a = process.env.KNOWN_VAR;
const b = process.env.UNDEFINED_VAR;
`;
const purgeResult = await purgeTransformer(purgeCode, 'config.js');
assert.ok(purgeResult.includes('const a = "known";'), 'Known variable should be replaced');
assert.ok(purgeResult.includes('const b = undefined;'), 'Unknown variable with purge should be replaced with undefined');

// 5. JSON files passthrough unmodified
const jsonInput = '{"env": "process.env.NODE_ENV"}';
const jsonResult = await replaceEnvCode(jsonInput, 'config.json', { NODE_ENV: 'production' });
assert.strictEqual(jsonResult, jsonInput, 'JSON files should pass through unmodified');

// 6. Preserves assignments and property chains on process.env
const assignmentCode = `
process.env.NODE_ENV = "override";
const sub = process.env.NODE_ENV.toUpperCase();
`;
const preservedResult = await replaceEnvCode(assignmentCode, 'init.js', { NODE_ENV: 'production' });
assert.ok(preservedResult.includes('process.env.NODE_ENV = "override";'), 'Assignment should not be replaced');
assert.ok(preservedResult.includes('process.env.NODE_ENV.toUpperCase();'), 'Property access on process.env variable should not be replaced');

console.log('All loose-envify contract tests passed successfully.');

오리진 시더

익명