CodeSampleX

サンプル

@sinclair/typebox 0.27.8: Value

検証済みサンプル — npm @sinclair/typebox 0.27.8: Value. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: Value.Check validates objects against schemas and…

sha256:36c552342821f64249368981bccad0ffdc13ccf234ca425cf51df483595ee837

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 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-29

ケース

HOW
ゴール
verify Value in pkg:npm/%40sinclair/typebox@0.27.8
パッケージ
シンボル
  • Value
環境
node 22.23.2
作成日
2026-08-29T05:26:56Z

コントラクト

  1. Value.Check validates objects against schemas and returns boolean validation status
  2. Value.Errors reports structured errors with path and descriptive message for invalid payloads
  3. Value.Cast applies default values and coerces structure to conform to target schema
  4. Value.Create generates minimal valid instances satisfying schema property constraints and defaults
  5. Value.Convert coerces string representations of primitives into matching schema types
  6. Value.Equal performs deep structural equality comparison between values
  7. Value.Clone creates independent deep copies of complex nested data structures
  8. Value.Diff and Value.Patch compute and apply structural delta changesets between objects
  9. Value.Mutate updates target object properties in-place to mirror source values
  10. Value.Hash produces consistent 64-bit deterministic hash invariant to object key ordering

ファイル

  • 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 Value in pkg:npm/%40sinclair/typebox@0.27.8
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40sinclair/typebox@0.27.8
Demonstrate these symbols/APIs:
  - Value

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:08546b4001fc3945339e7b4a013dff12d3691a8321ce970672a9670210026445","constraints":{"executionContext":"node"},"contract":["Value.Check validates objects against schemas and returns boolean validation status","Value.Errors reports structured errors with path and descriptive message for invalid payloads","Value.Cast applies default values and coerces structure to conform to target schema","Value.Create generates minimal valid instances satisfying schema property constraints and defaults","Value.Convert coerces string representations of primitives into matching schema types","Value.Equal performs deep structural equality comparison between values","Value.Clone creates independent deep copies of complex nested data structures","Value.Diff and Value.Patch compute and apply structural delta changesets between objects","Value.Mutate updates target object properties in-place to mirror source values","Value.Hash produces consistent 64-bit deterministic hash invariant to object key ordering"],"goal":"verify Value in pkg:npm/%40sinclair/typebox@0.27.8","kind":"HOW","packages":["pkg:npm/%40sinclair/typebox@0.27.8"],"schemaVersion":1,"symbols":["Value"]},"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.8"],"schemaVersion":1,"subject":"pkg:npm/%40sinclair/typebox@0.27.8","symbols":["Value"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-typebox-value",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-typebox-value",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@sinclair/typebox": "0.27.8"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.27.8",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz",
      "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-typebox-value",
  "version": "1.0.0",
  "private": true,
  "type": "commonjs",
  "license": "MIT-0",
  "dependencies": {
    "@sinclair/typebox": "0.27.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Value in pkg:npm/%40sinclair/typebox@0.27.8",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinclair/typebox@0.27.8"
  ],
  "symbols": [
    "Value"
  ]
}
src/index.js
const { Type, FormatRegistry } = require('@sinclair/typebox');
const { Value } = require('@sinclair/typebox/value');

// Register email format validator if not already registered
if (!FormatRegistry.Has('email')) {
  FormatRegistry.Set('email', (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value));
}

const UserProfileSchema = Type.Object({
  id: Type.Number({ minimum: 1 }),
  username: Type.String({ minLength: 2, maxLength: 50 }),
  email: Type.String({ format: 'email', default: 'user@example.com' }),
  role: Type.Union([Type.Literal('admin'), Type.Literal('member'), Type.Literal('guest')]),
  preferences: Type.Object({
    theme: Type.Union([Type.Literal('light'), Type.Literal('dark')]),
    notifications: Type.Boolean({ default: true })
  }, { default: { theme: 'light', notifications: true } }),
  tags: Type.Array(Type.String(), { default: [] })
}, { additionalProperties: false });

/**
 * Validates a value against a schema.
 * @param {import('@sinclair/typebox').TSchema} schema
 * @param {unknown} value
 * @returns {boolean}
 */
function isValid(schema, value) {
  return Value.Check(schema, value);
}

/**
 * Returns structured validation errors.
 * @param {import('@sinclair/typebox').TSchema} schema
 * @param {unknown} value
 * @returns {Array<{ path: string, message: string, type: number }>}
 */
function getValidationErrors(schema, value) {
  const errors = [];
  for (const error of Value.Errors(schema, value)) {
    errors.push({
      path: error.path,
      message: error.message,
      type: error.type
    });
  }
  return errors;
}

/**
 * Casts a value into schema shape by applying defaults.
 * @param {import('@sinclair/typebox').TSchema} schema
 * @param {unknown} value
 * @returns {unknown}
 */
function castToSchema(schema, value) {
  return Value.Cast(schema, value);
}

/**
 * Creates default instance satisfying schema.
 * @param {import('@sinclair/typebox').TSchema} schema
 * @returns {unknown}
 */
function createDefault(schema) {
  return Value.Create(schema);
}

/**
 * Converts string values into schema types where possible.
 * @param {import('@sinclair/typebox').TSchema} schema
 * @param {unknown} value
 * @returns {unknown}
 */
function convertTypes(schema, value) {
  return Value.Convert(schema, value);
}

/**
 * Checks structural equality between two values.
 * @param {unknown} left
 * @param {unknown} right
 * @returns {boolean}
 */
function areEqual(left, right) {
  return Value.Equal(left, right);
}

/**
 * Deep clones a value.
 * @template T
 * @param {T} value
 * @returns {T}
 */
function cloneValue(value) {
  return Value.Clone(value);
}

/**
 * Calculates diff operations and patches an object.
 * @param {unknown} original
 * @param {unknown} target
 * @returns {{ diff: any[], patched: any }}
 */
function diffAndPatch(original, target) {
  const diff = Value.Diff(original, target);
  const patched = Value.Patch(original, diff);
  return { diff, patched };
}

/**
 * Structurally mutates target object in place to match source.
 * @param {object} target
 * @param {object} source
 */
function mutateInPlace(target, source) {
  Value.Mutate(target, source);
}

/**
 * Computes deterministic hash value.
 * @param {unknown} value
 * @returns {bigint}
 */
function hashValue(value) {
  return Value.Hash(value);
}

module.exports = {
  Type,
  Value,
  FormatRegistry,
  UserProfileSchema,
  isValid,
  getValidationErrors,
  castToSchema,
  createDefault,
  convertTypes,
  areEqual,
  cloneValue,
  diffAndPatch,
  mutateInPlace,
  hashValue
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  Type,
  Value,
  UserProfileSchema,
  isValid,
  getValidationErrors,
  castToSchema,
  createDefault,
  convertTypes,
  areEqual,
  cloneValue,
  diffAndPatch,
  mutateInPlace,
  hashValue
} = require('../src/index.js');

// 1. Value.Check validates objects against schemas and returns boolean validation status
const validProfile = {
  id: 1,
  username: 'alice',
  email: 'alice@example.com',
  role: 'admin',
  preferences: {
    theme: 'dark',
    notifications: false
  },
  tags: ['admin', 'engineering']
};
assert.equal(isValid(UserProfileSchema, validProfile), true, 'validProfile should pass Value.Check');
assert.equal(Value.Check(UserProfileSchema, validProfile), true, 'Value.Check direct call should be true');

const invalidProfile = {
  id: -1, // fails minimum 1
  username: 'a', // fails minLength 2
  email: 'not-an-email',
  role: 'invalid_role',
  preferences: {
    theme: 'blue'
  }
};
assert.equal(isValid(UserProfileSchema, invalidProfile), false, 'invalidProfile should fail Value.Check');
assert.equal(Value.Check(UserProfileSchema, invalidProfile), false, 'Value.Check direct call should be false');

// 2. Value.Errors reports structured errors with path and descriptive message for invalid payloads
const errors = getValidationErrors(UserProfileSchema, invalidProfile);
assert.ok(errors.length >= 4, 'Should contain at least 4 errors');
assert.ok(errors.some(e => e.path === '/id'), 'Errors should include path /id');
assert.ok(errors.some(e => e.path === '/username'), 'Errors should include path /username');
assert.ok(errors.some(e => e.path === '/role'), 'Errors should include path /role');
assert.ok(errors.some(e => e.path.startsWith('/preferences')), 'Errors should include path under /preferences');

// 3. Value.Cast applies default values and coerces structure to conform to target schema
const partialProfile = {
  id: 10,
  username: 'bob',
  email: 'bob@example.com',
  role: 'member'
};
const casted = castToSchema(UserProfileSchema, partialProfile);
assert.equal(casted.id, 10);
assert.equal(casted.username, 'bob');
assert.deepEqual(casted.preferences, { theme: 'light', notifications: true }, 'Cast should populate default preferences');
assert.deepEqual(casted.tags, [], 'Cast should populate default tags array');
assert.equal(Value.Check(UserProfileSchema, casted), true, 'Casted object should satisfy schema');

// 4. Value.Create generates minimal valid instances satisfying schema property constraints and defaults
const created = createDefault(UserProfileSchema);
assert.equal(typeof created, 'object', 'Create should return an object');
assert.ok(created.id >= 1, 'Created id should respect minimum 1');
assert.ok(created.username.length >= 2, 'Created username should respect minLength 2');
assert.deepEqual(created.preferences, { theme: 'light', notifications: true }, 'Created preferences should use defaults');
assert.deepEqual(created.tags, [], 'Created tags should use default');

// 5. Value.Convert coerces string representations of primitives into matching schema types
const rawInput = {
  id: '42',
  username: 'charlie',
  email: 'charlie@example.com',
  role: 'guest',
  preferences: {
    theme: 'light',
    notifications: 'false'
  },
  tags: ['test']
};
const converted = convertTypes(UserProfileSchema, rawInput);
assert.equal(typeof converted.id, 'number', 'Convert should coerce id to number');
assert.equal(converted.id, 42);
assert.equal(typeof converted.preferences.notifications, 'boolean', 'Convert should coerce notifications to boolean');
assert.equal(converted.preferences.notifications, false);

// 6. Value.Equal performs deep structural equality comparison between values
const objA = { user: 'david', settings: { flags: [1, 2, 3] } };
const objB = { user: 'david', settings: { flags: [1, 2, 3] } };
const objC = { user: 'david', settings: { flags: [1, 2, 4] } };
assert.equal(areEqual(objA, objB), true, 'Identical structural objects should be equal');
assert.equal(areEqual(objA, objC), false, 'Different structural objects should not be equal');

// 7. Value.Clone creates independent deep copies of complex nested data structures
const originalData = { user: 'eve', nested: { counter: 100, list: ['a', 'b'] } };
const clonedData = cloneValue(originalData);
assert.deepEqual(clonedData, originalData, 'Cloned data should be deep equal to original');
clonedData.nested.counter = 200;
clonedData.nested.list.push('c');
assert.equal(originalData.nested.counter, 100, 'Original nested counter should remain unchanged');
assert.equal(originalData.nested.list.length, 2, 'Original nested list should remain unchanged');

// 8. Value.Diff and Value.Patch compute and apply structural delta changesets between objects
const baseline = { id: 1, name: 'frank', status: 'pending' };
const target = { id: 1, name: 'frank', status: 'approved', role: 'admin' };
const { diff, patched } = diffAndPatch(baseline, target);
assert.ok(Array.isArray(diff), 'Diff should return an array of operations');
assert.ok(diff.length > 0, 'Diff should contain patch operations');
assert.deepEqual(patched, target, 'Patched baseline should match target structure');

// 9. Value.Mutate updates target object properties in-place to mirror source values
const mutableTarget = { id: 5, username: 'grace', active: false };
mutateInPlace(mutableTarget, { id: 5, username: 'grace_hopper', active: true });
assert.equal(mutableTarget.username, 'grace_hopper', 'Mutate should update username in-place');
assert.equal(mutableTarget.active, true, 'Mutate should update active flag in-place');

// 10. Value.Hash produces consistent 64-bit deterministic hash invariant to object key ordering
const payloadOrder1 = { alpha: 'one', beta: 2, gamma: true };
const payloadOrder2 = { gamma: true, beta: 2, alpha: 'one' };
const hash1 = hashValue(payloadOrder1);
const hash2 = hashValue(payloadOrder2);
assert.equal(typeof hash1, 'bigint', 'Hash should return a bigint');
assert.equal(hash1, hash2, 'Hash should be invariant to key insertion order');

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

オリジンシーダー

匿名