CodeSampleX

Пример

jest-watcher 30.4.1: JestHook, TestWatcher, BaseWatchPlugin

Проверенный пример — npm jest-watcher 30.4.1: JestHook, TestWatcher, BaseWatchPlugin. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:4d317e11abecdbde9a3894aa56baa71bb856cdb4467ad6caba60354511266e77

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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
Цель
verify pkg:npm/jest-watcher@30.4.1
Пакеты
Символы
  • JestHook
  • TestWatcher
  • BaseWatchPlugin
  • KEYS
  • Prompt
Создан
2026-08-27T22:36:56Z

Контракт

  1. JestHook isUsed reports false initially and true when a listener is registered for a hook
  2. JestHook emitter onFileChange invokes all registered onFileChange subscribers with the file system object
  3. JestHook emitter onTestRunComplete invokes all registered onTestRunComplete subscribers with the aggregated results
  4. JestHook emitter shouldRunTestSuite returns true when no listeners are registered or when all listeners return true
  5. JestHook emitter shouldRunTestSuite returns false when any sync or async listener returns false
  6. TestWatcher tracks watch mode and initial uninterrupted state
  7. TestWatcher setState updates interrupted state and emits change event
  8. BaseWatchPlugin provides default plugin lifecycle methods and KEYS defines standard ANSI key sequences
  9. Prompt manages interactive input buffer, callbacks, and entering state
  10. Prompt handles backspace, CONTROL_U, and ESCAPE cancellation

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# jest-watcher `JestHook`, `TestWatcher`, `BaseWatchPlugin`, `KEYS`, and `Prompt`

## Prior Solution Search
`search_known_solution` returned `REFERENCE_ONLY` for `pkg:npm/jest-watcher@29.7.0`, targeting the upgrade and verification of `pkg:npm/jest-watcher@30.4.1`.

## Pinned Release
- `jest-watcher`: `30.4.1`

## Observed Behavior

When interacting with Jest's watch mode hooks, watcher runtime, and interactive prompts in `jest-watcher`:

1. **`JestHook` Registration and Lifecycle Dispatch**:
   - `JestHook` provides `getSubscriber()` for registering test lifecycle callbacks and `getEmitter()` for dispatching events.
   - `isUsed(hookName)` returns `false` initially and dynamically reports `true` once at least one listener is registered for `'onFileChange'`, `'onTestRunComplete'`, or `'shouldRunTestSuite'`.
   - `emitter.onFileChange(fs)` synchronously dispatches exposed filesystem project paths to all registered subscribers.
   - `emitter.onTestRunComplete(results)` synchronously dispatches aggregated test run metrics to all registered subscribers.
   - `emitter.shouldRunTestSuite(suiteInfo)` asynchronously evaluates all registered predicate functions via `Promise.all`. If no subscribers exist, it defaults to `true`. If any predicate returns or resolves to `false`, the suite run is suppressed (`false`).

2. **`TestWatcher` State Management**:
   - `TestWatcher` extends Emittery to provide reactive watch mode state tracking.
   - Constructor receives `{ isWatchMode: boolean }`, retrievable via `isWatchMode()`.
   - `state` initializes to `{ interrupted: false }`.
   - `setState(state)` updates the internal state and emits an async `'change'` event with the updated state dictionary.

3. **`BaseWatchPlugin` and `KEYS`**:
   - `BaseWatchPlugin` acts as the base class for Jest watch mode plugins, implementing default stubs for `apply()`, `getUsageInfo()`, `onKey()`, and `run()`.
   - `KEYS` maps standardized ANSI escape codes and terminal keystroke sequences (`ARROW_UP`, `ENTER`, `ESCAPE`, etc.).

4. **`Prompt` Interactive Input Buffer**:
   - `Prompt` manages interactive terminal input handling with `enter()`, `put()`, and `abort()`.
   - `isEntering()` indicates whether the prompt is currently capturing user input.
   - Supports keystroke processing including `KEYS.ENTER`, `KEYS.ESCAPE`, `KEYS.BACKSPACE`, and `KEYS.CONTROL_U`.
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/jest-watcher@30.4.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jest-watcher@30.4.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:d9b6025bec0af0303e6b599d5019ee1ed51769ff01375bfa621a51d092af1082","contract":["JestHook isUsed reports false initially and true when a listener is registered for a hook","JestHook emitter onFileChange invokes all registered onFileChange subscribers with the file system object","JestHook emitter onTestRunComplete invokes all registered onTestRunComplete subscribers with the aggregated results","JestHook emitter shouldRunTestSuite returns true when no listeners are registered or when all listeners return true","JestHook emitter shouldRunTestSuite returns false when any sync or async listener returns false","TestWatcher tracks watch mode and initial uninterrupted state","TestWatcher setState updates interrupted state and emits change event","BaseWatchPlugin provides default plugin lifecycle methods and KEYS defines standard ANSI key sequences","Prompt manages interactive input buffer, callbacks, and entering state","Prompt handles backspace, CONTROL_U, and ESCAPE cancellation"],"goal":"verify pkg:npm/jest-watcher@30.4.1","kind":"HOW","packages":["pkg:npm/jest-watcher@30.4.1"],"schemaVersion":1,"symbols":["JestHook","TestWatcher","BaseWatchPlugin","KEYS","Prompt"]},"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/jest-watcher@30.4.1"],"schemaVersion":1,"subject":"pkg:npm/jest-watcher@30.4.1","symbols":["JestHook","TestWatcher","BaseWatchPlugin","KEYS","Prompt"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "verify-jest-watcher",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "verify-jest-watcher",
      "version": "1.0.0",
      "dependencies": {
        "jest-watcher": "30.4.1"
      }
    },
    "node_modules/@babel/code-frame": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
      "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-validator-identifier": "^7.29.7",
        "js-tokens": "^4.0.0",
        "picocolors": "^1.1.1"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-validator-identifier": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@jest/console": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.4.1.tgz",
      "integrity": "sha512-v3bhyxUh9Hgmo5p6hAOXe14/R3ZxZDOsvHleh4B07z3m/x4/ngPUXEm9XwK4sF4u+f+P2ORb0Ge+MgpaqRMVDA==",
      "license": "MIT",
      "dependencies": {
        "@jest/types": "30.4.1",
        "@types/node": "*",
        "chalk": "^4.1.2",
        "jest-message-util": "30.4.1",
        "jest-util": "30.4.1",
        "slash": "^3.0.0"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/@jest/pattern": {
      "version": "30.4.0",
      "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.4.0.tgz",
      "integrity": "sha512-RAWn3+f9u8BsHijKJ71uHcFp6vmyEt6VvoWXkl6hKF3qVIuWNmudVjg12DlBPGup/frIl5UcUlH5HfEuvHpEXg==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*",
        "jest-regex-util": "30.4.0"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/@jest/schemas": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.4.1.tgz",
      "integrity": "sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==",
      "license": "MIT",
      "dependencies": {
        "@sinclair/typebox": "^0.34.0"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/@jest/test-result": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.4.1.tgz",
      "integrity": "sha512-/ZG7pgEiOmmWkN9TplKbOu4id2N5lh7FHwRwlkgBVAzGdRH+OkkQ8wX/kIxg4zmd3ZQvAL1RwL2yWsvNYYECTw==",
      "license": "MIT",
      "dependencies": {
        "@jest/console": "30.4.1",
        "@jest/types": "30.4.1",
        "@types/istanbul-lib-coverage": "^2.0.6",
        "collect-v8-coverage": "^1.0.2"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/@jest/types": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.4.1.tgz",
      "integrity": "sha512-f1x/vJXIfjOlEmejYpbkbgw1gOqpPECwMvMEtBqe47j7H2Hg8h8w3o3ikhSXq3MI15kg+oQ0exWO0uCtTNJLoQ==",
      "license": "MIT",
      "dependencies": {
        "@jest/pattern": "30.4.0",
        "@jest/schemas": "30.4.1",
        "@types/istanbul-lib-coverage": "^2.0.6",
        "@types/istanbul-reports": "^3.0.4",
        "@types/node": "*",
        "@types/yargs": "^17.0.33",
        "chalk": "^4.1.2"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.34.52",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz",
      "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==",
      "license": "MIT"
    },
    "node_modules/@types/istanbul-lib-coverage": {
      "version": "2.0.6",
      "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
      "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
      "license": "MIT"
    },
    "node_modules/@types/istanbul-lib-report": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz",
      "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==",
      "license": "MIT",
      "dependencies": {
        "@types/istanbul-lib-coverage": "*"
      }
    },
    "node_modules/@types/istanbul-reports": {
      "version": "3.0.4",
      "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz",
      "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==",
      "license": "MIT",
      "dependencies": {
        "@types/istanbul-lib-report": "*"
      }
    },
    "node_modules/@types/node": {
      "version": "26.4.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
      "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/@types/stack-utils": {
      "version": "2.0.3",
      "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz",
      "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==",
      "license": "MIT"
    },
    "node_modules/@types/yargs": {
      "version": "17.0.35",
      "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
      "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==",
      "license": "MIT",
      "dependencies": {
        "@types/yargs-parser": "*"
      }
    },
    "node_modules/@types/yargs-parser": {
      "version": "21.0.3",
      "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
      "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
      "license": "MIT"
    },
    "node_modules/ansi-escapes": {
      "version": "4.3.2",
      "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz",
      "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==",
      "license": "MIT",
      "dependencies": {
        "type-fest": "^0.21.3"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/ansi-regex": {
      "version": "5.0.1",
      "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
      "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/ansi-styles": {
      "version": "4.3.0",
      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
      "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
      "license": "MIT",
      "dependencies": {
        "color-convert": "^2.0.1"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
      }
    },
    "node_modules/chalk": {
      "version": "4.1.2",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
      "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
      "license": "MIT",
      "dependencies": {
        "ansi-styles": "^4.1.0",
        "supports-color": "^7.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/chalk?sponsor=1"
      }
    },
    "node_modules/char-regex": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz",
      "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/ci-info": {
      "version": "4.4.0",
      "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz",
      "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/sibiraj-s"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/collect-v8-coverage": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz",
      "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==",
      "license": "MIT"
    },
    "node_modules/color-convert": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
      "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
      "license": "MIT",
      "dependencies": {
        "color-name": "~1.1.4"
      },
      "engines": {
        "node": ">=7.0.0"
      }
    },
    "node_modules/color-name": {
      "version": "1.1.4",
      "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
      "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
      "license": "MIT"
    },
    "node_modules/emittery": {
      "version": "0.13.1",
      "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz",
      "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://github.com/sindresorhus/emittery?sponsor=1"
      }
    },
    "node_modules/escape-string-regexp": {
      "version": "2.0.0",
      "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz",
      "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/has-flag": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
      "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/jest-message-util": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.4.1.tgz",
      "integrity": "sha512-kwCKIvq0MCW1HzLoGola9Te6JUdzgV0loyKJ3Qghrkz9i5/RRIHsL95BMQc2HBBhlBKC4j22K9p11TGHH8RBpQ==",
      "license": "MIT",
      "dependencies": {
        "@babel/code-frame": "^7.27.1",
        "@jest/types": "30.4.1",
        "@types/stack-utils": "^2.0.3",
        "chalk": "^4.1.2",
        "graceful-fs": "^4.2.11",
        "jest-util": "30.4.1",
        "picomatch": "^4.0.3",
        "pretty-format": "30.4.1",
        "slash": "^3.0.0",
        "stack-utils": "^2.0.6"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/jest-regex-util": {
      "version": "30.4.0",
      "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.4.0.tgz",
      "integrity": "sha512-mWlvLviKIgIQ8VCuM1xRdD0TWp3zlzionlmDBjuXVBs+VkmXq6FgW9T4Emr7oGz/Rk6feDCGyiugolcQEyp3mg==",
      "license": "MIT",
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/jest-util": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.4.1.tgz",
      "integrity": "sha512-vjQb1sACEiv13DKJMDToJpzVW0joCsIQrmbg0fi7CyOOt+g9jTuQl2A216pWRBYhOVt53XbL/2LbMKg1BECWOw==",
      "license": "MIT",
      "dependencies": {
        "@jest/types": "30.4.1",
        "@types/node": "*",
        "chalk": "^4.1.2",
        "ci-info": "^4.2.0",
        "graceful-fs": "^4.2.11",
        "picomatch": "^4.0.3"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/jest-watcher": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-30.4.1.tgz",
      "integrity": "sha512-/l9UonmvCwjHH7d2h3iAwIloLc1H0S8mJZ/LNK3i86hqwPAz8otUJjP9MfYtz9Tt77Su5FD2xGjZn8d31IZHlw==",
      "license": "MIT",
      "dependencies": {
        "@jest/test-result": "30.4.1",
        "@jest/types": "30.4.1",
        "@types/node": "*",
        "ansi-escapes": "^4.3.2",
        "chalk": "^4.1.2",
        "emittery": "^0.13.1",
        "jest-util": "30.4.1",
        "string-length": "^4.0.2"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    },
    "node_modules/picomatch": {
      "version": "4.0.7",
      "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
      "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      },
      "funding": {
        "url": "https://github.com/sponsors/jonschlinkert"
      }
    },
    "node_modules/pretty-format": {
      "version": "30.4.1",
      "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.4.1.tgz",
      "integrity": "sha512-K6KiKMHTL4jjX4u3Kir2EW07nRfcqVTXIImx50wbjHQTcZPgg+gjVeNTIT3l3L1Rd4UefxfogquC9J37SoFyyw==",
      "license": "MIT",
      "dependencies": {
        "@jest/schemas": "30.4.1",
        "ansi-styles": "^5.2.0",
        "react-is-18": "npm:react-is@^18.3.1",
        "react-is-19": "npm:react-is@^19.2.5"
      },
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    },
    "node_modules/pretty-format/node_modules/ansi-styles": {
      "version": "5.2.0",
      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz",
      "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
      }
    },
    "node_modules/react-is-18": {
      "name": "react-is",
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz",
      "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
      "license": "MIT"
    },
    "node_modules/react-is-19": {
      "name": "react-is",
      "version": "19.2.8",
      "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.8.tgz",
      "integrity": "sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ==",
      "license": "MIT"
    },
    "node_modules/slash": {
      "version": "3.0.0",
      "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
      "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/stack-utils": {
      "version": "2.0.6",
      "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz",
      "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==",
      "license": "MIT",
      "dependencies": {
        "escape-string-regexp": "^2.0.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/string-length": {
      "version": "4.0.2",
      "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz",
      "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==",
      "license": "MIT",
      "dependencies": {
        "char-regex": "^1.0.2",
        "strip-ansi": "^6.0.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/strip-ansi": {
      "version": "6.0.1",
      "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
      "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
      "license": "MIT",
      "dependencies": {
        "ansi-regex": "^5.0.1"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/supports-color": {
      "version": "7.2.0",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
      "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/type-fest": {
      "version": "0.21.3",
      "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz",
      "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==",
      "license": "(MIT OR CC0-1.0)",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "verify-jest-watcher",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "jest-watcher": "30.4.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/jest-watcher@30.4.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jest-watcher@30.4.1"
  ],
  "symbols": [
    "JestHook",
    "TestWatcher",
    "BaseWatchPlugin",
    "KEYS",
    "Prompt"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { JestHook, TestWatcher, BaseWatchPlugin, KEYS, Prompt } from 'jest-watcher';

async function run() {
  // 1. JestHook isUsed reports false initially and true when a listener is registered for a hook
  const hook = new JestHook();
  assert.equal(hook.isUsed('onFileChange'), false);
  assert.equal(hook.isUsed('onTestRunComplete'), false);
  assert.equal(hook.isUsed('shouldRunTestSuite'), false);
  assert.equal(hook.isUsed('unknownHook'), false);

  const subscriber = hook.getSubscriber();
  const emitter = hook.getEmitter();

  assert.equal(typeof subscriber.onFileChange, 'function');
  assert.equal(typeof subscriber.onTestRunComplete, 'function');
  assert.equal(typeof subscriber.shouldRunTestSuite, 'function');
  assert.equal(typeof emitter.onFileChange, 'function');
  assert.equal(typeof emitter.onTestRunComplete, 'function');
  assert.equal(typeof emitter.shouldRunTestSuite, 'function');

  // 2. JestHook emitter onFileChange invokes all registered onFileChange subscribers with the file system object
  const fileChangesReceived = [];
  subscriber.onFileChange((fs) => {
    fileChangesReceived.push({ id: 1, fs });
  });
  subscriber.onFileChange((fs) => {
    fileChangesReceived.push({ id: 2, fs });
  });

  assert.equal(hook.isUsed('onFileChange'), true);

  const mockFs = {
    projects: [
      {
        config: { rootDir: '/workspace' },
        testPaths: ['/workspace/tests/a.test.js', '/workspace/tests/b.test.js'],
      },
    ],
  };

  emitter.onFileChange(mockFs);
  assert.equal(fileChangesReceived.length, 2);
  assert.deepEqual(fileChangesReceived[0], { id: 1, fs: mockFs });
  assert.deepEqual(fileChangesReceived[1], { id: 2, fs: mockFs });

  // 3. JestHook emitter onTestRunComplete invokes all registered onTestRunComplete subscribers with the aggregated results
  const resultsReceived = [];
  subscriber.onTestRunComplete((results) => {
    resultsReceived.push(results);
  });

  assert.equal(hook.isUsed('onTestRunComplete'), true);

  const mockAggregatedResults = {
    numFailedTestSuites: 0,
    numFailedTests: 0,
    numPassedTestSuites: 2,
    numPassedTests: 10,
    numTotalTestSuites: 2,
    numTotalTests: 10,
    success: true,
    startTime: Date.now(),
    wasInterrupted: false,
  };

  emitter.onTestRunComplete(mockAggregatedResults);
  assert.equal(resultsReceived.length, 1);
  assert.deepEqual(resultsReceived[0], mockAggregatedResults);

  // 4. JestHook emitter shouldRunTestSuite returns true when no listeners are registered or when all listeners return true
  const isolatedHook = new JestHook();
  const isolatedEmitter = isolatedHook.getEmitter();
  const testSuiteAlpha = { config: {}, testPath: '/workspace/tests/alpha.test.js' };
  const initialDecision = await isolatedEmitter.shouldRunTestSuite(testSuiteAlpha);
  assert.equal(initialDecision, true);

  const isolatedSub = isolatedHook.getSubscriber();
  isolatedSub.shouldRunTestSuite((suite) => suite.testPath.endsWith('.test.js'));
  isolatedSub.shouldRunTestSuite(async (suite) => !suite.testPath.includes('ignored'));

  const allowedDecision = await isolatedEmitter.shouldRunTestSuite(testSuiteAlpha);
  assert.equal(allowedDecision, true);

  // 5. JestHook emitter shouldRunTestSuite returns false when any sync or async listener returns false
  const rejectedSuite = { config: {}, testPath: '/workspace/tests/ignored.test.js' };
  const rejectedDecision = await isolatedEmitter.shouldRunTestSuite(rejectedSuite);
  assert.equal(rejectedDecision, false);

  const nonTestFile = { config: {}, testPath: '/workspace/tests/helper.js' };
  const nonTestDecision = await isolatedEmitter.shouldRunTestSuite(nonTestFile);
  assert.equal(nonTestDecision, false);

  // 6. TestWatcher tracks watch mode and initial uninterrupted state
  const watcher = new TestWatcher({ isWatchMode: true });
  assert.equal(watcher.isWatchMode(), true);
  assert.equal(watcher.isInterrupted(), false);
  assert.deepEqual(watcher.state, { interrupted: false });

  const nonWatchWatcher = new TestWatcher({ isWatchMode: false });
  assert.equal(nonWatchWatcher.isWatchMode(), false);
  assert.equal(nonWatchWatcher.isInterrupted(), false);

  // 7. TestWatcher setState updates interrupted state and emits change event
  const stateChanges = [];
  watcher.on('change', (state) => {
    stateChanges.push({ ...state });
  });

  await watcher.setState({ interrupted: true });
  assert.equal(watcher.isInterrupted(), true);
  assert.deepEqual(watcher.state, { interrupted: true });
  assert.equal(stateChanges.length, 1);
  assert.deepEqual(stateChanges[0], { interrupted: true });

  await watcher.setState({ interrupted: false });
  assert.equal(watcher.isInterrupted(), false);
  assert.equal(stateChanges.length, 2);
  assert.deepEqual(stateChanges[1], { interrupted: false });

  // 8. BaseWatchPlugin provides default plugin lifecycle methods and KEYS defines standard ANSI key sequences
  class CustomWatchPlugin extends BaseWatchPlugin {
    constructor(options) {
      super(options);
      this.applied = false;
      this.lastKeyPressed = null;
    }
    apply(hooks) {
      this.applied = true;
      hooks.onFileChange(() => {});
    }
    onKey(key) {
      this.lastKeyPressed = key;
    }
    getUsageInfo() {
      return { key: 'c', prompt: 'custom plugin command' };
    }
  }

  const mockStdin = {};
  const mockStdout = {};
  const plugin = new CustomWatchPlugin({ stdin: mockStdin, stdout: mockStdout });

  assert.equal(plugin.applied, false);
  plugin.apply(subscriber);
  assert.equal(plugin.applied, true);

  plugin.onKey(KEYS.ENTER);
  assert.equal(plugin.lastKeyPressed, '\r');
  plugin.onKey(KEYS.ESCAPE);
  assert.equal(plugin.lastKeyPressed, '\u001b');
  plugin.onKey(KEYS.ARROW_UP);
  assert.equal(plugin.lastKeyPressed, '\u001b[A');

  const usage = plugin.getUsageInfo({});
  assert.deepEqual(usage, { key: 'c', prompt: 'custom plugin command' });

  const basePlugin = new BaseWatchPlugin({ stdin: mockStdin, stdout: mockStdout });
  assert.equal(basePlugin.getUsageInfo({}), null);
  const runResult = await basePlugin.run({}, () => {});
  assert.equal(runResult, undefined);

  // 9. Prompt manages interactive input buffer, callbacks, and entering state
  const prompt = new Prompt();
  prompt.abort();
  assert.equal(prompt.isEntering(), false);

  let enteredValue = null;
  prompt.enter(
    () => {},
    (val) => {
      enteredValue = val;
    },
    () => {}
  );
  assert.equal(prompt.isEntering(), true);

  prompt.put('a');
  prompt.put('b');
  prompt.put(KEYS.ENTER);
  assert.equal(enteredValue, 'ab');
  assert.equal(prompt.isEntering(), false);

  // 10. Prompt handles backspace, CONTROL_U, and ESCAPE cancellation
  const prompt2 = new Prompt();
  let cancelledVal = null;
  let changedVal = null;
  prompt2.enter(
    (pattern) => {
      changedVal = pattern;
    },
    () => {},
    (val) => {
      cancelledVal = val;
    }
  );
  prompt2.put('x');
  prompt2.put('y');
  prompt2.put('z');
  assert.equal(changedVal, 'xyz');
  prompt2.put(KEYS.BACKSPACE);
  assert.equal(changedVal, 'xy');
  prompt2.put(KEYS.CONTROL_U);
  assert.equal(changedVal, '');
  prompt2.put('test');
  prompt2.put(KEYS.ESCAPE);
  assert.equal(cancelledVal, 'test');
  assert.equal(prompt2.isEntering(), false);
}

run();

Исходный сидер

аноним