CodeSampleX

Пример

tslib 2.8.1: __assign, __rest, __spreadArray

Проверенный пример — npm tslib 2.8.1: __assign, __rest, __spreadArray. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:9d90614e2da1c07480456eab71e334abd9b4e8f9fc2bd9b864554d8da26465ff

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

Кейс

HOW
Цель
verify pkg:npm/tslib@2.8.1
Пакеты
Символы
  • __assign
  • __rest
  • __spreadArray
  • __awaiter
  • __values
  • __read
  • __importDefault
Окружение
node 22.23.2
Создан
2026-08-23T13:28:36Z

Контракт

  1. __assign merges own enumerable properties from source objects into a target object
  2. __rest creates a shallow copy of an object omitting specified property keys
  3. __spreadArray concatenates elements and arrays according to spread semantics
  4. __awaiter executes generator functions as asynchronous operations returning a Promise
  5. __values extracts iterator instances from iterable objects
  6. __read extracts up to n elements from an iterable into an array
  7. __importDefault wraps modules without __esModule flag in a default property container

Файлы

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

Скачать артефакт с исходным кодом (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/tslib@2.8.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/tslib@2.8.1

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:3ee9f555cdd1556bd20f12441c6b219bc3fd552d722c7d5c1e0ac787e152d888","constraints":{"executionContext":"node"},"contract":["__assign merges own enumerable properties from source objects into a target object","__rest creates a shallow copy of an object omitting specified property keys","__spreadArray concatenates elements and arrays according to spread semantics","__awaiter executes generator functions as asynchronous operations returning a Promise","__values extracts iterator instances from iterable objects","__read extracts up to n elements from an iterable into an array","__importDefault wraps modules without __esModule flag in a default property container"],"goal":"verify pkg:npm/tslib@2.8.1","kind":"HOW","packages":["pkg:npm/tslib@2.8.1"],"schemaVersion":1,"symbols":["__assign","__rest","__spreadArray","__awaiter","__values","__read","__importDefault"]},"contractCommand":["node","test/contract.js"],"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/tslib@2.8.1"],"schemaVersion":1,"subject":"pkg:npm/tslib@2.8.1","symbols":["__assign","__rest","__spreadArray","__awaiter","__values","__read","__importDefault"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-tslib",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-tslib",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "tslib": "2.8.1"
      }
    },
    "node_modules/tslib": {
      "version": "2.8.1",
      "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
      "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
      "license": "0BSD"
    }
  }
}
package.json
{
  "name": "sample-tslib",
  "version": "1.0.0",
  "license": "MIT-0",
  "dependencies": {
    "tslib": "2.8.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/tslib@2.8.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/tslib@2.8.1"
  ]
}
src/index.js
'use strict';

const tslib = require('tslib');

/**
 * Merges properties from source objects into a target object.
 * @param {object} target - Target object.
 * @param {...object} sources - Source objects.
 * @returns {object} The mutated target object.
 */
function mergeObjects(target, ...sources) {
  return tslib.__assign(target, ...sources);
}

/**
 * Creates a shallow copy of an object omitting specified property keys.
 * @param {object} obj - Source object.
 * @param {string[]} keys - Keys to omit.
 * @returns {object} New object without the omitted keys.
 */
function omitKeys(obj, keys) {
  return tslib.__rest(obj, keys);
}

/**
 * Concatenates an array or elements into a target array according to spread semantics.
 * @param {Array} to - Target array.
 * @param {Array} from - Source array to spread.
 * @param {boolean} [pack=false] - Whether arguments are packed.
 * @returns {Array} Combined array.
 */
function combineArrays(to, from, pack) {
  return tslib.__spreadArray(to, from, pack);
}

/**
 * Executes a generator function as an asynchronous task returning a Promise.
 * @param {*} thisArg - The this context for the generator.
 * @param {function(): Generator} generatorFunc - Generator function to execute.
 * @returns {Promise<*>} Promise resolving with the return value of generator.
 */
function runAsyncGenerator(thisArg, generatorFunc) {
  return tslib.__awaiter(thisArg, void 0, void 0, generatorFunc);
}

/**
 * Extracts an iterator from an iterable object.
 * @param {Iterable<*>} iterable - Iterable object.
 * @returns {Iterator<*>} Iterator instance.
 */
function getIterableValues(iterable) {
  return tslib.__values(iterable);
}

/**
 * Extracts up to count elements from an iterable into an array.
 * @param {Iterable<*>} iterable - Source iterable.
 * @param {number} [count] - Maximum elements to read.
 * @returns {Array} Array of read elements.
 */
function takeElements(iterable, count) {
  return tslib.__read(iterable, count);
}

/**
 * Wraps a module object for ES default import interop if needed.
 * @param {*} mod - Module to import.
 * @returns {*} Object containing the module or default export.
 */
function interopDefault(mod) {
  return tslib.__importDefault(mod);
}

module.exports = {
  mergeObjects,
  omitKeys,
  combineArrays,
  runAsyncGenerator,
  getIterableValues,
  takeElements,
  interopDefault,
};
test/contract.js
'use strict';

const assert = require('node:assert/strict');
const {
  mergeObjects,
  omitKeys,
  combineArrays,
  runAsyncGenerator,
  getIterableValues,
  takeElements,
  interopDefault,
} = require('../src/index.js');

// Contract 1: __assign merges own enumerable properties from source objects into a target object
{
  const target = { a: 1 };
  const source1 = { b: 2 };
  const source2 = { c: 3, a: 10 };
  const result = mergeObjects(target, source1, source2);
  assert.strictEqual(result, target, 'mergeObjects should mutate and return the target object');
  assert.deepStrictEqual(result, { a: 10, b: 2, c: 3 });
}

// Contract 2: __rest creates a shallow copy of an object omitting specified property keys
{
  const original = { id: 101, name: 'Alice', role: 'admin', active: true };
  const restObj = omitKeys(original, ['role', 'active']);
  assert.deepStrictEqual(restObj, { id: 101, name: 'Alice' });
  assert.strictEqual('role' in restObj, false);
  assert.strictEqual('active' in restObj, false);
}

// Contract 3: __spreadArray concatenates elements and arrays according to spread semantics
{
  const arr1 = [1, 2];
  const arr2 = [3, 4];
  const combined = combineArrays(arr1, arr2, true);
  assert.deepStrictEqual(combined, [1, 2, 3, 4]);

  const cloned = combineArrays([], [10, 20], true);
  assert.deepStrictEqual(cloned, [10, 20]);
}

// Contract 4: __awaiter executes generator functions as asynchronous operations returning a Promise
async function testAsyncRunner() {
  const promise = runAsyncGenerator(null, function* () {
    const step1 = yield Promise.resolve(21);
    const step2 = yield Promise.resolve(step1 * 2);
    return step2;
  });

  assert.ok(promise instanceof Promise, 'runAsyncGenerator should return a Promise');
  const finalValue = await promise;
  assert.strictEqual(finalValue, 42, 'runAsyncGenerator should evaluate generator and resolve result');
}

// Contract 5: __values extracts iterator instances from iterable objects
{
  const numbers = [100, 200, 300];
  const iterator = getIterableValues(numbers);
  assert.strictEqual(typeof iterator.next, 'function');
  assert.deepStrictEqual(iterator.next(), { value: 100, done: false });
  assert.deepStrictEqual(iterator.next(), { value: 200, done: false });
  assert.deepStrictEqual(iterator.next(), { value: 300, done: false });
  assert.strictEqual(iterator.next().done, true);
}

// Contract 6: __read extracts up to n elements from an iterable into an array
{
  const set = new Set(['first', 'second', 'third']);
  const firstTwo = takeElements(set, 2);
  assert.deepStrictEqual(firstTwo, ['first', 'second']);

  const allElements = takeElements(set);
  assert.deepStrictEqual(allElements, ['first', 'second', 'third']);
}

// Contract 7: __importDefault wraps modules without __esModule flag in a default property container
{
  const plainCjs = { version: '1.0.0' };
  const wrapped = interopDefault(plainCjs);
  assert.deepStrictEqual(wrapped, { default: { version: '1.0.0' } });

  const esModule = { __esModule: true, default: 'exportedDefault' };
  const unchanged = interopDefault(esModule);
  assert.strictEqual(unchanged, esModule);
}

(async () => {
  await testAsyncRunner();
  console.log('All contract tests passed successfully.');
})();

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

аноним