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. contract 在 node 22 · linux alpine/x64 · docker…

sha256:f6cf7fcd5c1d7405d53fa97c3e51c41bf973fc70620273e3f61d518e8fe4af07

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

原始种子者

匿名