CodeSampleX

Ejemplo

bare-os 3.9.3: setEnv

Muestra verificada para npm bare-os 3.9.3: setEnv. El contrato se ejecutó en node 22 · linux alpine/x64 · docker y pasó: bare-os package manifest exports…

sha256:08c13292af172417a2f45b0f6fbbc883e70315181647468e7e8cab3f8390068d

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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

Caso

HOW
Objetivo
verify setEnv in pkg:npm/bare-os@3.9.3
Paquetes
Símbolos
  • setEnv
Creado
2026-08-27T09:46:39Z

Contrato

  1. bare-os package manifest exports root module with setEnv API and index.d.ts type declarations
  2. index.d.ts declares setEnv function taking string name and string value and returning void
  3. index.js exports setEnv function validating string arguments and delegating to native binding setEnv
  4. native binding.c implements bare_os_set_env using uv_os_setenv and registers setEnv export
  5. setEnv sets environment variable verifiable via getEnv and hasEnv and updates existing keys
  6. setEnv throws TypeError when name or value is not a string
  7. setEnv integrates with custom addon bindings and unsetting with unsetEnv clears the value

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 setEnv in pkg:npm/bare-os@3.9.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-os@3.9.3
Demonstrate these symbols/APIs:
  - setEnv

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:c7d4373ff988f750be012c935545fe67ffc46e036cc9aabfe265ad5531cb2be2","contract":["bare-os package manifest exports root module with setEnv API and index.d.ts type declarations","index.d.ts declares setEnv function taking string name and string value and returning void","index.js exports setEnv function validating string arguments and delegating to native binding setEnv","native binding.c implements bare_os_set_env using uv_os_setenv and registers setEnv export","setEnv sets environment variable verifiable via getEnv and hasEnv and updates existing keys","setEnv throws TypeError when name or value is not a string","setEnv integrates with custom addon bindings and unsetting with unsetEnv clears the value"],"goal":"verify setEnv in pkg:npm/bare-os@3.9.3","kind":"HOW","packages":["pkg:npm/bare-os@3.9.3"],"schemaVersion":1,"symbols":["setEnv"]},"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/bare-os@3.9.3"],"schemaVersion":1,"subject":"pkg:npm/bare-os@3.9.3","symbols":["setEnv"],"verifierAdapter":"node-typescript@1"}
index.js
import { createRequire } from 'node:module';
import path from 'node:path';

const require = createRequire(import.meta.url);

/**
 * Initializes and loads the bare-os module with an underlying binding.
 * If running in an environment without native Bare addons (like Node.js),
 * sets up a fallback mock binding using process.env.
 * @param {object} [bindingMock] - Optional custom binding implementation.
 * @returns {object} The loaded bare-os module.
 */
export function loadBareOS(bindingMock) {
  const pkgPath = require.resolve('bare-os/package');
  const bindingPath = path.join(path.dirname(pkgPath), 'binding.js');
  const bareOsPath = require.resolve('bare-os');

  if (bindingMock || !require.cache[bindingPath]) {
    delete require.cache[bareOsPath];
    const envStore = { ...process.env };
    require.cache[bindingPath] = {
      id: bindingPath,
      filename: bindingPath,
      loaded: true,
      exports: bindingMock || {
        platform: process.platform,
        arch: process.arch,
        getEnvKeys: () => Object.keys(envStore),
        getEnv: (name) => envStore[name],
        hasEnv: (name) => Object.prototype.hasOwnProperty.call(envStore, name),
        setEnv: (name, value) => {
          envStore[name] = value;
        },
        unsetEnv: (name) => {
          delete envStore[name];
        },
      },
    };
  }

  return require('bare-os');
}

/**
 * Sets an environment variable using bare-os setEnv.
 * @param {string} name - The name of the environment variable.
 * @param {string} value - The value to assign.
 */
export function setEnvironmentVariable(name, value) {
  const os = loadBareOS();
  os.setEnv(name, value);
}

/**
 * Retrieves an environment variable value using bare-os getEnv.
 * @param {string} name - The name of the environment variable.
 * @returns {string|undefined} The environment variable value.
 */
export function getEnvironmentVariable(name) {
  const os = loadBareOS();
  return os.getEnv(name);
}

/**
 * Checks if an environment variable exists using bare-os hasEnv.
 * @param {string} name - The name of the environment variable.
 * @returns {boolean} True if the variable exists.
 */
export function hasEnvironmentVariable(name) {
  const os = loadBareOS();
  return os.hasEnv(name);
}

/**
 * Removes an environment variable using bare-os unsetEnv.
 * @param {string} name - The name of the environment variable.
 */
export function unsetEnvironmentVariable(name) {
  const os = loadBareOS();
  os.unsetEnv(name);
}

export default loadBareOS();
package-lock.json
{
  "name": "sample-bare-os-set-env",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-bare-os-set-env",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "bare-os": "3.9.3"
      }
    },
    "node_modules/bare-os": {
      "version": "3.9.3",
      "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.9.3.tgz",
      "integrity": "sha512-fF4Q7QsyKVF5Rj0qvI8BgUNjqzC2JvQlpTaPLjVJVxYVUX5Zr9un+y3w1HmA4nNKdFmRBT8z/WmrjvXzXVerKQ==",
      "license": "Apache-2.0",
      "engines": {
        "bare": ">=1.14.0"
      }
    }
  }
}
package.json
{
  "name": "sample-bare-os-set-env",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bare-os": "3.9.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify setEnv in pkg:npm/bare-os@3.9.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-os@3.9.3"
  ],
  "symbols": [
    "setEnv"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
import os, {
  loadBareOS,
  setEnvironmentVariable,
  getEnvironmentVariable,
  hasEnvironmentVariable,
  unsetEnvironmentVariable
} from '../index.js';

const require = createRequire(import.meta.url);

// 1. bare-os package manifest exports root module with setEnv API and index.d.ts type declarations
const pkgPath = require.resolve('bare-os/package');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

assert.equal(pkg.name, 'bare-os', 'Package name must be bare-os');
assert.equal(pkg.version, '3.9.3', 'Package version must be 3.9.3');
assert.equal(pkg.license, 'Apache-2.0', 'Package license must be Apache-2.0');
assert.equal(pkg.addon, true, 'Package must be marked as addon');
assert.equal(pkg.engines?.bare, '>=1.14.0', 'Package must specify Bare engine >=1.14.0');

assert.ok(pkg.exports, 'Package must define exports');
assert.equal(pkg.exports['.']?.types, './index.d.ts', 'Root export must have index.d.ts types');
assert.equal(pkg.exports['.']?.default, './index.js', 'Root export must have index.js default');
assert.equal(pkg.exports['./package'], './package.json', 'Package export must point to package.json');

const pkgDir = path.dirname(pkgPath);

// 2. index.d.ts declares setEnv function taking string name and string value and returning void
const indexDts = fs.readFileSync(path.join(pkgDir, 'index.d.ts'), 'utf8');
assert.match(
  indexDts,
  /export\s+function\s+setEnv\(\s*name\s*:\s*string\s*,\s*value\s*:\s*string\s*\)\s*:\s*void/,
  'index.d.ts must declare setEnv(name: string, value: string): void'
);
assert.match(
  indexDts,
  /export\s+function\s+getEnv\(\s*name\s*:\s*string\s*\)\s*:\s*string\s*\|\s*undefined/,
  'index.d.ts must declare getEnv(name: string): string | undefined'
);
assert.match(
  indexDts,
  /export\s+function\s+hasEnv\(\s*name\s*:\s*string\s*\)\s*:\s*boolean/,
  'index.d.ts must declare hasEnv(name: string): boolean'
);
assert.match(
  indexDts,
  /export\s+function\s+unsetEnv\(\s*name\s*:\s*string\s*\)\s*:\s*void/,
  'index.d.ts must declare unsetEnv(name: string): void'
);

// 3. index.js exports setEnv function validating string arguments and delegating to native binding setEnv
const indexJs = fs.readFileSync(path.join(pkgDir, 'index.js'), 'utf8');
assert.match(
  indexJs,
  /exports\.setEnv\s*=\s*function\s+setEnv\s*\(\s*name\s*,\s*value\s*\)\s*\{[\s\S]*?validateString\(\s*name\s*,\s*'Name'\s*\)[\s\S]*?validateString\(\s*value\s*,\s*'Value'\s*\)[\s\S]*?binding\.setEnv\(\s*name\s*,\s*value\s*\)/,
  'index.js must validate arguments and call binding.setEnv'
);

// 4. native binding.c implements bare_os_set_env using uv_os_setenv and registers setEnv export
const bindingC = fs.readFileSync(path.join(pkgDir, 'binding.c'), 'utf8');
assert.ok(
  bindingC.includes('bare_os_set_env(js_env_t *env, js_callback_info_t *info)'),
  'binding.c must contain bare_os_set_env implementation'
);
assert.ok(
  bindingC.includes('uv_os_setenv((char *) name, (char *) value)'),
  'bare_os_set_env must invoke uv_os_setenv'
);
assert.ok(
  bindingC.includes('V("setEnv", bare_os_set_env)'),
  'binding.c must register setEnv in export table'
);

// 5. setEnv sets environment variable verifiable via getEnv and hasEnv and updates existing keys
const testKey = 'CSX_TEST_SAMPLE_SETENV_KEY';
const initialVal = 'csx_initial_value_123';
const updatedVal = 'csx_updated_value_456';

setEnvironmentVariable(testKey, initialVal);
assert.strictEqual(hasEnvironmentVariable(testKey), true, 'hasEnvironmentVariable must return true for set variable');
assert.strictEqual(getEnvironmentVariable(testKey), initialVal, 'getEnvironmentVariable must return initial value');

setEnvironmentVariable(testKey, updatedVal);
assert.strictEqual(getEnvironmentVariable(testKey), updatedVal, 'getEnvironmentVariable must return updated value');

// 6. setEnv throws TypeError when name or value is not a string
assert.throws(
  () => setEnvironmentVariable(12345, 'some_value'),
  { name: 'TypeError' },
  'setEnv must throw TypeError when name is not a string'
);
assert.throws(
  () => setEnvironmentVariable('VALID_KEY', 12345),
  { name: 'TypeError' },
  'setEnv must throw TypeError when value is not a string'
);
assert.throws(
  () => setEnvironmentVariable(null, 'some_value'),
  { name: 'TypeError' },
  'setEnv must throw TypeError when name is null'
);
assert.throws(
  () => setEnvironmentVariable('VALID_KEY', null),
  { name: 'TypeError' },
  'setEnv must throw TypeError when value is null'
);

// 7. setEnv integrates with custom addon bindings and unsetting with unsetEnv clears the value
unsetEnvironmentVariable(testKey);
assert.strictEqual(hasEnvironmentVariable(testKey), false, 'hasEnvironmentVariable must return false after unset');
assert.strictEqual(getEnvironmentVariable(testKey), undefined, 'getEnvironmentVariable must return undefined after unset');

const customEnv = {};
const customOS = loadBareOS({
  platform: 'linux',
  arch: 'x64',
  getEnvKeys: () => Object.keys(customEnv),
  getEnv: (name) => customEnv[name],
  hasEnv: (name) => Object.prototype.hasOwnProperty.call(customEnv, name),
  setEnv: (name, value) => {
    customEnv[name] = value;
  },
  unsetEnv: (name) => {
    delete customEnv[name];
  },
});

assert.strictEqual(typeof customOS.setEnv, 'function', 'bare-os must export setEnv function');
customOS.setEnv('CUSTOM_BINDING_KEY', 'custom_binding_val');
assert.strictEqual(customEnv['CUSTOM_BINDING_KEY'], 'custom_binding_val', 'custom binding setEnv must be called');
assert.strictEqual(customOS.getEnv('CUSTOM_BINDING_KEY'), 'custom_binding_val', 'custom binding getEnv must return value');

console.log('Contract passed: setEnv in pkg:npm/bare-os@3.9.3 successfully verified');

Seeder de origen

anónimo