CodeSampleX

Sample

@sinclair/typebox 0.27.8: Value.Cast

Verified sample for npm @sinclair/typebox 0.27.8: Value.Cast. The contract ran on node 22 · linux alpine/x64 · docker and passed.

sha256:5f11a7f6590a0f981dc1fb894e20f3d7719b503dca90f34b593dfcd005e38ae0

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 npm

Verification-run environments

Environment Contract Stages Run
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

Case

HOW
Goal
verify Value.Cast in pkg:npm/%40sinclair/typebox@0.27.8
Packages
Symbols
  • Value.Cast
Created
2026-08-29T05:40:40Z

Contract

  1. Value.Cast preserves valid primitive, object, and array values that already conform to schema
  2. Value.Cast applies explicit default metadata on invalid or missing properties
  3. Value.Cast substitutes type-level default values when invalid primitive types are encountered without explicit default
  4. Value.Cast reconstructs missing or partially missing object properties while retaining conforming fields
  5. Value.Cast casts each item in an array to match the element schema
  6. Value.Cast falls back to the first union variant when a value does not match any union branch
  7. Value.Cast respects optional fields by keeping undefined when not provided in the input object
  8. Value.Check confirms that cast values satisfy schema validation

Files

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

Download the source artifact (tar.gz)

Source

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.Cast 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.Cast

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:a40ddfeb690fe036773bf06ea1c44e7e3d3ecd7d3f3151a5edbf78bbefba6b32","contract":["Value.Cast preserves valid primitive, object, and array values that already conform to schema","Value.Cast applies explicit default metadata on invalid or missing properties","Value.Cast substitutes type-level default values when invalid primitive types are encountered without explicit default","Value.Cast reconstructs missing or partially missing object properties while retaining conforming fields","Value.Cast casts each item in an array to match the element schema","Value.Cast falls back to the first union variant when a value does not match any union branch","Value.Cast respects optional fields by keeping undefined when not provided in the input object","Value.Check confirms that cast values satisfy schema validation"],"goal":"verify Value.Cast in pkg:npm/%40sinclair/typebox@0.27.8","kind":"HOW","packages":["pkg:npm/%40sinclair/typebox@0.27.8"],"schemaVersion":1,"symbols":["Value.Cast"]},"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/%40sinclair/typebox@0.27.8"],"schemaVersion":1,"subject":"pkg:npm/%40sinclair/typebox@0.27.8","symbols":["Value.Cast"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { Type } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';

/**
 * Casts a value to conform to the specified TypeBox schema.
 * Replaces invalid properties and fills missing properties with schema defaults or standard type defaults.
 *
 * @param {import('@sinclair/typebox').TSchema} schema - TypeBox schema
 * @param {unknown} value - Value to cast
 * @returns {any} Cast value conforming to the schema
 */
export function castValue(schema, value) {
  return Value.Cast(schema, value);
}

/**
 * Casts and checks whether the result conforms to the schema.
 *
 * @param {import('@sinclair/typebox').TSchema} schema - TypeBox schema
 * @param {unknown} value - Value to cast
 * @returns {{ value: any, valid: boolean }} Object containing cast value and validity
 */
export function castAndValidate(schema, value) {
  const result = Value.Cast(schema, value);
  const valid = Value.Check(schema, result);
  return { value: result, valid };
}

export { Type, Value };
export default {
  castValue,
  castAndValidate,
  Type,
  Value,
};
package-lock.json
{
  "name": "sample-typebox-value-cast",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-typebox-value-cast",
      "version": "1.0.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-cast",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "dependencies": {
    "@sinclair/typebox": "0.27.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Value.Cast in pkg:npm/%40sinclair/typebox@0.27.8",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40sinclair/typebox@0.27.8"
  ],
  "symbols": [
    "Value.Cast"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { Type, Value, castValue, castAndValidate } from '../index.mjs';

// Contract 1: Value.Cast preserves valid primitive, object, and array values that already conform to schema
{
  const numSchema = Type.Number();
  assert.strictEqual(Value.Cast(numSchema, 42), 42);
  assert.strictEqual(castValue(numSchema, 42), 42);

  const strSchema = Type.String();
  assert.strictEqual(Value.Cast(strSchema, 'hello'), 'hello');

  const objSchema = Type.Object({
    id: Type.Number(),
    active: Type.Boolean(),
  });
  const validObj = { id: 1, active: true };
  assert.deepStrictEqual(Value.Cast(objSchema, validObj), { id: 1, active: true });

  const arrSchema = Type.Array(Type.String());
  const validArr = ['alpha', 'beta'];
  assert.deepStrictEqual(Value.Cast(arrSchema, validArr), ['alpha', 'beta']);
}

// Contract 2: Value.Cast applies explicit default metadata on invalid or missing properties
{
  const schemaWithDefaults = Type.Object({
    port: Type.Number({ default: 8080 }),
    host: Type.String({ default: 'localhost' }),
    debug: Type.Boolean({ default: false }),
  });

  const emptyInput = {};
  const castedEmpty = Value.Cast(schemaWithDefaults, emptyInput);
  assert.deepStrictEqual(castedEmpty, {
    port: 8080,
    host: 'localhost',
    debug: false,
  });

  const invalidTypesInput = { port: 'not-a-port', host: 12345 };
  const castedInvalid = Value.Cast(schemaWithDefaults, invalidTypesInput);
  assert.deepStrictEqual(castedInvalid, {
    port: 8080,
    host: 'localhost',
    debug: false,
  });
}

// Contract 3: Value.Cast substitutes type-level default values when invalid primitive types are encountered without explicit default
{
  assert.strictEqual(Value.Cast(Type.String(), 123), '');
  assert.strictEqual(Value.Cast(Type.Number(), 'abc'), 0);
  assert.strictEqual(Value.Cast(Type.Boolean(), 'yes'), false);
}

// Contract 4: Value.Cast reconstructs missing or partially missing object properties while retaining conforming fields
{
  const userSchema = Type.Object({
    name: Type.String(),
    age: Type.Number({ default: 20 }),
    email: Type.String({ default: 'user@example.com' }),
  });

  const partialInput = { name: 'Alice' };
  const castedUser = Value.Cast(userSchema, partialInput);
  assert.deepStrictEqual(castedUser, {
    name: 'Alice',
    age: 20,
    email: 'user@example.com',
  });
}

// Contract 5: Value.Cast casts each item in an array to match the element schema
{
  const numberArraySchema = Type.Array(Type.Number({ default: 1 }));
  const mixedArray = [10, 'invalid', 30, null];
  const castedArray = Value.Cast(numberArraySchema, mixedArray);
  assert.deepStrictEqual(castedArray, [10, 1, 30, 1]);
}

// Contract 6: Value.Cast falls back to the first union variant when a value does not match any union branch
{
  const statusUnion = Type.Union([
    Type.Literal('pending'),
    Type.Literal('active'),
    Type.Literal('suspended'),
  ]);

  assert.strictEqual(Value.Cast(statusUnion, 'active'), 'active');
  assert.strictEqual(Value.Cast(statusUnion, 'unknown_status'), 'pending');
}

// Contract 7: Value.Cast respects optional fields by keeping undefined when not provided in the input object
{
  const schemaWithOptional = Type.Object({
    requiredKey: Type.String(),
    optionalKey: Type.Optional(Type.String()),
  });

  const castedWithoutOptional = Value.Cast(schemaWithOptional, { requiredKey: 'value' });
  assert.deepStrictEqual(castedWithoutOptional, { requiredKey: 'value' });
  assert.strictEqual('optionalKey' in castedWithoutOptional, false);
}

// Contract 8: Value.Check confirms that cast values satisfy schema validation
{
  const complexSchema = Type.Object({
    user: Type.Object({
      name: Type.String(),
      role: Type.Union([Type.Literal('admin'), Type.Literal('user')], { default: 'user' }),
    }),
    tags: Type.Array(Type.String()),
  });

  const { value, valid } = castAndValidate(complexSchema, { user: {} });
  assert.strictEqual(valid, true);
  assert.strictEqual(Value.Check(complexSchema, value), true);
  assert.deepStrictEqual(value, {
    user: {
      name: '',
      role: 'user',
    },
    tags: [],
  });
}

console.log('All Value.Cast contracts passed.');

Origin Seeder

anonymous