CodeSampleX

샘플

node-cron 4.2.1

검증된 샘플 — npm node-cron 4.2.1. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: validate confirms valid 5-field and 6-field cron expressions and…

sha256:d03be4452a408684fffca44dc4ccebd0b5ce7a4c30f4fdb0e228e61a1e604e27

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

컨트랙트

  1. validate confirms valid 5-field and 6-field cron expressions and rejects invalid patterns
  2. createTask creates an unstarted ScheduledTask with initial status stopped and null next run date
  3. task.start transitions task status to idle and schedules the next run date
  4. task.stop transitions task status to stopped and clears the scheduled next run date
  5. task.execute immediately invokes the scheduled task function and resolves with the return value
  6. task.destroy transitions task status to destroyed and permanently halts execution
  7. schedule instantiates and starts a ScheduledTask in idle status
  8. 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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# 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.
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/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.
csx.json
{"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"}
package-lock.json
{
  "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"
      }
    }
  }
}
package.json
{
  "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"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/node-cron@4.2.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/node-cron@4.2.1"
  ]
}
src/cron-service.mjs
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,
};
test/contract.mjs
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);
});

오리진 시더

익명