CodeSampleX

示例

chai 5.3.3

已验证示例 — npm chai 5.3.3. contract 在 node 22 · linux alpine/x64 · docker 上运行并通过: expect validates type checks, nested properties, array inclusions, and deep…

sha256:239e87c15b12de39cb023e728fefabc45cce4ac7c1581079b464101071a427d4

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

案例

HOW
目标
verify pkg:npm/chai@5.3.3
包
环境
node 22.23.2
创建时间
2026-08-26T09:19:19Z

契约

  1. expect validates type checks, nested properties, array inclusions, and deep equality
  2. expect verifies thrown errors matching type and message
  3. should interface attaches chainable assertions to Object.prototype
  4. chai.use enables custom plugin assertions on Assertion prototype
  5. assert provides classic TDD assertions including strictEqual, deepEqual, and throws
  6. AssertionError is thrown on failed assertions

文件

  • 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 pkg:npm/chai@5.3.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/chai@5.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:1a53cb897ec511fb003f74d40fad6b7ac6b9e91172b863f9f19641236fcbc783","constraints":{"executionContext":"node"},"contract":["expect validates type checks, nested properties, array inclusions, and deep equality","expect verifies thrown errors matching type and message","should interface attaches chainable assertions to Object.prototype","chai.use enables custom plugin assertions on Assertion prototype","assert provides classic TDD assertions including strictEqual, deepEqual, and throws","AssertionError is thrown on failed assertions"],"goal":"verify pkg:npm/chai@5.3.3","kind":"HOW","packages":["pkg:npm/chai@5.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/chai@5.3.3"],"schemaVersion":1,"subject":"pkg:npm/chai@5.3.3","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-chai",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-chai",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "chai": "5.3.3"
      }
    },
    "node_modules/assertion-error": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
      "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/chai": {
      "version": "5.3.3",
      "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
      "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
      "license": "MIT",
      "dependencies": {
        "assertion-error": "^2.0.1",
        "check-error": "^2.1.1",
        "deep-eql": "^5.0.1",
        "loupe": "^3.1.0",
        "pathval": "^2.0.0"
      },
      "engines": {
        "node": ">=18"
      }
    },
    "node_modules/check-error": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
      "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
      "license": "MIT",
      "engines": {
        "node": ">= 16"
      }
    },
    "node_modules/deep-eql": {
      "version": "5.0.2",
      "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
      "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      }
    },
    "node_modules/loupe": {
      "version": "3.2.1",
      "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
      "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
      "license": "MIT"
    },
    "node_modules/pathval": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
      "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
      "license": "MIT",
      "engines": {
        "node": ">= 14.16"
      }
    }
  }
}
package.json
{
  "name": "sample-chai",
  "version": "1.0.0",
  "description": "Clean-room verification of chai assertions, should interface, and plugin extensions",
  "type": "module",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "chai": "5.3.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/chai@5.3.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/chai@5.3.3"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
import * as chai from 'chai';

const { expect, assert, AssertionError, use } = chai;

/**
 * Validates object properties and types using chai expect style.
 *
 * @param {Record<string, unknown>} target
 * @param {Record<string, string>} schema
 * @returns {boolean}
 */
export function validateObjectWithExpect(target, schema) {
  expect(target, 'target must be an object').to.be.an('object').that.is.not.null;
  for (const [key, typeStr] of Object.entries(schema)) {
    expect(target, `property ${key} must exist`).to.have.property(key);
    expect(typeof target[key], `property ${key} must have type ${typeStr}`).to.equal(typeStr);
  }
  return true;
}

/**
 * Validates value using chai should style.
 *
 * @param {any} value
 * @returns {boolean}
 */
export function setupAndValidateShould(value) {
  const should = chai.should();
  should.exist(value);
  value.should.be.an('object');
  return true;
}

/**
 * Registers a custom Chai plugin that adds a `.positiveNumber` chainable property.
 *
 * @returns {void}
 */
export function registerPositiveNumberPlugin() {
  use((chaiModule, utils) => {
    utils.addProperty(chaiModule.Assertion.prototype, 'positiveNumber', function () {
      const obj = this._obj;
      this.assert(
        typeof obj === 'number' && obj > 0,
        'expected #{this} to be a positive number',
        'expected #{this} to not be a positive number'
      );
    });
  });
}

/**
 * Performs assertions using chai assert style.
 *
 * @param {unknown} actual
 * @param {unknown} expected
 * @returns {boolean}
 */
export function validateWithAssert(actual, expected) {
  assert.isDefined(actual, 'actual should be defined');
  assert.deepEqual(actual, expected, 'actual and expected must match deeply');
  return true;
}

export { chai, expect, assert, AssertionError, use };
test/contract.mjs
import * as chai from 'chai';
import {
  validateObjectWithExpect,
  setupAndValidateShould,
  registerPositiveNumberPlugin,
  validateWithAssert,
  expect,
  assert,
  AssertionError,
} from '../src/index.js';

async function runContract() {
  // 1. expect validates type checks, nested properties, array inclusions, and deep equality
  expect('sample-text').to.be.a('string').and.to.equal('sample-text');
  expect([1, 2, 3]).to.be.an('array').that.includes(2);
  expect({ a: { b: 42 } }).to.have.nested.property('a.b', 42);
  expect({ x: 1, y: [2, 3] }).to.deep.equal({ x: 1, y: [2, 3] });
  assert.isTrue(
    validateObjectWithExpect({ id: 10, name: 'chai' }, { id: 'number', name: 'string' }),
    'validateObjectWithExpect should pass'
  );

  // 2. expect verifies thrown errors matching type and message
  const throwingFn = () => {
    throw new RangeError('out of bounds index');
  };
  expect(throwingFn).to.throw(RangeError, /bounds/);

  // 3. should interface attaches chainable assertions to Object.prototype
  const should = chai.should();
  should.exist({ active: true });
  ({ status: 200, label: 'ok' }).should.have.property('status').equal(200);
  assert.isTrue(setupAndValidateShould({ ready: true }), 'setupAndValidateShould should pass');

  // 4. chai.use enables custom plugin assertions on Assertion prototype
  registerPositiveNumberPlugin();
  expect(100).to.be.a.positiveNumber;
  let pluginError = null;
  try {
    expect(-5).to.be.a.positiveNumber;
  } catch (err) {
    pluginError = err;
  }
  assert.isNotNull(pluginError, 'custom plugin should reject negative numbers');
  assert.instanceOf(pluginError, AssertionError, 'plugin error should be AssertionError');

  // 5. assert provides classic TDD assertions including strictEqual, deepEqual, and throws
  assert.strictEqual('val', 'val', 'strict equality check');
  assert.isAbove(10, 5, 'number range check');
  assert.isTrue(validateWithAssert({ k: 1 }, { k: 1 }), 'validateWithAssert should pass');
  assert.throws(() => {
    throw new Error('fail');
  }, Error, 'fail');

  // 6. AssertionError is thrown on failed assertions
  let caught = null;
  try {
    expect(1).to.equal(2);
  } catch (err) {
    caught = err;
  }
  assert.isNotNull(caught, 'expect failure must throw');
  assert.instanceOf(caught, AssertionError, 'thrown error must be instance of AssertionError');

  console.log('Contract assertions passed.');
}

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

原始种子者

匿名