CodeSampleX

Пример

@sinclair/typebox 0.27.12: TypeCompiler

Проверенный пример — npm @sinclair/typebox 0.27.12: TypeCompiler. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:82ebcbf1ffddb07e5ee641d2142102ead84b6920b94bd197387dade7ceaec415

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

Кейс

HOW
Цель
verify @sinclair/typebox.TypeCompiler in pkg:npm/%40sinclair/typebox@0.27.12
Пакеты
Символы
  • @sinclair/typebox.TypeCompiler
Окружение
node 22.23.2
Создан
2026-08-21T05:30:37Z

Контракт

  1. TypeCompiler compiles a TypeBox schema into an executable validator
  2. compiled validator Check returns true for valid data matching schema constraints
  3. compiled validator Check returns false for invalid data violating schema constraints
  4. compiled validator Errors yields structured error objects with path and message for invalid fields
  5. TypeCompiler.Code and compiled validator Code return generated JavaScript validator code string

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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 @sinclair/typebox.TypeCompiler in pkg:npm/%40sinclair/typebox@0.27.12
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40sinclair/typebox@0.27.12
Demonstrate these symbols/APIs:
  - @sinclair/typebox.TypeCompiler
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:9069eaf7719afee29034d5fa1ddf7ccecf17b2bed8db6bda6ca23b58d26fecee","constraints":{"executionContext":"node"},"contract":["TypeCompiler compiles a TypeBox schema into an executable validator","compiled validator Check returns true for valid data matching schema constraints","compiled validator Check returns false for invalid data violating schema constraints","compiled validator Errors yields structured error objects with path and message for invalid fields","TypeCompiler.Code and compiled validator Code return generated JavaScript validator code string"],"goal":"verify @sinclair/typebox.TypeCompiler in pkg:npm/%40sinclair/typebox@0.27.12","kind":"HOW","packages":["pkg:npm/%40sinclair/typebox@0.27.12"],"schemaVersion":1,"symbols":["@sinclair/typebox.TypeCompiler"]},"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/%40sinclair/typebox@0.27.12"],"schemaVersion":1,"subject":"pkg:npm/%40sinclair/typebox@0.27.12","symbols":["@sinclair/typebox.TypeCompiler"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-typebox-typecompiler",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-typebox-typecompiler",
      "version": "1.0.0",
      "dependencies": {
        "@sinclair/typebox": "0.27.12"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.27.12",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
      "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-typebox-typecompiler",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @sinclair/typebox.TypeCompiler",
  "main": "src/index.js",
  "dependencies": {
    "@sinclair/typebox": "0.27.12"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @sinclair/typebox.TypeCompiler in pkg:npm/%40sinclair/typebox@0.27.12",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinclair/typebox@0.27.12"
  ],
  "symbols": [
    "@sinclair/typebox.TypeCompiler"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const { Type } = require('@sinclair/typebox');
const { TypeCompiler } = require('@sinclair/typebox/compiler');

/**
 * Compiles a TypeBox schema into an optimized validator.
 * @param {import('@sinclair/typebox').TSchema} schema - The TypeBox schema definition.
 * @returns {import('@sinclair/typebox/compiler').TypeCheck<any>} Compiled TypeCheck instance.
 */
function compileSchema(schema) {
  return TypeCompiler.Compile(schema);
}

/**
 * Validates data against a compiled TypeCheck validator.
 * @param {import('@sinclair/typebox/compiler').TypeCheck<any>} compiled - Compiled TypeCheck validator.
 * @param {unknown} data - Data to validate.
 * @returns {boolean} True if valid, false otherwise.
 */
function isValid(compiled, data) {
  return compiled.Check(data);
}

/**
 * Collects all validation error details for invalid data.
 * @param {import('@sinclair/typebox/compiler').TypeCheck<any>} compiled - Compiled TypeCheck validator.
 * @param {unknown} data - Data to validate.
 * @returns {Array<{ path: string, message: string, type: number }>} Array of error descriptors.
 */
function getValidationErrors(compiled, data) {
  return [...compiled.Errors(data)].map((err) => ({
    path: err.path,
    message: err.message,
    type: err.type
  }));
}

/**
 * Returns the generated JavaScript validation source code for a schema.
 * @param {import('@sinclair/typebox').TSchema} schema - The TypeBox schema definition.
 * @returns {string} The generated validation function code.
 */
function inspectCompiledCode(schema) {
  return TypeCompiler.Code(schema);
}

module.exports = {
  Type,
  TypeCompiler,
  compileSchema,
  isValid,
  getValidationErrors,
  inspectCompiledCode
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  Type,
  TypeCompiler,
  compileSchema,
  isValid,
  getValidationErrors,
  inspectCompiledCode
} = require('../src/index.js');

// 1. Export verification
assert.strictEqual(typeof TypeCompiler, 'object', 'TypeCompiler must be exported');
assert.strictEqual(typeof TypeCompiler.Compile, 'function', 'TypeCompiler.Compile must be a function');
assert.strictEqual(typeof TypeCompiler.Code, 'function', 'TypeCompiler.Code must be a function');
assert.strictEqual(typeof compileSchema, 'function', 'compileSchema must be a function');
assert.strictEqual(typeof isValid, 'function', 'isValid must be a function');
assert.strictEqual(typeof getValidationErrors, 'function', 'getValidationErrors must be a function');

// 2. TypeCompiler compiles a TypeBox schema into an executable validator
const userSchema = Type.Object({
  id: Type.Integer({ minimum: 1 }),
  username: Type.String({ minLength: 3 }),
  roles: Type.Array(Type.String()),
  settings: Type.Optional(
    Type.Object({
      notifications: Type.Boolean()
    })
  )
});

const validator = compileSchema(userSchema);
assert.strictEqual(typeof validator.Check, 'function', 'Validator should have Check method');
assert.strictEqual(typeof validator.Errors, 'function', 'Validator should have Errors method');
assert.strictEqual(typeof validator.Code, 'function', 'Validator should have Code method');

// 3. Compiled validator Check returns true for valid data matching schema constraints
const validUserA = {
  id: 42,
  username: 'alice',
  roles: ['admin', 'user'],
  settings: {
    notifications: true
  }
};
const validUserB = {
  id: 1,
  username: 'bob',
  roles: []
};

assert.strictEqual(isValid(validator, validUserA), true, 'Valid user A should pass validation');
assert.strictEqual(isValid(validator, validUserB), true, 'Valid user B (without optional settings) should pass validation');

// 4. Compiled validator Check returns false for invalid data violating schema constraints
const invalidUserA = {
  id: 0, // minimum is 1
  username: 'al', // minLength is 3
  roles: 'not-an-array'
};
const invalidUserB = {
  id: '42', // string instead of integer
  username: 'charlie',
  roles: [123] // number instead of string
};

assert.strictEqual(isValid(validator, invalidUserA), false, 'Invalid user A should fail validation');
assert.strictEqual(isValid(validator, invalidUserB), false, 'Invalid user B should fail validation');

// 5. Compiled validator Errors yields structured error objects with path and message for invalid fields
const errorsA = getValidationErrors(validator, invalidUserA);
assert(Array.isArray(errorsA), 'Errors should be an array');
assert(errorsA.length >= 3, 'Should produce at least 3 errors for invalid user A');

const paths = errorsA.map((e) => e.path);
assert(paths.includes('/id'), 'Errors should include path /id');
assert(paths.includes('/username'), 'Errors should include path /username');
assert(paths.includes('/roles'), 'Errors should include path /roles');

// 6. TypeCompiler.Code and compiled validator Code return generated JavaScript validator code string
const codeFromMethod = validator.Code();
const codeFromCompiler = inspectCompiledCode(userSchema);

assert.strictEqual(typeof codeFromMethod, 'string', 'validator.Code() should return string');
assert.strictEqual(typeof codeFromCompiler, 'string', 'TypeCompiler.Code() should return string');
assert(codeFromMethod.includes('return function check(value)'), 'Compiled code should define check function');
assert(codeFromCompiler.includes('return function check(value)'), 'inspectCompiledCode should define check function');

console.log('Contract tests passed successfully.');

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

аноним