示例
node-cron 4.2.1
已验证示例 — npm node-cron 4.2.1. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: validate confirms valid 5-field and 6-field cron expressions and rejects…
sha256:d03be4452a408684fffca44dc4ccebd0b5ce7a4c30f4fdb0e228e61a1e604e27
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
linux 24 · ubuntu · glibc 2.39 x64 npm
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| 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-11 |
案例
HOW- 目标
- verify pkg:npm/node-cron@4.2.1
- 创建时间
- 2026-09-11T03:43:00Z
契约
- validate confirms valid 5-field and 6-field cron expressions and rejects invalid patterns
- createTask creates an unstarted ScheduledTask with initial status stopped and null next run date
- task.start transitions task status to idle and schedules the next run date
- task.stop transitions task status to stopped and clears the scheduled next run date
- task.execute immediately invokes the scheduled task function and resolves with the return value
- task.destroy transitions task status to destroyed and permanently halts execution
- schedule instantiates and starts a ScheduledTask in idle status
- getTasks and getTask locate registered tasks by task identifier
文件
- NOTES.md
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/cron-service.mjs
- test/contract.mjs
源代码
# Notes: node-cron v4 API and Lifecycle Contract
## `search_known_solution` Result
`search_known_solution` returned NO_SAFE_MATCH for `pkg:npm/node-cron@4.2.1` with goal `verify pkg:npm/node-cron@4.2.1`.
## What a Naive Model Would Write
In older versions of `node-cron` (v3 and earlier), callers typically used `cron.schedule(expr, callback, { scheduled: false })` to create a task without starting it immediately. In v4, `TaskOptions` only accepts `{ timezone, name, noOverlap, maxExecutions, maxRandomDelay }`; passing `{ scheduled: false }` is ignored and does not stop the task from starting. Furthermore, task lifecycle in v4 is governed by a state machine with explicit statuses (`"stopped"`, `"idle"`, `"running"`, `"destroyed"`) and event emitter hooks.
## How the Wrong Version Fails
Code assuming v3 behavior passes `{ scheduled: false }` to `schedule()`, but in v4 `schedule()` always invokes `task.start()`, leading to unexpected background execution. To instantiate an unstarted task in v4, callers must use `createTask(expression, func, options)`. In addition, `task.getStatus()` returns explicit lifecycle state strings, and `task.execute()` provides manual promise-based execution.
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/node-cron@4.2.1
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/node-cron@4.2.1
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.
{"case":{"caseId":"case:sha256:cc93e3c3051f721ec04f201a74c827610df5ee2ecb2a0518168209f876e472c4","contract":["validate confirms valid 5-field and 6-field cron expressions and rejects invalid patterns","createTask creates an unstarted ScheduledTask with initial status stopped and null next run date","task.start transitions task status to idle and schedules the next run date","task.stop transitions task status to stopped and clears the scheduled next run date","task.execute immediately invokes the scheduled task function and resolves with the return value","task.destroy transitions task status to destroyed and permanently halts execution","schedule instantiates and starts a ScheduledTask in idle status","getTasks and getTask locate registered tasks by task identifier"],"goal":"verify pkg:npm/node-cron@4.2.1","kind":"HOW","packages":["pkg:npm/node-cron@4.2.1"],"schemaVersion":1},"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/node-cron@4.2.1"],"schemaVersion":1,"subject":"pkg:npm/node-cron@4.2.1","verifierAdapter":"node-typescript@1"}
{
"name": "node-cron-verification",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "node-cron-verification",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"node-cron": "4.2.1"
}
},
"node_modules/node-cron": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.2.1.tgz",
"integrity": "sha512-lgimEHPE/QDgFlywTd8yTR61ptugX3Qer29efeyWw2rv259HtGBNn1vZVmp8lB9uo9wC0t/AT4iGqXxia+CJFg==",
"license": "ISC",
"engines": {
"node": ">=6.0.0"
}
}
}
}
{
"name": "node-cron-verification",
"version": "1.0.0",
"private": true,
"type": "module",
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"node-cron": "4.2.1"
}
}
{
"schemaVersion": 1,
"goal": "verify pkg:npm/node-cron@4.2.1",
"kind": "HOW",
"packages": [
"pkg:npm/node-cron@4.2.1"
]
}
import cron, { schedule, createTask, validate, getTasks, getTask } from "node-cron";
/**
* Validates a cron expression string against node-cron grammar.
* Supports standard 5-field and optional 6-field (with seconds) syntax.
*/
export function validatePattern(expression) {
return validate(expression);
}
/**
* Creates an unstarted ScheduledTask instance.
* In node-cron v4, createTask instantiates a task in "stopped" state
* without scheduling initial timers until task.start() is invoked.
*/
export function createManagedTask(expression, taskFn, options = {}) {
return createTask(expression, taskFn, options);
}
/**
* Schedules and immediately starts a ScheduledTask instance.
* In node-cron v4, schedule transitions the task into "idle" state.
*/
export function scheduleManagedTask(expression, taskFn, options = {}) {
return schedule(expression, taskFn, options);
}
/**
* Manually executes a ScheduledTask out-of-band and awaits the promise result.
*/
export async function executeTaskManually(task) {
return await task.execute();
}
/**
* Stops and permanently destroys a ScheduledTask instance.
*/
export function stopAndDestroyTask(task) {
task.destroy();
}
export {
cron,
schedule,
createTask,
validate,
getTasks,
getTask,
};
import { strict as assert } from "node:assert";
import cron, { schedule, createTask, validate, getTasks, getTask } from "node-cron";
import {
validatePattern,
createManagedTask,
scheduleManagedTask,
executeTaskManually,
stopAndDestroyTask,
} from "../src/cron-service.mjs";
async function runContract() {
// 1. validate confirms valid 5-field and 6-field cron expressions and rejects invalid patterns
assert.equal(validatePattern("* * * * *"), true, "5-field pattern should be valid");
assert.equal(validatePattern("*/15 * * * *"), true, "step pattern should be valid");
assert.equal(validatePattern("0 0 1 1 *"), true, "date pattern should be valid");
assert.equal(validatePattern("* * * * * *"), true, "6-field pattern should be valid");
assert.equal(validatePattern("invalid-cron-pattern"), false, "invalid string should be rejected");
assert.equal(validatePattern("60 * * * *"), false, "minute out of range should be rejected");
assert.equal(validatePattern("* 25 * * *"), false, "hour out of range should be rejected");
// 2. createTask creates an unstarted ScheduledTask with initial status stopped and null next run date
let invocationCount = 0;
const task = createManagedTask("0 0 1 1 *", () => {
invocationCount++;
return "task-contract-result";
}, { name: "offline-cron-task" });
assert.ok(task, "task instance must be returned");
assert.ok(typeof task.id === "string" && task.id.length > 0, "task id must be a non-empty string");
assert.equal(task.name, "offline-cron-task", "task name must match configured option");
assert.equal(task.getStatus(), "stopped", "initial status must be stopped");
assert.equal(task.getNextRun(), null, "getNextRun must return null when task is stopped");
// 3. task.start transitions task status to idle and schedules the next run date
let taskStartedEventEmitted = false;
task.on("task:started", () => {
taskStartedEventEmitted = true;
});
task.start();
assert.equal(task.getStatus(), "idle", "status after start must be idle");
assert.equal(taskStartedEventEmitted, true, "task:started event must be fired on start");
const nextRun = task.getNextRun();
assert.ok(nextRun instanceof Date, "getNextRun must return a Date object after start");
assert.ok(nextRun.getTime() > Date.now(), "nextRun must be in the future");
// 4. task.stop transitions task status to stopped and clears the scheduled next run date
let taskStoppedEventEmitted = false;
task.on("task:stopped", () => {
taskStoppedEventEmitted = true;
});
task.stop();
assert.equal(task.getStatus(), "stopped", "status after stop must be stopped");
assert.equal(taskStoppedEventEmitted, true, "task:stopped event must be fired on stop");
assert.equal(task.getNextRun(), null, "getNextRun must return null after stop");
// 5. task.execute immediately invokes the scheduled task function and resolves with the return value
let execStarted = false;
let execFinished = false;
task.on("execution:started", () => {
execStarted = true;
});
task.on("execution:finished", () => {
execFinished = true;
});
const execResult = await executeTaskManually(task);
assert.equal(execResult, "task-contract-result", "execute must return task function return value");
assert.equal(invocationCount, 1, "task function must have executed exactly once");
assert.equal(execStarted, true, "execution:started event must be fired");
assert.equal(execFinished, true, "execution:finished event must be fired");
// 6. task.destroy transitions task status to destroyed and permanently halts execution
let taskDestroyedEventEmitted = false;
task.on("task:destroyed", () => {
taskDestroyedEventEmitted = true;
});
stopAndDestroyTask(task);
assert.equal(task.getStatus(), "destroyed", "status after destroy must be destroyed");
assert.equal(taskDestroyedEventEmitted, true, "task:destroyed event must be fired");
// 7. schedule instantiates and starts a ScheduledTask in idle status
const scheduledTask = scheduleManagedTask("0 12 * * *", () => "scheduled-ok", { name: "auto-started-cron" });
assert.equal(scheduledTask.getStatus(), "idle", "schedule must start task in idle status");
assert.ok(scheduledTask.getNextRun() instanceof Date, "scheduled task must have valid next run date");
// 8. getTasks and getTask locate registered tasks by task identifier
const registryTasks = getTasks();
assert.ok(registryTasks instanceof Map, "getTasks must return a Map");
assert.ok(registryTasks.has(scheduledTask.id), "task registry must contain scheduled task id");
const foundTask = getTask(scheduledTask.id);
assert.equal(foundTask, scheduledTask, "getTask must return the exact registered task instance");
scheduledTask.destroy();
console.log("Contract verified successfully.");
}
runContract().catch((err) => {
console.error("Contract test failed:", err);
process.exit(1);
});
原始种子者
匿名