CodeSampleX

示例

ajv 8.20.0

已验证示例 — npm ajv 8.20.0. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: Ajv compiles JSON Schema definitions and validates data against type, range…

sha256:6034448091e83acd71353a24dfef0b3ce4787f68fb81f17c094b61e7686a1b0e

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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-23

案例

HOW
目标
verify pkg:npm/ajv@8.20.0
包
创建时间
2026-08-23T06:00:29Z

契约

  1. Ajv compiles JSON Schema definitions and validates data against type, range, and format constraints
  2. Ajv populates errors with keyword, instancePath, and params when validation fails
  3. Ajv resolves internal and cross-schema references via $id and $ref registered with addSchema
  4. Ajv with allErrors true collects all schema validation failures instead of stopping on first error
  5. Ajv with useDefaults true assigns default property values defined in the schema to target objects
  6. Ajv with coerceTypes true coerces data types to match expected schema property types
  7. Ajv supports custom keyword definitions with user-defined validation logic

文件

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • 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: verify pkg:npm/ajv@8.20.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/ajv@8.20.0

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:cda1eb837659c6d00224eba01877c96436902d2429b2bb23b3520f230b68fb1c","contract":["Ajv compiles JSON Schema definitions and validates data against type, range, and format constraints","Ajv populates errors with keyword, instancePath, and params when validation fails","Ajv resolves internal and cross-schema references via $id and $ref registered with addSchema","Ajv with allErrors true collects all schema validation failures instead of stopping on first error","Ajv with useDefaults true assigns default property values defined in the schema to target objects","Ajv with coerceTypes true coerces data types to match expected schema property types","Ajv supports custom keyword definitions with user-defined validation logic"],"goal":"verify pkg:npm/ajv@8.20.0","kind":"HOW","packages":["pkg:npm/ajv@8.20.0"],"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/ajv@8.20.0"],"schemaVersion":1,"subject":"pkg:npm/ajv@8.20.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-ajv",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-ajv",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "ajv": "8.20.0"
      }
    },
    "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/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"
      }
    }
  }
}
package.json
{
  "name": "sample-ajv",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for ajv@8.20.0",
  "license": "MIT-0",
  "dependencies": {
    "ajv": "8.20.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/ajv@8.20.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/ajv@8.20.0"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import Ajv from 'ajv';

async function testAll() {
  // 1. Ajv compiles JSON Schema definitions and validates data against type, range, and format constraints
  const ajv = new Ajv();
  const schema = {
    type: 'object',
    properties: {
      id: { type: 'integer', minimum: 1 },
      username: { type: 'string', minLength: 3, maxLength: 20 },
      email: { type: 'string' },
      roles: {
        type: 'array',
        items: { type: 'string' },
        minItems: 1,
        uniqueItems: true
      }
    },
    required: ['id', 'username'],
    additionalProperties: false
  };

  const validate = ajv.compile(schema);
  assert.equal(typeof validate, 'function', 'compile must return a validation function');

  const validRecord = {
    id: 101,
    username: 'developer',
    roles: ['admin', 'editor']
  };
  const isValid = validate(validRecord);
  assert.equal(isValid, true, 'valid data must pass validation');
  assert.equal(validate.errors, null, 'validate.errors must be null on success');

  // 2. Ajv populates errors with keyword, instancePath, and params when validation fails
  const invalidRecord = {
    id: 0,
    username: 'ab',
    extraField: true
  };
  const isInvalid = validate(invalidRecord);
  assert.equal(isInvalid, false, 'invalid data must fail validation');
  assert.ok(Array.isArray(validate.errors), 'validate.errors must be an array');
  assert.ok(validate.errors.length > 0, 'errors must not be empty');

  const firstError = validate.errors[0];
  assert.ok('keyword' in firstError, 'error object must include keyword');
  assert.ok('instancePath' in firstError, 'error object must include instancePath');
  assert.ok('message' in firstError, 'error object must include message');

  // 3. Ajv resolves internal and cross-schema references via $id and $ref registered with addSchema
  const ajvRef = new Ajv();
  const addressSchema = {
    $id: 'https://example.com/schemas/address.json',
    type: 'object',
    properties: {
      street: { type: 'string', minLength: 1 },
      zipCode: { type: 'string', pattern: '^[0-9]{5}$' }
    },
    required: ['street', 'zipCode'],
    additionalProperties: false
  };
  ajvRef.addSchema(addressSchema);

  const customerSchema = {
    $id: 'https://example.com/schemas/customer.json',
    type: 'object',
    properties: {
      name: { type: 'string', minLength: 1 },
      billingAddress: { $ref: 'https://example.com/schemas/address.json' }
    },
    required: ['name', 'billingAddress']
  };

  const validateCustomer = ajvRef.compile(customerSchema);
  assert.equal(
    validateCustomer({
      name: 'Tester',
      billingAddress: { street: '123 Main St', zipCode: '12345' }
    }),
    true,
    'valid referenced schema data must pass'
  );
  assert.equal(
    validateCustomer({
      name: 'Tester',
      billingAddress: { street: '123 Main St', zipCode: 'INVALID' }
    }),
    false,
    'invalid referenced schema data must fail'
  );

  // 4. Ajv with allErrors true collects all schema validation failures instead of stopping on first error
  const ajvAllErrors = new Ajv({ allErrors: true });
  const validateAll = ajvAllErrors.compile(schema);
  const multiErrorRecord = {
    id: -1,
    username: 'x',
    roles: []
  };
  const isMultiInvalid = validateAll(multiErrorRecord);
  assert.equal(isMultiInvalid, false);
  assert.ok(
    validateAll.errors.length >= 3,
    `allErrors should collect multiple errors, received: ${validateAll.errors.length}`
  );

  // 5. Ajv with useDefaults true assigns default property values defined in the schema to target objects
  const ajvDefaults = new Ajv({ useDefaults: true });
  const schemaWithDefaults = {
    type: 'object',
    properties: {
      status: { type: 'string', default: 'pending' },
      retries: { type: 'integer', default: 3 },
      meta: {
        type: 'object',
        properties: {
          enabled: { type: 'boolean', default: true }
        }
      }
    }
  };
  const validateDefaults = ajvDefaults.compile(schemaWithDefaults);
  const targetObject = { meta: {} };
  const defaultsValid = validateDefaults(targetObject);
  assert.equal(defaultsValid, true);
  assert.equal(targetObject.status, 'pending', 'default property value must be assigned');
  assert.equal(targetObject.retries, 3, 'default numeric value must be assigned');
  assert.equal(targetObject.meta.enabled, true, 'nested default value must be assigned');

  // 6. Ajv with coerceTypes true coerces data types to match expected schema property types
  const ajvCoerce = new Ajv({ coerceTypes: true });
  const schemaCoerce = {
    type: 'object',
    properties: {
      port: { type: 'integer' },
      debug: { type: 'boolean' }
    },
    required: ['port', 'debug']
  };
  const validateCoerce = ajvCoerce.compile(schemaCoerce);
  const inputToCoerce = { port: '8080', debug: 'true' };
  const coerceValid = validateCoerce(inputToCoerce);
  assert.equal(coerceValid, true, 'type coercion must succeed');
  assert.strictEqual(inputToCoerce.port, 8080, 'string number must be coerced to integer');
  assert.strictEqual(inputToCoerce.debug, true, 'string boolean must be coerced to boolean');

  // 7. Ajv supports custom keyword definitions with user-defined validation logic
  const ajvCustom = new Ajv();
  ajvCustom.addKeyword({
    keyword: 'isDivisibleBy',
    type: 'number',
    validate: (divisor, data) => typeof data === 'number' && data % divisor === 0
  });

  const schemaCustom = {
    type: 'object',
    properties: {
      score: { type: 'number', isDivisibleBy: 5 }
    }
  };
  const validateCustom = ajvCustom.compile(schemaCustom);
  assert.equal(validateCustom({ score: 25 }), true, 'custom keyword validation must pass when true');
  assert.equal(validateCustom({ score: 23 }), false, 'custom keyword validation must fail when false');

  console.log('Contract passed');
}

testAll().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

原始种子者

匿名