CodeSampleX

Пример

schema-utils 4.3.3: validate options against JSON schema with schema-utils

Проверенный пример — npm schema-utils 4.3.3: validate options against JSON schema with schema-utils. Контракт выполнен на node 22 · linux alpine/x64 · docker…

sha256:ad32d2a53f41519843bedc56a03a32131704d43c30b4392448cb434972228d8a

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

Кейс

HOW
Цель
validate options against JSON schema with schema-utils
Пакеты
Окружение
node 22.23.2
Создан
2026-08-23T18:25:30Z

Контракт

  1. validate accepts valid options complying with the JSON schema without throwing
  2. validate throws a ValidationError when options violate property types or constraints
  3. validate throws a ValidationError when required schema properties are missing
  4. validate supports custom configuration options such as name, baseDataPath, and postFormatter
  5. disableValidation and enableValidation control whether runtime schema verification is executed via needValidate

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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: validate options against JSON schema with schema-utils
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/schema-utils@4.3.3
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:7f9b51ea67579cc906f4cbf47c665a105405f04aa7038959432fc44c9ac56355","constraints":{"executionContext":"node"},"contract":["validate accepts valid options complying with the JSON schema without throwing","validate throws a ValidationError when options violate property types or constraints","validate throws a ValidationError when required schema properties are missing","validate supports custom configuration options such as name, baseDataPath, and postFormatter","disableValidation and enableValidation control whether runtime schema verification is executed via needValidate"],"goal":"validate options against JSON schema with schema-utils","kind":"HOW","packages":["pkg:npm/schema-utils@4.3.3"],"schemaVersion":1},"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/schema-utils@4.3.3"],"schemaVersion":1,"subject":"pkg:npm/schema-utils@4.3.3","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-schema-utils-validate",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-schema-utils-validate",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "schema-utils": "4.3.3"
      }
    },
    "node_modules/@types/json-schema": {
      "version": "7.0.15",
      "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
      "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
      "license": "MIT"
    },
    "node_modules/ajv": {
      "version": "8.20.0",
      "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
      "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
      "license": "MIT",
      "dependencies": {
        "fast-deep-equal": "^3.1.3",
        "fast-uri": "^3.0.1",
        "json-schema-traverse": "^1.0.0",
        "require-from-string": "^2.0.2"
      },
      "funding": {
        "type": "github",
        "url": "https://github.com/sponsors/epoberezkin"
      }
    },
    "node_modules/ajv-formats": {
      "version": "2.1.1",
      "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz",
      "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==",
      "license": "MIT",
      "dependencies": {
        "ajv": "^8.0.0"
      },
      "peerDependencies": {
        "ajv": "^8.0.0"
      },
      "peerDependenciesMeta": {
        "ajv": {
          "optional": true
        }
      }
    },
    "node_modules/ajv-keywords": {
      "version": "5.1.0",
      "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz",
      "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==",
      "license": "MIT",
      "dependencies": {
        "fast-deep-equal": "^3.1.3"
      },
      "peerDependencies": {
        "ajv": "^8.8.2"
      }
    },
    "node_modules/fast-deep-equal": {
      "version": "3.1.3",
      "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
      "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
      "license": "MIT"
    },
    "node_modules/fast-uri": {
      "version": "3.1.6",
      "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.6.tgz",
      "integrity": "sha512-7Ical1vFEMr0onbVzEDIreM22I4khW+fzyQPwvAFWBp1iwdshSZRsL4jjRvPG9JP1uiqMHRto+YU6R2/CzDz5Q==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/fastify"
        },
        {
          "type": "opencollective",
          "url": "https://opencollective.com/fastify"
        }
      ],
      "license": "BSD-3-Clause"
    },
    "node_modules/json-schema-traverse": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
      "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
      "license": "MIT"
    },
    "node_modules/require-from-string": {
      "version": "2.0.2",
      "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
      "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
      "license": "MIT",
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/schema-utils": {
      "version": "4.3.3",
      "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz",
      "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==",
      "license": "MIT",
      "dependencies": {
        "@types/json-schema": "^7.0.9",
        "ajv": "^8.9.0",
        "ajv-formats": "^2.1.1",
        "ajv-keywords": "^5.1.0"
      },
      "engines": {
        "node": ">= 10.13.0"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/webpack"
      }
    }
  }
}
package.json
{
  "name": "sample-schema-utils-validate",
  "version": "1.0.0",
  "description": "Clean-room verification sample for schema-utils validate",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "dependencies": {
    "schema-utils": "4.3.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "validate options against JSON schema with schema-utils",
  "kind": "HOW",
  "packages": [
    "pkg:npm/schema-utils@4.3.3"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.mjs
import { validate, ValidationError, needValidate, enableValidation, disableValidation } from 'schema-utils';

export function validateConfiguration(schema, options, configuration) {
  validate(schema, options, configuration);
  return true;
}

export function validatePluginOptions(schema, options, pluginName) {
  validate(schema, options, { name: pluginName, baseDataPath: 'options' });
  return true;
}

export function isValidationActive() {
  return needValidate();
}

export function setValidationActive(active) {
  if (active) {
    enableValidation();
  } else {
    disableValidation();
  }
}

export {
  validate,
  ValidationError,
  needValidate,
  enableValidation,
  disableValidation
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  validate,
  ValidationError,
  validateConfiguration,
  validatePluginOptions,
  isValidationActive,
  setValidationActive
} from '../src/index.mjs';

const schema = {
  type: 'object',
  properties: {
    target: {
      type: 'string',
      enum: ['web', 'node']
    },
    minify: {
      type: 'boolean'
    },
    port: {
      type: 'integer',
      minimum: 1,
      maximum: 65535
    }
  },
  required: ['target'],
  additionalProperties: false
};

// 1. validate accepts valid options complying with the JSON schema without throwing
{
  const validOptions = { target: 'node', minify: true, port: 8080 };
  assert.doesNotThrow(() => {
    validate(schema, validOptions, { name: 'DemoPlugin' });
  });
  assert.equal(validateConfiguration(schema, validOptions, { name: 'DemoPlugin' }), true);
}

// 2. validate throws a ValidationError when options violate property types or constraints
{
  assert.throws(
    () => {
      validate(schema, { target: 'invalid' }, { name: 'DemoPlugin' });
    },
    (err) => {
      assert(err instanceof ValidationError);
      assert.equal(err.name, 'ValidationError');
      assert(Array.isArray(err.errors));
      assert(err.message.includes('DemoPlugin'));
      assert(err.message.includes('should be one of these'));
      return true;
    }
  );

  assert.throws(
    () => {
      validate(schema, { target: 'web', port: -1 }, { name: 'DemoPlugin' });
    },
    (err) => {
      assert(err instanceof ValidationError);
      return true;
    }
  );
}

// 3. validate throws a ValidationError when required schema properties are missing
{
  assert.throws(
    () => {
      validate(schema, { minify: true }, { name: 'DemoPlugin' });
    },
    (err) => {
      assert(err instanceof ValidationError);
      assert(err.message.includes("configuration misses the property 'target'"));
      return true;
    }
  );
}

// 4. validate supports custom configuration options such as name, baseDataPath, and postFormatter
{
  assert.throws(
    () => {
      validatePluginOptions(schema, { target: 123 }, 'CustomLoader');
    },
    (err) => {
      assert(err instanceof ValidationError);
      assert(err.message.includes('CustomLoader'));
      assert(err.message.includes('options.target'));
      assert(err.message.includes('Invalid options object.'));
      return true;
    }
  );

  assert.throws(
    () => {
      validate(schema, { target: 123 }, {
        name: 'FormatterPlugin',
        postFormatter: (formattedError) => `FORMATTED: ${formattedError}`
      });
    },
    (err) => {
      assert(err instanceof ValidationError);
      assert(err.message.includes('FORMATTED: '));
      return true;
    }
  );
}

// 5. disableValidation and enableValidation control whether runtime schema verification is executed via needValidate
{
  try {
    setValidationActive(false);
    assert.equal(isValidationActive(), false);
    assert.doesNotThrow(() => {
      validate(schema, { target: 'invalid-mode' }, { name: 'DemoPlugin' });
    });
  } finally {
    setValidationActive(true);
  }
  assert.equal(isValidationActive(), true);
  assert.throws(() => {
    validate(schema, { target: 'invalid-mode' }, { name: 'DemoPlugin' });
  });
}

console.log('All schema-utils@4.3.3 contract assertions passed.');

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

аноним