CodeSampleX

샘플

source-map 0.6.1: SourceNode

검증된 샘플 — npm source-map 0.6.1: SourceNode. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: SourceNode instantiates code chunks with line, column…

sha256:37b956378f645a8faaa9bf7aa566e0037de3975ee51f3fdfd78000829e293b84

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
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-23
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-07

케이스

HOW
목표
verify source-map.SourceNode in pkg:npm/source-map@0.6.1
패키지
심벌
  • source-map.SourceNode
생성일
2026-08-23T13:42:52Z

컨트랙트

  1. SourceNode instantiates code chunks with line, column, source file, and optional identifier name
  2. SourceNode.add and SourceNode.prepend append and prepend string chunks or child SourceNodes
  3. SourceNode.walk traverses chunk nodes yielding code snippets and mapped source locations
  4. SourceNode.join combines chunks with a separator and SourceNode.replaceRight updates matching text
  5. SourceNode.toStringWithSourceMap generates merged code and a SourceMapGenerator with line and column mappings
  6. SourceNode.fromStringWithSourceMap reconstructs SourceNodes from generated code and a SourceMapConsumer
  7. SourceNode.setSourceContent and walkSourceContents manage original file source content

파일

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

소스 아티팩트 내려받기 (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: verify source-map.SourceNode in pkg:npm/source-map@0.6.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/source-map@0.6.1
Demonstrate these symbols/APIs:
  - source-map.SourceNode

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:0ab2eb95142514f98b253f8b8f5980840259bc9432263fd626a8817ca3890dd8","contract":["SourceNode instantiates code chunks with line, column, source file, and optional identifier name","SourceNode.add and SourceNode.prepend append and prepend string chunks or child SourceNodes","SourceNode.walk traverses chunk nodes yielding code snippets and mapped source locations","SourceNode.join combines chunks with a separator and SourceNode.replaceRight updates matching text","SourceNode.toStringWithSourceMap generates merged code and a SourceMapGenerator with line and column mappings","SourceNode.fromStringWithSourceMap reconstructs SourceNodes from generated code and a SourceMapConsumer","SourceNode.setSourceContent and walkSourceContents manage original file source content"],"goal":"verify source-map.SourceNode in pkg:npm/source-map@0.6.1","kind":"HOW","packages":["pkg:npm/source-map@0.6.1"],"schemaVersion":1,"symbols":["source-map.SourceNode"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/source-map@0.6.1"],"schemaVersion":1,"subject":"pkg:npm/source-map@0.6.1","symbols":["source-map.SourceNode"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const { SourceNode, SourceMapConsumer, SourceMapGenerator } = require('source-map');

/**
 * Creates a new SourceNode instance.
 * @param {number|null} line - 1-based line number in source file
 * @param {number|null} column - 0-based column number in source file
 * @param {string|null} source - Source filename
 * @param {string|SourceNode|Array<string|SourceNode>} [chunks] - Optional initial chunks
 * @param {string} [name] - Optional identifier name
 * @returns {SourceNode}
 */
function createSourceNode(line, column, source, chunks, name) {
  return new SourceNode(line, column, source, chunks, name);
}

/**
 * Combines multiple chunks or nodes with an optional separator.
 * @param {Array<string|SourceNode>} nodes - Nodes or string chunks to combine
 * @param {string} [separator] - Delimiter to join chunks with
 * @returns {SourceNode}
 */
function buildJoinedNode(nodes, separator) {
  const root = new SourceNode(null, null, null, nodes);
  if (separator !== undefined) {
    return root.join(separator);
  }
  return root;
}

/**
 * Generates output code along with its SourceMapGenerator.
 * @param {SourceNode} node - The root SourceNode
 * @param {object} [options] - Options like { file: string }
 * @returns {{ code: string, map: SourceMapGenerator }}
 */
function generateCodeAndMap(node, options) {
  return node.toStringWithSourceMap(options);
}

/**
 * Reconstructs a SourceNode tree from generated code and a SourceMapConsumer.
 * @param {string} code - Generated code string
 * @param {SourceMapConsumer} consumer - The source map consumer
 * @param {string} [relativePath] - Optional relative path
 * @returns {SourceNode}
 */
function parseSourceNodeFromMap(code, consumer, relativePath) {
  return SourceNode.fromStringWithSourceMap(code, consumer, relativePath);
}

module.exports = {
  SourceNode,
  SourceMapConsumer,
  SourceMapGenerator,
  createSourceNode,
  buildJoinedNode,
  generateCodeAndMap,
  parseSourceNodeFromMap
};
package-lock.json
{
  "name": "sample-source-map-sourcenode",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-source-map-sourcenode",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "source-map": "0.6.1"
      }
    },
    "node_modules/source-map": {
      "version": "0.6.1",
      "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
      "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
      "license": "BSD-3-Clause",
      "engines": {
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-source-map-sourcenode",
  "version": "1.0.0",
  "private": true,
  "description": "verify source-map.SourceNode in pkg:npm/source-map@0.6.1",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "source-map": "0.6.1"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify source-map.SourceNode in pkg:npm/source-map@0.6.1",
  "kind": "HOW",
  "packages": [
    "pkg:npm/source-map@0.6.1"
  ],
  "symbols": [
    "source-map.SourceNode"
  ]
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  SourceNode,
  SourceMapConsumer,
  createSourceNode,
  buildJoinedNode,
  generateCodeAndMap,
  parseSourceNodeFromMap
} = require('../index.js');

function testInstantiationAndAddPrepend() {
  const node = createSourceNode(1, 0, 'source-a.js', 'function compute(');
  node.add('x, y) {\n');
  node.prepend('/* generated header */\n');

  const result = node.toString();
  assert.strictEqual(
    result,
    '/* generated header */\nfunction compute(x, y) {\n',
    'SourceNode must correctly prepend and append chunks'
  );
}

function testWalk() {
  const node = createSourceNode(10, 4, 'helper.js', 'return x * y;', 'computeMul');
  const visited = [];

  node.walk((chunk, loc) => {
    visited.push({ chunk, loc });
  });

  assert.strictEqual(visited.length, 1, 'SourceNode.walk should visit one chunk');
  assert.strictEqual(visited[0].chunk, 'return x * y;');
  assert.strictEqual(visited[0].loc.line, 10);
  assert.strictEqual(visited[0].loc.column, 4);
  assert.strictEqual(visited[0].loc.source, 'helper.js');
  assert.strictEqual(visited[0].loc.name, 'computeMul');
}

function testJoinAndReplaceRight() {
  const nodeA = createSourceNode(1, 0, 'a.js', 'alpha');
  const nodeB = createSourceNode(2, 0, 'b.js', 'beta');
  const nodeC = createSourceNode(3, 0, 'c.js', 'gamma_old');

  const joined = buildJoinedNode([nodeA, nodeB, nodeC], ' + ');
  assert.strictEqual(joined.toString(), 'alpha + beta + gamma_old');

  joined.replaceRight(/gamma_old/, 'gamma_new');
  assert.strictEqual(
    joined.toString(),
    'alpha + beta + gamma_new',
    'SourceNode.replaceRight must update the rightmost matching chunk'
  );
}

function testToStringWithSourceMapAndConsumer() {
  const root = new SourceNode(null, null, null, [
    createSourceNode(1, 0, 'math.js', 'const factor = 2;\n'),
    createSourceNode(2, 0, 'math.js', 'const total = factor * 5;\n', 'totalCalc'),
    createSourceNode(3, 0, 'math.js', 'console.log(total);\n')
  ]);

  const { code, map } = generateCodeAndMap(root, { file: 'output.js' });
  const expectedCode = 'const factor = 2;\nconst total = factor * 5;\nconsole.log(total);\n';

  assert.strictEqual(code, expectedCode, 'Generated code must match combined chunks');

  const rawMap = map.toJSON();
  assert.strictEqual(rawMap.file, 'output.js');
  assert.deepStrictEqual(rawMap.sources, ['math.js']);

  const consumer = new SourceMapConsumer(rawMap);

  const pos1 = consumer.originalPositionFor({ line: 1, column: 0 });
  assert.strictEqual(pos1.source, 'math.js');
  assert.strictEqual(pos1.line, 1);
  assert.strictEqual(pos1.column, 0);

  const pos2 = consumer.originalPositionFor({ line: 2, column: 0 });
  assert.strictEqual(pos2.source, 'math.js');
  assert.strictEqual(pos2.line, 2);
  assert.strictEqual(pos2.column, 0);
  assert.strictEqual(pos2.name, 'totalCalc');

  // Test static fromStringWithSourceMap reconstruction
  const reconstructed = parseSourceNodeFromMap(code, consumer);
  assert.strictEqual(
    reconstructed.toString(),
    code,
    'SourceNode.fromStringWithSourceMap must recreate equivalent output'
  );
}

function testSourceContentManagement() {
  const node = createSourceNode(1, 0, 'module.js', 'const value = 42;\n');
  const sourceCode = '// module source file\nconst value = 42;\n';
  node.setSourceContent('module.js', sourceCode);

  let retrievedContent = null;
  node.walkSourceContents((source, content) => {
    if (source === 'module.js') {
      retrievedContent = content;
    }
  });

  assert.strictEqual(retrievedContent, sourceCode, 'Source content must be retrieved correctly');

  const { map } = generateCodeAndMap(node);
  const rawMap = map.toJSON();
  assert.strictEqual(
    rawMap.sourcesContent[0],
    sourceCode,
    'Source map must include embedded sourcesContent'
  );
}

function run() {
  testInstantiationAndAddPrepend();
  testWalk();
  testJoinAndReplaceRight();
  testToStringWithSourceMapAndConsumer();
  testSourceContentManagement();
  console.log('Contract tests passed successfully.');
  process.exit(0);
}

run();

오리진 시더

익명