CodeSampleX

샘플

onetime 5.1.2: ensure a function is only executed once and returns the result of the first call

검증된 샘플 — npm onetime 5.1.2: ensure a function is only executed once and returns the result of the first call. node 22 · linux alpine/x64 · docker에서 contract를…

sha256:f6cf7fcd5c1d7405d53fa97c3e51c41bf973fc70620273e3f61d518e8fe4af07

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

케이스

HOW
목표
ensure a function is only executed once and returns the result of the first call
패키지
심벌
  • onetime
  • onetime.callCount
환경
node 22.23.2
생성일
2026-08-27T16:19:52Z

컨트랙트

  1. assert function executes once and returns initial result on subsequent calls
  2. assert subsequent calls return cached result without re-executing underlying function
  3. assert onetime.callCount accurately returns total invocations of wrapped function
  4. assert onetime.callCount throws when invoked on unwrapped function
  5. assert throw option raises Error on subsequent invocations
  6. assert non-function target throws TypeError
  7. assert wrapped function preserves name and metadata via mimicry

파일

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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: ensure a function is only executed once and returns the result of the first call
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/onetime@5.1.2
Demonstrate these symbols/APIs:
  - onetime
  - onetime.callCount

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:51ea40b1e41443e052109ff525dbff6a8e2e1e1765d264b4ca12ef16f65c6a74","contract":["assert function executes once and returns initial result on subsequent calls","assert subsequent calls return cached result without re-executing underlying function","assert onetime.callCount accurately returns total invocations of wrapped function","assert onetime.callCount throws when invoked on unwrapped function","assert throw option raises Error on subsequent invocations","assert non-function target throws TypeError","assert wrapped function preserves name and metadata via mimicry"],"goal":"ensure a function is only executed once and returns the result of the first call","kind":"HOW","packages":["pkg:npm/onetime@5.1.2"],"schemaVersion":1,"symbols":["onetime","onetime.callCount"]},"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/onetime@5.1.2"],"schemaVersion":1,"subject":"pkg:npm/onetime@5.1.2","symbols":["onetime","onetime.callCount"],"verifierAdapter":"node-typescript@1"}
index.js
const onetime = require('onetime');

function createSingleExecutor(fn, options) {
  return onetime(fn, options);
}

function getInvocationCount(fn) {
  return onetime.callCount(fn);
}

module.exports = {
  onetime,
  createSingleExecutor,
  getInvocationCount,
};
package-lock.json
{
  "name": "sample-onetime",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-onetime",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "onetime": "5.1.2"
      }
    },
    "node_modules/mimic-fn": {
      "version": "2.1.0",
      "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",
      "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/onetime": {
      "version": "5.1.2",
      "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz",
      "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==",
      "license": "MIT",
      "dependencies": {
        "mimic-fn": "^2.1.0"
      },
      "engines": {
        "node": ">=6"
      }
    }
  }
}
package.json
{
  "name": "sample-onetime",
  "version": "1.0.0",
  "description": "Minimal clean-room sample verifying onetime execution guarantees and call counting",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "onetime": "5.1.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "ensure a function is only executed once and returns the result of the first call",
  "kind": "HOW",
  "packages": [
    "pkg:npm/onetime@5.1.2"
  ],
  "symbols": [
    "onetime",
    "onetime.callCount"
  ]
}
test/contract.mjs
import assert from 'node:assert';
import onetime from 'onetime';
import { createSingleExecutor, getInvocationCount } from '../index.js';

// 1. Synchronous function runs once and caches return value across multiple invocations
let callCount = 0;
const onceFn = onetime((a, b) => {
  callCount += 1;
  return a + b;
});

assert.strictEqual(callCount, 0, 'wrapped function must not run before invocation');
assert.strictEqual(onceFn(2, 3), 5, 'first invocation computes and returns result');
assert.strictEqual(callCount, 1, 'underlying function executed once');

assert.strictEqual(onceFn(10, 20), 5, 'subsequent invocation returns cached initial result');
assert.strictEqual(callCount, 1, 'underlying function is not re-executed');

// 2. Helper createSingleExecutor adheres to onetime single-execution semantics
let helperCount = 0;
const helperFn = createSingleExecutor(() => {
  helperCount += 1;
  return 'initialized';
});
assert.strictEqual(helperFn(), 'initialized', 'helper executes target function once');
assert.strictEqual(helperFn(), 'initialized', 'helper returns cached result on repeat calls');
assert.strictEqual(helperCount, 1, 'helper target executed only once');

// 3. onetime.callCount accurately reports wrapper invocation count
assert.strictEqual(onetime.callCount(onceFn), 2, 'callCount reflects total wrapper calls');
assert.strictEqual(getInvocationCount(helperFn), 2, 'getInvocationCount reflects total wrapper calls');

const uncalledFn = onetime(() => 'unused');
assert.strictEqual(onetime.callCount(uncalledFn), 0, 'uncalled function has call count 0');

// 4. Calling onetime.callCount on a non-onetime function throws Error
assert.throws(
  () => {
    onetime.callCount(() => {});
  },
  {
    name: 'Error',
    message: /is not wrapped by the `onetime` package/,
  },
  'onetime.callCount on unwrapped function must throw'
);

// 5. Options { throw: true } raises Error on subsequent invocations
let throwTracker = 0;
const strictFn = onetime(
  function onlyOnce() {
    throwTracker += 1;
    return 'ok';
  },
  { throw: true }
);

assert.strictEqual(strictFn(), 'ok', 'first call succeeds when throw: true');
assert.strictEqual(throwTracker, 1, 'target function executed once');

assert.throws(
  () => {
    strictFn();
  },
  {
    name: 'Error',
    message: 'Function `onlyOnce` can only be called once',
  },
  'subsequent call throws descriptive error when throw: true'
);

assert.strictEqual(onetime.callCount(strictFn), 2, 'callCount increments even on throw');

// 6. Passing a non-function throws TypeError
assert.throws(
  () => {
    onetime(null);
  },
  {
    name: 'TypeError',
    message: 'Expected a function',
  },
  'passing non-function throws TypeError'
);

// 7. Function property mimicry and export shapes
function originalOperation(x) {
  return x;
}
const wrapped = onetime(originalOperation);
assert.strictEqual(wrapped.name, 'originalOperation', 'wrapper preserves function name');
assert.strictEqual(typeof onetime, 'function', 'onetime is a function');
assert.strictEqual(typeof onetime.callCount, 'function', 'onetime.callCount is a function');
assert.strictEqual(onetime.default, onetime, 'onetime.default points to onetime for interop');

console.log('All onetime contract assertions passed.');

오리진 시더

익명