CodeSampleX

샘플

yaml 2.9.0: Asynchronously traverse and modify YAML AST with visitAsync

검증된 샘플 — npm yaml 2.9.0: Asynchronously traverse and modify YAML AST with visitAsync. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:1252c8c3eb7dd04c41fbf774e291102f99ad969814cd1b8997c64f4665dc6309

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm wsl

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
Asynchronously traverse and modify YAML AST with visitAsync
패키지
심벌
  • visitAsync
생성일
2026-08-19T12:01:59Z

컨트랙트

  1. assert visitAsync asynchronously traverses YAML AST nodes including Document, Map, Seq, Pair, and Scalar
  2. assert visitAsync modifies Scalar node values and replaces nodes during async traversal
  3. assert visitAsync removes nodes and key-value pairs when visitor returns visitAsync.REMOVE
  4. assert visitAsync halts traversal immediately when visitor returns visitAsync.BREAK
  5. assert visitAsync skips child node inspection when visitor returns visitAsync.SKIP

파일

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • 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: Asynchronously traverse and modify YAML AST with visitAsync
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/yaml@2.9.0
Demonstrate these symbols/APIs:
  - visitAsync

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:584503da0c90f459f86c9923c29d6e386e004018b44de84f0f0273026e62757a","contract":["assert visitAsync asynchronously traverses YAML AST nodes including Document, Map, Seq, Pair, and Scalar","assert visitAsync modifies Scalar node values and replaces nodes during async traversal","assert visitAsync removes nodes and key-value pairs when visitor returns visitAsync.REMOVE","assert visitAsync halts traversal immediately when visitor returns visitAsync.BREAK","assert visitAsync skips child node inspection when visitor returns visitAsync.SKIP"],"goal":"Asynchronously traverse and modify YAML AST with visitAsync","kind":"HOW","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["visitAsync"]},"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,"virtualization":"wsl"},"license":"MIT-0","packages":["pkg:npm/yaml@2.9.0"],"schemaVersion":1,"symbols":["visitAsync"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { visitAsync, isScalar, isPair, isMap, isSeq, isDocument, Scalar } from 'yaml';

/**
 * Asynchronously updates all Scalar values matching the predicate.
 */
export async function transformScalarsAsync(doc, transformFn) {
  await visitAsync(doc, {
    async Scalar(key, node, path) {
      const updated = await transformFn(node.value, key, path);
      if (updated !== undefined) {
        node.value = updated;
      }
    }
  });
  return doc;
}

/**
 * Asynchronously removes pairs matching the filter condition.
 */
export async function filterPairsAsync(doc, shouldRemoveFn) {
  await visitAsync(doc, {
    async Pair(key, node, path) {
      const shouldRemove = await shouldRemoveFn(node.key?.value, node.value, path);
      if (shouldRemove) {
        return visitAsync.REMOVE;
      }
    }
  });
  return doc;
}

/**
 * Asynchronously collects visited node types.
 */
export async function collectNodeTypesAsync(doc) {
  const types = [];
  await visitAsync(doc, {
    async Map() { types.push('Map'); },
    async Seq() { types.push('Seq'); },
    async Pair() { types.push('Pair'); },
    async Scalar() { types.push('Scalar'); }
  });
  return types;
}

export { visitAsync, isScalar, isPair, isMap, isSeq, isDocument, Scalar };
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=="
    }
  }
}
package.json
{
  "name": "sample",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "yaml": "2.9.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Asynchronously traverse and modify YAML AST with visitAsync",
  "kind": "HOW",
  "packages": [
    "pkg:npm/yaml@2.9.0"
  ],
  "symbols": [
    "visitAsync"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { parseDocument, Scalar } from 'yaml';
import {
  visitAsync,
  transformScalarsAsync,
  filterPairsAsync,
  collectNodeTypesAsync
} from '../index.mjs';

// 1. assert visitAsync asynchronously traverses YAML AST nodes including Document, Map, Seq, Pair, and Scalar
{
  const yamlText = `
service: gateway
endpoints:
  - /health
  - /metrics
retries: 5
`;
  const doc = parseDocument(yamlText);
  const types = await collectNodeTypesAsync(doc);

  assert.ok(types.includes('Map'), 'Must visit Map nodes');
  assert.ok(types.includes('Seq'), 'Must visit Seq nodes');
  assert.ok(types.includes('Pair'), 'Must visit Pair nodes');
  assert.ok(types.includes('Scalar'), 'Must visit Scalar nodes');

  const visitedValues = [];
  await visitAsync(doc, {
    async Scalar(key, node) {
      visitedValues.push(node.value);
    }
  });

  assert.ok(visitedValues.includes('gateway'));
  assert.ok(visitedValues.includes('/health'));
  assert.ok(visitedValues.includes('/metrics'));
  assert.ok(visitedValues.includes(5));
}

// 2. assert visitAsync modifies Scalar node values and replaces nodes during async traversal
{
  const yamlText = `
user: alice
endpoint: /v1/api
`;
  const doc = parseDocument(yamlText);

  await transformScalarsAsync(doc, async (value) => {
    if (value === 'alice') {
      return Promise.resolve('bob');
    }
    return undefined;
  });

  // Replace a Scalar node with a new Scalar node
  await visitAsync(doc, {
    async Scalar(key, node) {
      if (node.value === '/v1/api') {
        return new Scalar('/v2/api');
      }
    }
  });

  const js = doc.toJS();
  assert.equal(js.user, 'bob');
  assert.equal(js.endpoint, '/v2/api');
}

// 3. assert visitAsync removes nodes and key-value pairs when visitor returns visitAsync.REMOVE
{
  const yamlText = `
environment: production
debugMode: true
tags:
  - legacy
  - stable
`;
  const doc = parseDocument(yamlText);

  await filterPairsAsync(doc, async (key) => {
    return Promise.resolve(key === 'debugMode');
  });

  await visitAsync(doc, {
    async Scalar(key, node) {
      if (node.value === 'legacy') {
        return visitAsync.REMOVE;
      }
    }
  });

  const js = doc.toJS();
  assert.equal(js.debugMode, undefined);
  assert.equal(js.environment, 'production');
  assert.deepEqual(js.tags, ['stable']);
}

// 4. assert visitAsync halts traversal immediately when visitor returns visitAsync.BREAK
{
  const yamlText = `
first: 10
second: 20
third: 30
fourth: 40
`;
  const doc = parseDocument(yamlText);
  const seenScalars = [];

  await visitAsync(doc, {
    async Scalar(key, node) {
      seenScalars.push(node.value);
      if (node.value === 20) {
        return visitAsync.BREAK;
      }
    }
  });

  assert.ok(seenScalars.includes('first'));
  assert.ok(seenScalars.includes(10));
  assert.ok(seenScalars.includes('second'));
  assert.ok(seenScalars.includes(20));
  assert.ok(!seenScalars.includes('third'), 'Should break before third');
  assert.ok(!seenScalars.includes(30), 'Should break before 30');
  assert.ok(!seenScalars.includes('fourth'), 'Should break before fourth');
  assert.ok(!seenScalars.includes(40), 'Should break before 40');
}

// 5. assert visitAsync skips child node inspection when visitor returns visitAsync.SKIP
{
  const yamlText = `
metadata:
  nestedField1: skipMe
  nestedField2: skipMeToo
keepField: processMe
`;
  const doc = parseDocument(yamlText);
  const processed = [];

  await visitAsync(doc, {
    async Map(key, node, path) {
      if (path.length > 0 && path[path.length - 1].key?.value === 'metadata') {
        return visitAsync.SKIP;
      }
    },
    async Scalar(key, node) {
      processed.push(node.value);
    }
  });

  assert.ok(processed.includes('metadata'));
  assert.ok(!processed.includes('nestedField1'), 'nestedField1 must be skipped');
  assert.ok(!processed.includes('skipMe'), 'skipMe must be skipped');
  assert.ok(!processed.includes('nestedField2'), 'nestedField2 must be skipped');
  assert.ok(!processed.includes('skipMeToo'), 'skipMeToo must be skipped');
  assert.ok(processed.includes('keepField'));
  assert.ok(processed.includes('processMe'));
}

console.log('PASS: All visitAsync contract assertions passed successfully');

오리진 시더

익명