CodeSampleX

Пример

@jridgewell/trace-mapping 0.3.31: Trace original and generated positions using TraceMap and originalPositionFor

Проверенный пример — npm @jridgewell/trace-mapping 0.3.31: Trace original and generated positions using TraceMap and originalPositionFor. Контракт выполнен…

sha256:9f5113845aad7fcb93550da642cb001dff2204128b5703621807d7d98755e4dd

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

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

Окружение Контракт Этапы Запуск
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-24

Кейс

HOW
Цель
Trace original and generated positions using TraceMap and originalPositionFor
Пакеты
Символы
  • TraceMap
  • originalPositionFor
  • generatedPositionFor
  • sourceContentFor
Окружение
node 22.23.2
Создан
2026-08-24T20:21:57Z

Контракт

  1. TraceMap parses a standard v3 source map and provides access to metadata fields
  2. originalPositionFor maps generated 1-based line and 0-based column to original source position and identifier name
  3. generatedPositionFor maps original source position back to generated 1-based line and 0-based column
  4. allGeneratedPositionsFor returns all generated locations corresponding to a source position
  5. sourceContentFor retrieves the embedded source content for a source file
  6. decodedMap and encodedMap convert TraceMap back to valid decoded and encoded source map objects
  7. eachMapping iterates over all mappings in generated order

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.js
  • 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: Trace original and generated positions using TraceMap and originalPositionFor
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40jridgewell/trace-mapping@0.3.31
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:5340003b0c2aaa3ffa3a399c615e887150ea814184af00187f22379b5c4cddbe","constraints":{"executionContext":"node"},"contract":["TraceMap parses a standard v3 source map and provides access to metadata fields","originalPositionFor maps generated 1-based line and 0-based column to original source position and identifier name","generatedPositionFor maps original source position back to generated 1-based line and 0-based column","allGeneratedPositionsFor returns all generated locations corresponding to a source position","sourceContentFor retrieves the embedded source content for a source file","decodedMap and encodedMap convert TraceMap back to valid decoded and encoded source map objects","eachMapping iterates over all mappings in generated order"],"goal":"Trace original and generated positions using TraceMap and originalPositionFor","kind":"HOW","packages":["pkg:npm/%40jridgewell/trace-mapping@0.3.31"],"schemaVersion":1,"symbols":["TraceMap","originalPositionFor","generatedPositionFor","sourceContentFor"]},"contractCommand":["node","test/contract.mjs"],"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/%40jridgewell/trace-mapping@0.3.31"],"schemaVersion":1,"subject":"pkg:npm/%40jridgewell/trace-mapping@0.3.31","symbols":["TraceMap","originalPositionFor","generatedPositionFor","sourceContentFor"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-trace-mapping",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-trace-mapping",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@jridgewell/trace-mapping": "0.3.31"
      }
    },
    "node_modules/@jridgewell/resolve-uri": {
      "version": "3.1.2",
      "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
      "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.0.0"
      }
    },
    "node_modules/@jridgewell/sourcemap-codec": {
      "version": "1.5.5",
      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
      "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
      "license": "MIT"
    },
    "node_modules/@jridgewell/trace-mapping": {
      "version": "0.3.31",
      "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
      "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
      "license": "MIT",
      "dependencies": {
        "@jridgewell/resolve-uri": "^3.1.0",
        "@jridgewell/sourcemap-codec": "^1.4.14"
      }
    }
  }
}
package.json
{
  "name": "sample-trace-mapping",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @jridgewell/trace-mapping",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@jridgewell/trace-mapping": "0.3.31"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Trace original and generated positions using TraceMap and originalPositionFor",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40jridgewell/trace-mapping@0.3.31"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
const {
  TraceMap,
  originalPositionFor,
  generatedPositionFor,
  allGeneratedPositionsFor,
  sourceContentFor,
  decodedMappings,
  encodedMappings,
  encodedMap,
  decodedMap,
  eachMapping,
  LEAST_UPPER_BOUND,
  GREATEST_LOWER_BOUND,
} = require('@jridgewell/trace-mapping');

function createTraceMap(map, mapUrl) {
  return new TraceMap(map, mapUrl);
}

function findOriginalPosition(tracer, line, column, bias) {
  return originalPositionFor(tracer, { line, column, bias });
}

function findGeneratedPosition(tracer, source, line, column, bias) {
  return generatedPositionFor(tracer, { source, line, column, bias });
}

function getSourceContent(tracer, source) {
  return sourceContentFor(tracer, source);
}

module.exports = {
  TraceMap,
  originalPositionFor,
  generatedPositionFor,
  allGeneratedPositionsFor,
  sourceContentFor,
  decodedMappings,
  encodedMappings,
  encodedMap,
  decodedMap,
  eachMapping,
  LEAST_UPPER_BOUND,
  GREATEST_LOWER_BOUND,
  createTraceMap,
  findOriginalPosition,
  findGeneratedPosition,
  getSourceContent,
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  TraceMap,
  originalPositionFor,
  generatedPositionFor,
  allGeneratedPositionsFor,
  sourceContentFor,
  decodedMappings,
  encodedMappings,
  encodedMap,
  decodedMap,
  eachMapping,
  LEAST_UPPER_BOUND,
  GREATEST_LOWER_BOUND,
  createTraceMap,
  findOriginalPosition,
  findGeneratedPosition,
  getSourceContent,
} = require('../src/index.js');

const rawMap = {
  version: 3,
  file: 'output.js',
  sources: ['input.js'],
  sourcesContent: ['const greeting = "hello world";\nconsole.log(greeting);\n'],
  names: ['greeting', 'console', 'log'],
  mappings: 'AAAA,MAAMA,WAAW,aAAjB;AACAC,QAAQC,GAAR,CAAYF,QAAZ',
};

// 1. TraceMap parses a standard v3 source map and provides access to metadata fields
const tracer = createTraceMap(rawMap);
assert.ok(tracer instanceof TraceMap, 'createTraceMap should return a TraceMap instance');
assert.strictEqual(tracer.version, 3, 'version should be 3');
assert.strictEqual(tracer.file, 'output.js', 'file should match output.js');
assert.deepStrictEqual(tracer.sources, ['input.js'], 'sources should match input array');
assert.deepStrictEqual(tracer.names, ['greeting', 'console', 'log'], 'names should match input names');

// 2. originalPositionFor maps generated 1-based line and 0-based column to original source position and identifier name
const orig1 = findOriginalPosition(tracer, 1, 0);
assert.strictEqual(orig1.source, 'input.js', 'source should be input.js');
assert.strictEqual(orig1.line, 1, 'original line should be 1');
assert.strictEqual(orig1.column, 0, 'original column should be 0');

const origName = originalPositionFor(tracer, { line: 1, column: 6 });
assert.strictEqual(origName.source, 'input.js', 'source should be input.js');
assert.strictEqual(origName.line, 1, 'original line should be 1');
assert.strictEqual(origName.column, 6, 'original column should be 6');
assert.strictEqual(origName.name, 'greeting', 'name should resolve to greeting');

// 3. generatedPositionFor maps original source position back to generated 1-based line and 0-based column
const gen1 = findGeneratedPosition(tracer, 'input.js', 1, 6);
assert.strictEqual(gen1.line, 1, 'generated line should be 1');
assert.strictEqual(gen1.column, 6, 'generated column should be 6');

const genDirect = generatedPositionFor(tracer, { source: 'input.js', line: 1, column: 6 });
assert.strictEqual(genDirect.line, 1, 'generated line should be 1');
assert.strictEqual(genDirect.column, 6, 'generated column should be 6');

// 4. allGeneratedPositionsFor returns all generated locations corresponding to a source position
const allGen = allGeneratedPositionsFor(tracer, { source: 'input.js', line: 1, column: 6 });
assert.ok(Array.isArray(allGen), 'allGeneratedPositionsFor should return an array');
assert.ok(allGen.length >= 1, 'should find at least one generated position');
assert.strictEqual(allGen[0].line, 1, 'first generated line should be 1');
assert.strictEqual(allGen[0].column, 6, 'first generated column should be 6');

// 5. sourceContentFor retrieves the embedded source content for a source file
const content = getSourceContent(tracer, 'input.js');
assert.strictEqual(content, 'const greeting = "hello world";\nconsole.log(greeting);\n', 'sourceContent should match embedded content');
const missingContent = sourceContentFor(tracer, 'nonexistent.js');
assert.strictEqual(missingContent, null, 'missing source should return null content');

// 6. decodedMap and encodedMap convert TraceMap back to valid decoded and encoded source map objects
const enc = encodedMap(tracer);
assert.strictEqual(enc.version, 3, 'encoded map version should be 3');
assert.strictEqual(enc.mappings, 'AAAA,MAAMA,WAAW,aAAjB;AACAC,QAAQC,GAAR,CAAYF,QAAZ', 'encoded mappings should match');

const dec = decodedMap(tracer);
assert.strictEqual(dec.version, 3, 'decoded map version should be 3');
assert.ok(Array.isArray(dec.mappings), 'decoded mappings should be an array of lines');

// 7. eachMapping iterates over all mappings in generated order
const mappings = [];
eachMapping(tracer, (m) => {
  mappings.push(m);
});
assert.ok(mappings.length > 0, 'eachMapping should visit mappings');
assert.strictEqual(mappings[0].generatedLine, 1, 'first mapping line should be 1');

// 8. Bias constants
assert.strictEqual(LEAST_UPPER_BOUND, -1, 'LEAST_UPPER_BOUND constant should be -1');
assert.strictEqual(GREATEST_LOWER_BOUND, 1, 'GREATEST_LOWER_BOUND constant should be 1');

console.log('Contract tests passed successfully.');

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

аноним