CodeSampleX

示例

istanbul-lib-report 3.0.1: create report context with custom watermarks and check classForPercent

已验证示例 — npm istanbul-lib-report 3.0.1: create report context with custom watermarks and check classForPercent. contract 在 node 22 · linux alpine/x64 · docker…

sha256:27b7c655ddaa34dcead744ae50c60912232b0e30b26e8858a8feada9dd56db77

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 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-27

案例

HOW
目标
create report context with custom watermarks and check classForPercent
包
符号
  • createContext
  • getDefaultWatermarks
环境
node 22.23.2
创建时间
2026-08-27T16:33:46Z

契约

  1. getDefaultWatermarks returns default percentage thresholds of 50 and 80 for statements, functions, branches, and lines
  2. createContext initializes a Context instance with default directory and normalized watermarks when custom values are omitted
  3. createContext accepts custom reporting directory and watermark thresholds overriding specific coverage metric bounds
  4. Context.classForPercent classifies percentage values into low, medium, or high buckets based on configured watermark thresholds
  5. Context.classForPercent returns unknown for unrecognized coverage metric types
  6. Context.getSource retrieves file source code using custom sourceFinder function

文件

  • 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: create report context with custom watermarks and check classForPercent
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/istanbul-lib-report@3.0.1
Demonstrate these symbols/APIs:
  - createContext
  - getDefaultWatermarks

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:235ef04ec064d4dc3b1b867840f0783c191efefc084bb0b03b115fe9c3585349","contract":["getDefaultWatermarks returns default percentage thresholds of 50 and 80 for statements, functions, branches, and lines","createContext initializes a Context instance with default directory and normalized watermarks when custom values are omitted","createContext accepts custom reporting directory and watermark thresholds overriding specific coverage metric bounds","Context.classForPercent classifies percentage values into low, medium, or high buckets based on configured watermark thresholds","Context.classForPercent returns unknown for unrecognized coverage metric types","Context.getSource retrieves file source code using custom sourceFinder function"],"goal":"create report context with custom watermarks and check classForPercent","kind":"HOW","packages":["pkg:npm/istanbul-lib-report@3.0.1"],"schemaVersion":1,"symbols":["createContext","getDefaultWatermarks"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/istanbul-lib-report@3.0.1"],"schemaVersion":1,"subject":"pkg:npm/istanbul-lib-report@3.0.1","symbols":["createContext","getDefaultWatermarks"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-istanbul-lib-report",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-istanbul-lib-report",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "istanbul-lib-report": "3.0.1"
      }
    },
    "node_modules/has-flag": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
      "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/istanbul-lib-coverage": {
      "version": "3.2.2",
      "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
      "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/istanbul-lib-report": {
      "version": "3.0.1",
      "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
      "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
      "license": "BSD-3-Clause",
      "dependencies": {
        "istanbul-lib-coverage": "^3.0.0",
        "make-dir": "^4.0.0",
        "supports-color": "^7.1.0"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/make-dir": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz",
      "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
      "license": "MIT",
      "dependencies": {
        "semver": "^7.5.3"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/semver": {
      "version": "7.8.5",
      "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
      "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
      "license": "ISC",
      "bin": {
        "semver": "bin/semver.js"
      },
      "engines": {
        "node": ">=10"
      }
    },
    "node_modules/supports-color": {
      "version": "7.2.0",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
      "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    }
  }
}
package.json
{
  "name": "sample-istanbul-lib-report",
  "version": "1.0.0",
  "description": "Clean-room verification sample for istanbul-lib-report",
  "main": "src/index.js",
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "istanbul-lib-report": "3.0.1"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "create report context with custom watermarks and check classForPercent",
  "kind": "HOW",
  "packages": [
    "pkg:npm/istanbul-lib-report@3.0.1"
  ],
  "symbols": [
    "createContext",
    "getDefaultWatermarks"
  ]
}
src/index.js
import libReport from 'istanbul-lib-report';

const { createContext: createReportContext, getDefaultWatermarks: getReportDefaultWatermarks } = libReport;

/**
 * Returns standard default watermarks for coverage metrics.
 *
 * @returns {Record<string, [number, number]>} Default watermark thresholds.
 */
export function getDefaultWatermarks() {
  return getReportDefaultWatermarks();
}

/**
 * Creates an Istanbul reporting context with optional customized settings.
 *
 * @param {object} [options={}] - Configuration options for the reporting context.
 * @param {string} [options.dir] - Base directory for report generation.
 * @param {object} [options.watermarks] - Custom watermark thresholds for metrics.
 * @param {Function} [options.sourceFinder] - Custom source lookup function.
 * @param {object} [options.coverageMap] - Coverage map instance or mock.
 * @returns {object} Istanbul Context instance.
 */
export function createCoverageReportContext(options = {}) {
  const coverageMap = options.coverageMap || {
    files: () => [],
    fileCoverageFor: () => null
  };

  return createReportContext({
    dir: options.dir,
    watermarks: options.watermarks,
    sourceFinder: options.sourceFinder,
    coverageMap
  });
}

/**
 * Evaluates coverage classification ('low', 'medium', 'high', or 'unknown') for a percentage.
 *
 * @param {object} context - Istanbul Context instance.
 * @param {string} metricType - Coverage metric ('statements', 'functions', 'branches', 'lines').
 * @param {number} percent - Coverage percentage value.
 * @returns {string} Severity class name.
 */
export function evaluateCoverageClass(context, metricType, percent) {
  return context.classForPercent(metricType, percent);
}
test/contract.mjs
import assert from 'node:assert/strict';
import libReport from 'istanbul-lib-report';
import {
  getDefaultWatermarks,
  createCoverageReportContext,
  evaluateCoverageClass
} from '../src/index.js';

const { createContext, getDefaultWatermarks: getDirectDefaultWatermarks } = libReport;

// 1. getDefaultWatermarks returns default percentage thresholds of 50 and 80 for statements, functions, branches, and lines
{
  const directDefaults = getDirectDefaultWatermarks();
  const helperDefaults = getDefaultWatermarks();

  assert.deepEqual(
    directDefaults,
    {
      statements: [50, 80],
      functions: [50, 80],
      branches: [50, 80],
      lines: [50, 80]
    },
    'Direct getDefaultWatermarks must return expected 50/80 boundaries'
  );

  assert.deepEqual(
    helperDefaults,
    directDefaults,
    'Helper getDefaultWatermarks must match direct package export'
  );
}

// 2. createContext initializes a Context instance with default directory and normalized watermarks when custom values are omitted
{
  const emptyMap = {
    files: () => [],
    fileCoverageFor: () => null
  };

  const context = createContext({ coverageMap: emptyMap });
  const helperContext = createCoverageReportContext();

  assert.equal(context.dir, 'coverage', 'Default reporting directory must be "coverage"');
  assert.equal(helperContext.dir, 'coverage', 'Helper default reporting directory must be "coverage"');

  assert.deepEqual(
    context.watermarks,
    {
      statements: [50, 80],
      functions: [50, 80],
      branches: [50, 80],
      lines: [50, 80]
    },
    'Context watermarks must default to standard boundaries'
  );
}

// 3. createContext accepts custom reporting directory and watermark thresholds overriding specific coverage metric bounds
{
  const customWatermarks = {
    statements: [65, 90],
    branches: [45, 75]
  };

  const context = createCoverageReportContext({
    dir: 'custom-reports',
    watermarks: customWatermarks
  });

  assert.equal(context.dir, 'custom-reports', 'Context must use configured directory');
  assert.deepEqual(
    context.watermarks.statements,
    [65, 90],
    'Statements watermark must reflect custom configuration'
  );
  assert.deepEqual(
    context.watermarks.branches,
    [45, 75],
    'Branches watermark must reflect custom configuration'
  );
  assert.deepEqual(
    context.watermarks.functions,
    [50, 80],
    'Unspecified functions watermark must keep default boundaries'
  );
  assert.deepEqual(
    context.watermarks.lines,
    [50, 80],
    'Unspecified lines watermark must keep default boundaries'
  );
}

// 4. Context.classForPercent classifies percentage values into low, medium, or high buckets based on configured watermark thresholds
{
  const context = createCoverageReportContext({
    watermarks: {
      statements: [60, 85]
    }
  });

  // Below low watermark ( < 60 ) -> 'low'
  assert.equal(context.classForPercent('statements', 0), 'low');
  assert.equal(context.classForPercent('statements', 59.9), 'low');
  assert.equal(evaluateCoverageClass(context, 'statements', 50), 'low');

  // Between low and high watermark ( >= 60 and < 85 ) -> 'medium'
  assert.equal(context.classForPercent('statements', 60), 'medium');
  assert.equal(context.classForPercent('statements', 75), 'medium');
  assert.equal(context.classForPercent('statements', 84.99), 'medium');
  assert.equal(evaluateCoverageClass(context, 'statements', 70), 'medium');

  // At or above high watermark ( >= 85 ) -> 'high'
  assert.equal(context.classForPercent('statements', 85), 'high');
  assert.equal(context.classForPercent('statements', 100), 'high');
  assert.equal(evaluateCoverageClass(context, 'statements', 95), 'high');
}

// 5. Context.classForPercent returns unknown for unrecognized coverage metric types
{
  const context = createCoverageReportContext();

  assert.equal(
    context.classForPercent('nonexistent_metric', 75),
    'unknown',
    'classForPercent must return "unknown" for unrecognized metric types'
  );
  assert.equal(
    evaluateCoverageClass(context, 'invalid_key', 100),
    'unknown',
    'Helper evaluateCoverageClass must return "unknown" for unrecognized metric types'
  );
}

// 6. Context.getSource retrieves file source code using custom sourceFinder function
{
  const sourceStore = {
    'lib/sample.js': 'export const answer = 42;'
  };

  const context = createCoverageReportContext({
    sourceFinder: (filePath) => {
      if (sourceStore[filePath]) {
        return sourceStore[filePath];
      }
      throw new Error(`Source not found: ${filePath}`);
    }
  });

  assert.equal(
    context.getSource('lib/sample.js'),
    'export const answer = 42;',
    'getSource must return content from sourceFinder'
  );

  assert.throws(
    () => context.getSource('missing/file.js'),
    /Source not found/,
    'getSource must propagate error from sourceFinder when file is absent'
  );
}

console.log('All contract assertions passed.');

原始种子者

匿名