CodeSampleX

Пример

detect-node 2.1.0: detect if code is running in node environment

Проверенный пример — npm detect-node 2.1.0: detect if code is running in node environment. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:4ac0fa8b7a486cc7cd27be3530094e1e8bfb26c79395415a97b5393cdcca367f

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

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 npm

Среды запусков проверки

Окружение Контракт Этапы Запуск
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
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

Кейс

HOW
Цель
detect if code is running in node environment
Пакеты
Символы
  • detect-node
Создан
2026-08-26T09:03:16Z

Контракт

  1. detect-node CommonJS export evaluates to a boolean
  2. detect-node evaluates to true when executed in Node.js environment
  3. detect-node ES module default export evaluates to true in Node.js
  4. wrapped helper function returns boolean true
  5. detect-node matches Object.prototype.toString check on global process object
  6. detect-node browser fallback entry exports false

Файлы

  • 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: detect if code is running in node environment
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/detect-node@2.1.0
Demonstrate these symbols/APIs:
  - detect-node

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:61480310920d66dae1814660cf183b7b218fb90746ac69d65cd770ae95e62dbc","contract":["detect-node CommonJS export evaluates to a boolean","detect-node evaluates to true when executed in Node.js environment","detect-node ES module default export evaluates to true in Node.js","wrapped helper function returns boolean true","detect-node matches Object.prototype.toString check on global process object","detect-node browser fallback entry exports false"],"goal":"detect if code is running in node environment","kind":"HOW","packages":["pkg:npm/detect-node@2.1.0"],"schemaVersion":1,"symbols":["detect-node"]},"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/detect-node@2.1.0"],"schemaVersion":1,"subject":"pkg:npm/detect-node@2.1.0","symbols":["detect-node"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-detect-node",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-detect-node",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "detect-node": "2.1.0"
      }
    },
    "node_modules/detect-node": {
      "version": "2.1.0",
      "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz",
      "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-detect-node",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for detect-node@2.1.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "detect-node": "2.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "detect if code is running in node environment",
  "kind": "HOW",
  "packages": [
    "pkg:npm/detect-node@2.1.0"
  ],
  "symbols": [
    "detect-node"
  ]
}
src/index.js
const isNode = require('detect-node');

/**
 * Checks if the current runtime execution environment is Node.js.
 *
 * @returns {boolean} True if running in Node.js environment, false otherwise.
 */
function checkIsNode() {
  return isNode;
}

module.exports = {
  isNode,
  checkIsNode
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import isNodeEsm from 'detect-node';

const require = createRequire(import.meta.url);
const isNodeCjs = require('detect-node');
const { isNode, checkIsNode } = require('../src/index.js');
const browserExport = require('detect-node/browser.js');

async function testAll() {
  // 1. detect-node CommonJS export evaluates to a boolean
  assert.equal(typeof isNodeCjs, 'boolean', 'detect-node CJS export must be boolean');

  // 2. detect-node evaluates to true when executed in Node.js environment
  assert.equal(isNodeCjs, true, 'detect-node CJS export must be true in Node.js');

  // 3. detect-node ES module default export evaluates to true in Node.js
  assert.equal(typeof isNodeEsm, 'boolean', 'detect-node ESM default export must be boolean');
  assert.equal(isNodeEsm, true, 'detect-node ESM export must be true in Node.js');

  // 4. wrapped helper function returns boolean true
  assert.equal(typeof checkIsNode, 'function', 'checkIsNode must be a function');
  assert.equal(checkIsNode(), true, 'checkIsNode() must return true in Node.js');
  assert.equal(isNode, true, 'exported isNode must be true');

  // 5. detect-node matches Object.prototype.toString check on global process object
  const expectedProcessCheck = Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
  assert.equal(isNodeCjs, expectedProcessCheck, 'detect-node value must match Object.prototype.toString process check');

  // 6. detect-node browser fallback entry exports false
  assert.equal(browserExport, false, 'detect-node browser entry must export false');

  console.log('All detect-node contract tests passed.');
}

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

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

аноним