CodeSampleX

샘플

universalify 0.1.2

검증된 샘플 — npm universalify 0.1.2. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: universalify exports fromCallback and fromPromise helper…

sha256:47138a0f287af8df505cb19dd457cf50ff97daf1c4d4f37f066e1c5faa63dd13

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
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@1
2026-08-21

케이스

HOW
목표
verify pkg:npm/universalify@0.1.2
패키지
환경
node 22.23.2
생성일
2026-08-21T05:19:59Z

컨트랙트

  1. universalify exports fromCallback and fromPromise helper functions
  2. fromCallback converts callback-based functions to return a promise when called without a callback
  3. fromCallback rejects the returned promise when the callback yields an error
  4. fromCallback invokes provided callback function with result when callback is supplied
  5. fromCallback delivers errors to the provided callback function
  6. fromPromise converts promise-returning functions to accept node-style callbacks
  7. fromPromise delivers rejected promise errors to the provided callback function
  8. fromPromise returns the original promise when invoked without a callback argument
  9. wrappers preserve the this context of wrapped functions

파일

  • 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 pkg:npm/universalify@0.1.2
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/universalify@0.1.2
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:86bd7f45a34442c30469b72e03da717415da0f1ae3fa0d9036ad121699c27219","constraints":{"executionContext":"node"},"contract":["universalify exports fromCallback and fromPromise helper functions","fromCallback converts callback-based functions to return a promise when called without a callback","fromCallback rejects the returned promise when the callback yields an error","fromCallback invokes provided callback function with result when callback is supplied","fromCallback delivers errors to the provided callback function","fromPromise converts promise-returning functions to accept node-style callbacks","fromPromise delivers rejected promise errors to the provided callback function","fromPromise returns the original promise when invoked without a callback argument","wrappers preserve the this context of wrapped functions"],"goal":"verify pkg:npm/universalify@0.1.2","kind":"HOW","packages":["pkg:npm/universalify@0.1.2"],"schemaVersion":1},"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/universalify@0.1.2"],"schemaVersion":1,"subject":"pkg:npm/universalify@0.1.2","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-universalify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-universalify",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "universalify": "0.1.2"
      }
    },
    "node_modules/universalify": {
      "version": "0.1.2",
      "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
      "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
      "license": "MIT",
      "engines": {
        "node": ">= 4.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-universalify",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for universalify@0.1.2",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "universalify": "0.1.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/universalify@0.1.2",
  "kind": "HOW",
  "packages": [
    "pkg:npm/universalify@0.1.2"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const universalify = require('universalify');

/**
 * Converts a callback-based function to return a Promise when no callback
 * argument is passed, while continuing to invoke callbacks when supplied.
 *
 * @param {Function} fn - The callback-accepting function to convert.
 * @returns {Function} Universal function supporting both Promise and callback styles.
 */
function universalFromCallback(fn) {
  return universalify.fromCallback(fn);
}

/**
 * Converts a Promise-returning function to also accept a Node.js-style error-first
 * callback as its last argument, while returning a Promise when called without a callback.
 *
 * @param {Function} fn - The Promise-returning function to convert.
 * @returns {Function} Universal function supporting both Promise and callback styles.
 */
function universalFromPromise(fn) {
  return universalify.fromPromise(fn);
}

module.exports = {
  universalify,
  fromCallback: universalify.fromCallback,
  fromPromise: universalify.fromPromise,
  universalFromCallback,
  universalFromPromise
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  universalify,
  fromCallback,
  fromPromise,
  universalFromCallback,
  universalFromPromise
} = require('../src/index.js');

async function testAll() {
  // 1. universalify exports fromCallback and fromPromise helper functions
  assert.equal(typeof universalify, 'object', 'universalify export should be an object');
  assert.equal(typeof universalify.fromCallback, 'function', 'universalify.fromCallback must be a function');
  assert.equal(typeof universalify.fromPromise, 'function', 'universalify.fromPromise must be a function');
  assert.equal(typeof fromCallback, 'function', 'fromCallback export must be a function');
  assert.equal(typeof fromPromise, 'function', 'fromPromise export must be a function');
  assert.equal(typeof universalFromCallback, 'function', 'universalFromCallback helper must be a function');
  assert.equal(typeof universalFromPromise, 'function', 'universalFromPromise helper must be a function');

  // 2. fromCallback converts callback-based functions to return a promise when called without a callback
  function addCallback(a, b, cb) {
    process.nextTick(() => cb(null, a + b));
  }
  const addPromise = universalify.fromCallback(addCallback);
  const addResult = await addPromise(15, 27);
  assert.equal(addResult, 42, 'fromCallback promise should resolve with result');

  // 3. fromCallback rejects the returned promise when the callback yields an error
  function failCallback(msg, cb) {
    process.nextTick(() => cb(new Error(msg)));
  }
  const failPromise = universalify.fromCallback(failCallback);
  await assert.rejects(
    async () => {
      await failPromise('operation failed');
    },
    {
      name: 'Error',
      message: 'operation failed'
    },
    'fromCallback promise should reject with callback error'
  );

  // 4. fromCallback invokes provided callback function with result when callback is supplied
  const callbackResult = await new Promise((resolve, reject) => {
    addPromise(10, 25, (err, res) => {
      if (err) return reject(err);
      resolve(res);
    });
  });
  assert.equal(callbackResult, 35, 'fromCallback should invoke callback with computed result');

  // 5. fromCallback delivers errors to the provided callback function
  const errorResult = await new Promise((resolve) => {
    failPromise('custom error message', (err, res) => {
      resolve({ err, res });
    });
  });
  assert.ok(errorResult.err instanceof Error, 'err should be an Error instance');
  assert.equal(errorResult.err.message, 'custom error message');
  assert.equal(errorResult.res, undefined);

  // 6. fromPromise converts promise-returning functions to accept node-style callbacks
  async function multiplyAsync(x, y) {
    return x * y;
  }
  const multiplyUniversal = universalify.fromPromise(multiplyAsync);

  const multiplyCallbackResult = await new Promise((resolve, reject) => {
    multiplyUniversal(6, 7, (err, res) => {
      if (err) return reject(err);
      resolve(res);
    });
  });
  assert.equal(multiplyCallbackResult, 42, 'fromPromise should deliver resolved value to callback');

  // 7. fromPromise delivers rejected promise errors to the provided callback function
  async function errorAsync(msg) {
    throw new Error(msg);
  }
  const errorUniversal = universalify.fromPromise(errorAsync);

  const promiseErrorResult = await new Promise((resolve) => {
    errorUniversal('async failure', (err, res) => {
      resolve({ err, res });
    });
  });
  assert.ok(promiseErrorResult.err instanceof Error, 'err should be an Error instance');
  assert.equal(promiseErrorResult.err.message, 'async failure');
  assert.equal(promiseErrorResult.res, undefined);

  // 8. fromPromise returns the original promise when invoked without a callback argument
  const directPromiseResult = await multiplyUniversal(8, 9);
  assert.equal(directPromiseResult, 72, 'fromPromise should return promise when no callback is passed');

  await assert.rejects(
    async () => {
      await errorUniversal('unhandled async failure');
    },
    {
      name: 'Error',
      message: 'unhandled async failure'
    },
    'fromPromise should return rejected promise when no callback is passed'
  );

  // 9. wrappers preserve the this context of wrapped functions
  const contextObject = {
    multiplier: 4,
    calculate(val, cb) {
      process.nextTick(() => cb(null, val * this.multiplier));
    },
    async calculateAsync(val) {
      return val * this.multiplier;
    }
  };
  const boundCb = universalify.fromCallback(contextObject.calculate);
  const boundAsync = universalify.fromPromise(contextObject.calculateAsync);

  const cbContextResult = await boundCb.call(contextObject, 5);
  assert.equal(cbContextResult, 20, 'fromCallback should respect this context binding');

  const asyncContextResult = await boundAsync.call(contextObject, 10);
  assert.equal(asyncContextResult, 40, 'fromPromise should respect this context binding');

  console.log('All universalify contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명