CodeSampleX

Exemplo

postcss 8.5.26: Result#warn

Amostra verificada para npm postcss 8.5.26: Result#warn. O contrato rodou em node 22 · linux alpine/x64 · docker e passou: Result#warn creates a Warning…

sha256:c7b7202cfdc559c9a83b2366d3489e2ab400fc512daef17d8c40cebffd91351c

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

Caso

HOW
Objetivo
verify Result#warn in pkg:npm/postcss@8.5.26
Pacotes
Símbolos
  • Result#warn
Ambiente
node 22.23.2
Criado
2026-08-27T02:00:36Z

Contrato

  1. Result#warn creates a Warning object with type 'warning' and pushes it to result.messages
  2. Result#warn returns the created Warning instance
  3. Result#warn automatically assigns the current plugin name when called during plugin execution
  4. Result#warn preserves explicitly provided plugin name and custom options
  5. Result#warn calculates source line and column numbers when an AST node is passed in options
  6. Result#warn calculates word range when node and word options are passed
  7. Result#warnings returns only warning messages filtered from result.messages
  8. Warning#toString formats warning with plugin name and node position when available

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 Result#warn in pkg:npm/postcss@8.5.26
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/postcss@8.5.26
Demonstrate these symbols/APIs:
  - Result#warn
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:87fbc26e74a6085be66691caa0b716b9d2393d0e58ae7989c1be8549467db2aa","constraints":{"executionContext":"node"},"contract":["Result#warn creates a Warning object with type 'warning' and pushes it to result.messages","Result#warn returns the created Warning instance","Result#warn automatically assigns the current plugin name when called during plugin execution","Result#warn preserves explicitly provided plugin name and custom options","Result#warn calculates source line and column numbers when an AST node is passed in options","Result#warn calculates word range when node and word options are passed","Result#warnings returns only warning messages filtered from result.messages","Warning#toString formats warning with plugin name and node position when available"],"goal":"verify Result#warn in pkg:npm/postcss@8.5.26","kind":"HOW","packages":["pkg:npm/postcss@8.5.26"],"schemaVersion":1,"symbols":["Result#warn"]},"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/postcss@8.5.26"],"schemaVersion":1,"subject":"pkg:npm/postcss@8.5.26","symbols":["Result#warn"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-postcss-result-warn",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-postcss-result-warn",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "postcss": "8.5.26"
      }
    },
    "node_modules/nanoid": {
      "version": "3.3.18",
      "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
      "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "bin": {
        "nanoid": "bin/nanoid.cjs"
      },
      "engines": {
        "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
      }
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    },
    "node_modules/postcss": {
      "version": "8.5.26",
      "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
      "integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
      "funding": [
        {
          "type": "opencollective",
          "url": "https://opencollective.com/postcss/"
        },
        {
          "type": "tidelift",
          "url": "https://tidelift.com/funding/github/npm/postcss"
        },
        {
          "type": "github",
          "url": "https://github.com/sponsors/ai"
        }
      ],
      "license": "MIT",
      "dependencies": {
        "nanoid": "^3.3.17",
        "picocolors": "^1.1.1",
        "source-map-js": "^1.2.1"
      },
      "engines": {
        "node": "^10 || ^12 || >=14"
      }
    },
    "node_modules/source-map-js": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
      "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-postcss-result-warn",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for postcss Result#warn",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "postcss": "8.5.26"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify Result#warn in pkg:npm/postcss@8.5.26",
  "kind": "HOW",
  "packages": [
    "pkg:npm/postcss@8.5.26"
  ],
  "symbols": [
    "Result#warn"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const postcss = require('postcss');

/**
 * Creates a PostCSS plugin that emits a warning during transformation.
 * @param {string} text
 * @param {object} [opts]
 * @returns {object} PostCSS plugin
 */
function createWarningPlugin(text, opts = {}) {
  return {
    postcssPlugin: opts.plugin || 'postcss-warn-plugin',
    Once(root, { result }) {
      result.warn(text, { ...opts, node: opts.node || root.first });
    }
  };
}

/**
 * Processes CSS and collects warnings.
 * @param {string} css
 * @param {Array} plugins
 * @param {object} [processOpts]
 * @returns {Promise<{ css: string, warnings: Array, result: object }>}
 */
async function processWithWarnings(css, plugins = [], processOpts = { from: undefined }) {
  const result = await postcss(plugins).process(css, processOpts);
  return {
    css: result.css,
    warnings: result.warnings(),
    result
  };
}

/**
 * Directly invokes warn on a Result instance.
 * @param {object} result
 * @param {string} text
 * @param {object} [opts]
 * @returns {object} Warning object
 */
function addDirectWarning(result, text, opts = {}) {
  return result.warn(text, opts);
}

module.exports = {
  createWarningPlugin,
  processWithWarnings,
  addDirectWarning
};
test/contract.js
const assert = require('node:assert');
const postcss = require('postcss');
const {
  createWarningPlugin,
  processWithWarnings,
  addDirectWarning
} = require('../src/index.js');

async function runContractTests() {
  // 1. Direct Result#warn creates and returns a Warning object pushed to messages
  const root = postcss.parse('a { color: red; }');
  const result = new postcss.Result(postcss(), root, {});
  const warning = result.warn('Direct warning message');

  assert.strictEqual(warning.type, 'warning', 'Warning object should have type "warning"');
  assert.strictEqual(warning.text, 'Direct warning message', 'Warning object should have the provided text');
  assert.strictEqual(result.messages.length, 1, 'Result.messages should contain the new warning');
  assert.strictEqual(result.messages[0], warning, 'Result.messages[0] should be the returned warning instance');
  assert.strictEqual(result.warnings().length, 1, 'Result.warnings() should contain 1 warning');
  assert.strictEqual(result.warnings()[0], warning, 'Result.warnings()[0] should match the warning instance');

  // 2. Automatic plugin name inheritance during plugin execution
  const plugin = {
    postcssPlugin: 'linter-plugin',
    Once(ast, { result: res }) {
      res.warn('Plugin generated warning', { node: ast.first });
    }
  };

  const processed = await postcss([plugin]).process('b { display: flex; }', { from: undefined });
  const pluginWarnings = processed.warnings();
  assert.strictEqual(pluginWarnings.length, 1, 'Should have captured 1 warning from plugin');
  assert.strictEqual(pluginWarnings[0].plugin, 'linter-plugin', 'Warning should inherit plugin name');
  assert.strictEqual(pluginWarnings[0].text, 'Plugin generated warning');

  // 3. Explicit plugin option override
  const overridePlugin = {
    postcssPlugin: 'default-plugin-name',
    Once(ast, { result: res }) {
      res.warn('Custom plugin warning', { plugin: 'explicit-plugin-override' });
    }
  };

  const overrideProcessed = await postcss([overridePlugin]).process('.box { margin: 0; }', { from: undefined });
  assert.strictEqual(overrideProcessed.warnings()[0].plugin, 'explicit-plugin-override', 'Explicit plugin option must override default');

  // 4. Line and column position extraction when node is passed
  const multiLineCss = 'header {\n  font-weight: bold;\n}';
  const parsedAst = postcss.parse(multiLineCss, { from: 'styles.css' });
  const ruleNode = parsedAst.first;
  const declNode = ruleNode.first;
  const locResult = new postcss.Result(postcss(), parsedAst, { from: 'styles.css' });

  const nodeWarning = locResult.warn('Declaration warning', { node: declNode });
  assert.strictEqual(nodeWarning.line, 2, 'Warning line should match declaration start line');
  assert.strictEqual(nodeWarning.column, 3, 'Warning column should match declaration start column');

  // 5. Word range calculation
  const wordWarning = locResult.warn('Property warning', { node: declNode, word: 'font-weight' });
  assert.strictEqual(wordWarning.line, 2);
  assert.strictEqual(wordWarning.column, 3);
  assert.strictEqual(wordWarning.word, 'font-weight');

  // 6. Result#warnings filters only warning messages
  locResult.messages.push({ type: 'dependency', file: 'other.css', parent: 'styles.css' });
  locResult.messages.push({ type: 'dir-dependency', dir: 'images' });
  assert.strictEqual(locResult.messages.length, 4, 'locResult should have 4 total messages');
  assert.strictEqual(locResult.warnings().length, 2, 'locResult.warnings() should only return the 2 warnings');

  // 7. Warning#toString formatting
  const plainWarn = new postcss.Result(postcss(), root, {}).warn('Standalone warning message');
  assert.strictEqual(plainWarn.toString(), 'Standalone warning message', 'Plain warning toString should equal its text');

  const namedPluginWarn = new postcss.Result(postcss(), root, {}).warn('Named message', { plugin: 'custom-tool' });
  assert.strictEqual(namedPluginWarn.toString(), 'custom-tool: Named message', 'Plugin warning toString should prefix plugin name');

  // 8. Helper module verification
  const helperPlugin = createWarningPlugin('Helper emitted warning', { plugin: 'helper-test-plugin' });
  const helperRes = await processWithWarnings('main { padding: 10px; }', [helperPlugin]);
  assert.strictEqual(helperRes.warnings.length, 1);
  assert.strictEqual(helperRes.warnings[0].text, 'Helper emitted warning');
  assert.strictEqual(helperRes.warnings[0].plugin, 'helper-test-plugin');

  const directWarnRes = new postcss.Result(postcss(), root, {});
  const directWarn = addDirectWarning(directWarnRes, 'Direct helper warning');
  assert.strictEqual(directWarn.text, 'Direct helper warning');
  assert.strictEqual(directWarnRes.warnings().length, 1);

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

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

Seeder de origem

anônimo