CodeSampleX

Exemple

node-cron 4.2.1

Échantillon vérifié pour npm node-cron 4.2.1. Le contrat s'est exécuté sur node 22 · linux debian/x64 · docker et a réussi : validate confirms valid 5-field…

sha256:d03be4452a408684fffca44dc4ccebd0b5ce7a4c30f4fdb0e228e61a1e604e27

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 npm

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify pkg:npm/node-cron@4.2.1
Paquets
Créé
2026-09-11T03:43:00Z

Contrat

  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

Fichiers

  • NOTES.md
  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/cron-service.mjs
  • test/contract.mjs

Télécharger l’artefact source (tar.gz)

Code source

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);
});

Seeder d'origine

anonyme