CodeSampleX

Пример

chalk 5.4.1: Suppress text output when colors are disabled via chalk.visible while standard and chained color styles pass text through unmodified

Проверенный пример — npm chalk 5.4.1: Suppress text output when colors are disabled via chalk.visible while standard and chained color styles pass text…

sha256:166812946ca1627b9db2bd37c749870d435c1a6b0fffa22be788bc974d744f86

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Кейс

HOW
Цель
Suppress text output when colors are disabled via chalk.visible while standard and chained color styles pass text through unmodified
Пакеты
Символы
  • Chalk.prototype.visible
  • Chalk.prototype.level
  • Chalk
Окружение
node
Создан
2026-08-16T16:10:54Z

Контракт

  1. chalk.visible and chained modifiers return an empty string when level is 0 rather than passing through unstyled text
  2. chalk.red and other standard styles return the original unstyled text when level is 0
  3. chalk.visible passes through unstyled text when level is 1 or higher
  4. chained styles like chalk.red.visible and chalk.visible.red apply full ANSI styling when level is 1 or higher regardless of chain order
  5. chalk.visible with multiple arguments joins them with spaces when level is 1 or higher and returns an empty string when level is 0
  6. nested chalk.visible calls inside outer styles omit the nested content at level 0 and style the entire composite string at level 1
  7. dynamically mutating level on a Chalk instance from 1 to 0 immediately switches chalk.visible from passthrough to empty string suppression

Файлы

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • src/index.mjs
  • test/contract.mjs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Chalk visible Modifier and Color Level Interaction Notes

## Search Results
`search_known_solution` returned existing sample `sha256:525f14e9ff41964b2cf8700329f042389c75335c2b13dc4d12796c1cbb8e0f28` ("Configure runtime color formatting and disable ANSI codes in Chalk v5 via chalk.level instead of deprecated chalk.enabled or missing chalk.supportsColor").

## What a Model Would Have Written Instead
A model assumes that setting `level: 0` disables ANSI escape sequences while uniformly preserving all input text across all chalk styling calls (such as `chalk.red('text')` and `chalk.visible('text')`).

## How the Wrong Version Fails
Silently with a green build, as `chalk.visible` and chained modifiers like `chalk.red.visible` return empty strings instead of the original text whenever `level` is `0`, causing log messages or optional UI elements to disappear without throwing any runtime exceptions.
csx.json
{"case":{"believed":"Setting chalk.level to 0 disables ANSI escape sequences while preserving all input text across all chalk styling calls, so chalk.visible and chained visible styles return the original string rather than an empty string.","caseId":"case:sha256:f25dc0aeee0df45ead6889339b01c350d43cd8f655e59eece14759399af6dc06","contract":["chalk.visible and chained modifiers return an empty string when level is 0 rather than passing through unstyled text","chalk.red and other standard styles return the original unstyled text when level is 0","chalk.visible passes through unstyled text when level is 1 or higher","chained styles like chalk.red.visible and chalk.visible.red apply full ANSI styling when level is 1 or higher regardless of chain order","chalk.visible with multiple arguments joins them with spaces when level is 1 or higher and returns an empty string when level is 0","nested chalk.visible calls inside outer styles omit the nested content at level 0 and style the entire composite string at level 1","dynamically mutating level on a Chalk instance from 1 to 0 immediately switches chalk.visible from passthrough to empty string suppression"],"goal":"Suppress text output when colors are disabled via chalk.visible while standard and chained color styles pass text through unmodified","kind":"HOW","packages":["pkg:npm/chalk@5.4.1"],"schemaVersion":1,"symbols":["Chalk.prototype.visible","Chalk.prototype.level","Chalk"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/chalk@5.4.1"],"schemaVersion":1,"symbols":["Chalk.prototype.visible","Chalk.prototype.level","Chalk"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-chalk-visible-level-interaction",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-chalk-visible-level-interaction",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "chalk": "5.4.1"
      }
    },
    "node_modules/chalk": {
      "version": "5.4.1",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.4.1.tgz",
      "integrity": "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w==",
      "license": "MIT",
      "engines": {
        "node": "^12.17.0 || ^14.13 || >=16.0.0"
      },
      "funding": {
        "url": "https://github.com/chalk/chalk?sponsor=1"
      }
    }
  }
}
package.json
{
  "name": "sample-chalk-visible-level-interaction",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "chalk": "5.4.1"
  }
}
src/index.mjs
import { Chalk } from 'chalk';

export function createChalkInstance(level) {
  return new Chalk({ level });
}

export function formatVisible(chalkInstance, text) {
  return chalkInstance.visible(text);
}

export function formatStandard(chalkInstance, text) {
  return chalkInstance.red(text);
}

export function formatChainedVisible(chalkInstance, text) {
  return {
    redVisible: chalkInstance.red.visible(text),
    visibleRed: chalkInstance.visible.red(text),
    visibleBoldBgBlue: chalkInstance.visible.bold.bgBlue(text),
  };
}

export function formatMultiArgVisible(chalkInstance, ...args) {
  return chalkInstance.visible(...args);
}

export function formatNestedWithVisible(chalkInstance, prefix, optionalBadge, suffix) {
  return chalkInstance.blue(`${prefix}${chalkInstance.visible(optionalBadge)}${suffix}`);
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  createChalkInstance,
  formatVisible,
  formatStandard,
  formatChainedVisible,
  formatMultiArgVisible,
  formatNestedWithVisible,
} from '../src/index.mjs';

// 1. chalk.visible and chained modifiers return an empty string when level is 0 rather than passing through unstyled text
const disabledChalk = createChalkInstance(0);
assert.equal(
  formatVisible(disabledChalk, 'Optional badge text'),
  '',
  'chalk.visible must return an empty string when color level is 0'
);

const chainedDisabled = formatChainedVisible(disabledChalk, 'Warning payload');
assert.equal(
  chainedDisabled.redVisible,
  '',
  'chalk.red.visible must return an empty string when level is 0'
);
assert.equal(
  chainedDisabled.visibleRed,
  '',
  'chalk.visible.red must return an empty string when level is 0'
);
assert.equal(
  chainedDisabled.visibleBoldBgBlue,
  '',
  'chalk.visible.bold.bgBlue must return an empty string when level is 0'
);

// 2. chalk.red and other standard styles return the original unstyled text when level is 0
assert.equal(
  formatStandard(disabledChalk, 'Standard message'),
  'Standard message',
  'Standard styles like chalk.red pass unstyled text through when level is 0'
);

// 3. chalk.visible passes through unstyled text when level is 1 or higher
const basicChalk = createChalkInstance(1);
assert.equal(
  formatVisible(basicChalk, 'Visible message'),
  'Visible message',
  'chalk.visible passes text through without ANSI codes when unstyled at level >= 1'
);

// 4. chained styles like chalk.red.visible and chalk.visible.red apply full ANSI styling when level is 1 or higher regardless of chain order
const chainedBasic = formatChainedVisible(basicChalk, 'Active alert');
assert.equal(
  chainedBasic.redVisible,
  '\u001b[31mActive alert\u001b[39m',
  'chalk.red.visible applies red ANSI escape codes at level 1'
);
assert.equal(
  chainedBasic.visibleRed,
  '\u001b[31mActive alert\u001b[39m',
  'chalk.visible.red applies red ANSI escape codes identically to chalk.red.visible'
);
assert.equal(
  chainedBasic.visibleBoldBgBlue,
  '\u001b[1m\u001b[44mActive alert\u001b[49m\u001b[22m',
  'chalk.visible.bold.bgBlue applies bold and bgBlue ANSI escape codes at level 1'
);

// 5. chalk.visible with multiple arguments joins them with spaces when level is 1 or higher and returns an empty string when level is 0
assert.equal(
  formatMultiArgVisible(disabledChalk, 'tag1', 'tag2', 123),
  '',
  'chalk.visible with multiple arguments returns an empty string when level is 0'
);
assert.equal(
  formatMultiArgVisible(basicChalk, 'tag1', 'tag2', 123),
  'tag1 tag2 123',
  'chalk.visible with multiple arguments joins with spaces when level >= 1'
);

// 6. nested chalk.visible calls inside outer styles omit the nested content at level 0 and style the entire composite string at level 1
const nestedDisabled = formatNestedWithVisible(disabledChalk, 'Status: ', '[ONLINE]', ' - OK');
assert.equal(
  nestedDisabled,
  'Status:  - OK',
  'Outer style omits nested chalk.visible content at level 0'
);

const nestedBasic = formatNestedWithVisible(basicChalk, 'Status: ', '[ONLINE]', ' - OK');
assert.equal(
  nestedBasic,
  '\u001b[34mStatus: [ONLINE] - OK\u001b[39m',
  'Outer style formats composite string containing chalk.visible content at level 1'
);

// 7. dynamically mutating level on a Chalk instance from 1 to 0 immediately switches chalk.visible from passthrough to empty string suppression
const dynamicChalk = createChalkInstance(1);
assert.equal(formatVisible(dynamicChalk, 'dynamic text'), 'dynamic text');
assert.equal(formatStandard(dynamicChalk, 'dynamic red'), '\u001b[31mdynamic red\u001b[39m');

dynamicChalk.level = 0;
assert.equal(formatVisible(dynamicChalk, 'dynamic text'), '');
assert.equal(formatStandard(dynamicChalk, 'dynamic red'), 'dynamic red');

console.log('CONTRACT PASS: chalk.visible and level interaction behavior verified');

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

csx-seed