CodeSampleX

Exemplo

yaml 2.9.0: Modify YAML AST and preserve comments using Document and parseDocument

Amostra verificada para npm yaml 2.9.0: Modify YAML AST and preserve comments using Document and parseDocument. O contrato rodou em node 22 · linux…

sha256:c117b9662afe8a7e991123cb048ccf2626f6768dbacc9931314e9f75f5266123

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 windows 11 x64 node javascript npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-19

Caso

HOW
Objetivo
Modify YAML AST and preserve comments using Document and parseDocument
Pacotes
Símbolos
  • Document
  • parseDocument
Ambiente
node
Criado
2026-08-18T19:29:04Z

Contrato

  1. parseDocument parses YAML string into a Document AST preserving comments
  2. Document get and set modify node values in the AST
  3. Document toString serializes the modified AST while preserving existing comments
  4. Document constructor creates a new YAML Document AST from JavaScript values
  5. Document toJSON converts the document AST back into a JavaScript object

Arquivos

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • 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: Modify YAML AST and preserve comments using Document and parseDocument
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/yaml@2.9.0
Demonstrate these symbols/APIs:
  - Document
  - parseDocument
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@11.8.0
  - runtime: node@24.13.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:531162b9e11d6f52620730b6b9a60d3305224c549c609b1402be08ae9ac9feab","constraints":{"executionContext":"node"},"contract":["parseDocument parses YAML string into a Document AST preserving comments","Document get and set modify node values in the AST","Document toString serializes the modified AST while preserving existing comments","Document constructor creates a new YAML Document AST from JavaScript values","Document toJSON converts the document AST back into a JavaScript object"],"goal":"Modify YAML AST and preserve comments using Document and parseDocument","kind":"HOW","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["Document","parseDocument"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"javascript","moduleSystem":"cjs","os":"windows","osVersionBucket":"11","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["Document","parseDocument"],"verifierAdapter":"node-typescript@1"}
index.js
const { Document, parseDocument } = require('yaml');

function parseYamlDocument(yamlText) {
  return parseDocument(yamlText);
}

function createYamlDocument(value) {
  return new Document(value);
}

function updateDocumentField(doc, key, value) {
  doc.set(key, value);
  return doc;
}

function documentToYamlString(doc) {
  return doc.toString();
}

module.exports = {
  Document,
  parseDocument,
  parseYamlDocument,
  createYamlDocument,
  updateDocumentField,
  documentToYamlString
};
package-lock.json
{
  "name": "sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample",
      "version": "1.0.0",
      "dependencies": {
        "yaml": "2.9.0"
      }
    },
    "node_modules/yaml": {
      "version": "2.9.0",
      "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
      "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
      "license": "ISC",
      "bin": {
        "yaml": "bin.mjs"
      },
      "engines": {
        "node": ">= 14.6"
      },
      "funding": {
        "url": "https://github.com/sponsors/eemeli"
      }
    }
  }
}
package.json
{
  "name": "sample",
  "version": "1.0.0",
  "private": true,
  "main": "index.js",
  "dependencies": {
    "yaml": "2.9.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Modify YAML AST and preserve comments using Document and parseDocument",
  "kind": "HOW",
  "packages": [
    "pkg:npm/yaml@2.9.0"
  ],
  "symbols": [
    "Document",
    "parseDocument"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@11.8.0",
    "runtime": "node@24.13.1"
  }
}
test/contract.js
const assert = require('assert');
const { Document, parseDocument } = require('../index.js');

// Assertion 1: parseDocument parses YAML string into a Document AST preserving comments
const yamlWithComments = '# Top header comment\nname: sample-app\n# Port configuration\nport: 3000\n';
const doc1 = parseDocument(yamlWithComments);
assert.ok(doc1 instanceof Document);
assert.strictEqual(doc1.get('name'), 'sample-app');
assert.strictEqual(doc1.get('port'), 3000);

// Assertion 2: Document get and set modify node values in the AST
const doc2 = parseDocument('key: initial\ncount: 1\n');
doc2.set('key', 'modified');
doc2.set('count', 2);
assert.strictEqual(doc2.get('key'), 'modified');
assert.strictEqual(doc2.get('count'), 2);

// Assertion 3: Document toString serializes the modified AST while preserving existing comments
const yamlInput = '# App settings\napp: demo # inline comment\nversion: 1\n';
const doc3 = parseDocument(yamlInput);
doc3.set('version', 2);
const serialized = doc3.toString();
assert.ok(serialized.includes('# App settings'));
assert.ok(serialized.includes('version: 2'));
assert.ok(serialized.includes('app: demo'));

// Assertion 4: Document constructor creates a new YAML Document AST from JavaScript values
const newDoc = new Document({ service: 'api', replicas: 3 });
newDoc.commentBefore = ' Service Configuration';
assert.strictEqual(newDoc.get('service'), 'api');
assert.strictEqual(newDoc.get('replicas'), 3);
const outputYaml = newDoc.toString();
assert.ok(outputYaml.includes('# Service Configuration'));
assert.ok(outputYaml.includes('service: api'));
assert.ok(outputYaml.includes('replicas: 3'));

// Assertion 5: Document toJSON converts the document AST back into a JavaScript object
const yamlData = 'title: Report\nitems:\n  - task1\n  - task2\n';
const doc5 = parseDocument(yamlData);
doc5.set('title', 'Updated Report');
const jsonObject = doc5.toJSON();
assert.deepStrictEqual(jsonObject, {
  title: 'Updated Report',
  items: ['task1', 'task2']
});

console.log('PASS: all contract assertions passed for Document and parseDocument');

Seeder de origem

anônimo