CodeSampleX

Пример

estree-walker 3.0.3: walk

Проверенный пример — npm estree-walker 3.0.3: walk. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден: walk exports a function that…

sha256:747d7c84c8b8cdc0507837241e7eee4bd8f7a985f6d0c44665fae8e3b70f1162

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

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

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

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

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

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

Кейс

HOW
Цель
verify estree-walker.walk in pkg:npm/estree-walker@3.0.3
Пакеты
Символы
  • estree-walker.walk
Создан
2026-09-06T22:14:00Z

Контракт

  1. walk exports a function that traverses an ESTree AST synchronously visiting nodes in enter and leave order
  2. walk callbacks receive node, parent, prop and index arguments
  3. walk this.skip skips descending into child nodes of the current AST node during enter traversal
  4. walk this.replace substitutes the matched AST node in the parent tree
  5. walk this.remove deletes the matched AST node from parent array container

Файлы

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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: verify estree-walker.walk in pkg:npm/estree-walker@3.0.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/estree-walker@3.0.3
Demonstrate these symbols/APIs:
  - estree-walker.walk

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:9fefcc28ffe75e691b2b51ae7b214a187509f9a65afb7ccaaa42ecded4376cf2","contract":["walk exports a function that traverses an ESTree AST synchronously visiting nodes in enter and leave order","walk callbacks receive node, parent, prop and index arguments","walk this.skip skips descending into child nodes of the current AST node during enter traversal","walk this.replace substitutes the matched AST node in the parent tree","walk this.remove deletes the matched AST node from parent array container"],"goal":"verify estree-walker.walk in pkg:npm/estree-walker@3.0.3","kind":"HOW","packages":["pkg:npm/estree-walker@3.0.3"],"schemaVersion":1,"symbols":["estree-walker.walk"]},"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},"license":"MIT-0","packages":["pkg:npm/estree-walker@3.0.3"],"schemaVersion":1,"subject":"pkg:npm/estree-walker@3.0.3","symbols":["estree-walker.walk"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "csx-sample-estree-walker-walk",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "csx-sample-estree-walker-walk",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "estree-walker": "3.0.3"
      }
    },
    "node_modules/@types/estree": {
      "version": "1.0.9",
      "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
      "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
      "license": "MIT"
    },
    "node_modules/estree-walker": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
      "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
      "license": "MIT",
      "dependencies": {
        "@types/estree": "^1.0.0"
      }
    }
  }
}
package.json
{
  "name": "csx-sample-estree-walker-walk",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "estree-walker": "3.0.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify estree-walker.walk in pkg:npm/estree-walker@3.0.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/estree-walker@3.0.3"
  ],
  "symbols": [
    "estree-walker.walk"
  ]
}
src/index.mjs
import { walk } from 'estree-walker';

export { walk };

/**
 * Traverses an AST synchronously and collects all node types in visit order.
 *
 * @param {object} ast - The ESTree AST root node.
 * @returns {string[]} - Array of node types.
 */
export function collectNodeTypes(ast) {
  const types = [];
  walk(ast, {
    enter(node) {
      types.push(node.type);
    },
  });
  return types;
}

/**
 * Traverses an AST and renames identifiers based on a replacement map.
 *
 * @param {object} ast - The ESTree AST root node.
 * @param {Record<string, string>} mapping - Mapping from old name to new name.
 * @returns {object} - The modified AST.
 */
export function renameIdentifiers(ast, mapping) {
  return walk(ast, {
    enter(node) {
      if (node.type === 'Identifier' && Object.prototype.hasOwnProperty.call(mapping, node.name)) {
        this.replace({
          ...node,
          name: mapping[node.name],
        });
      }
    },
  });
}

/**
 * Removes statement nodes matching a predicate from an AST.
 *
 * @param {object} ast - The ESTree AST root node.
 * @param {(node: object) => boolean} predicate - Predicate returning true for nodes to remove.
 * @returns {object} - The modified AST.
 */
export function removeNodes(ast, predicate) {
  return walk(ast, {
    enter(node) {
      if (predicate(node)) {
        this.remove();
      }
    },
  });
}

/**
 * Walks an AST skipping children of nodes matching skipPredicate.
 *
 * @param {object} ast - The ESTree AST root node.
 * @param {(node: object) => boolean} skipPredicate - Predicate returning true to skip children.
 * @returns {string[]} - Collected node types.
 */
export function walkWithSkip(ast, skipPredicate) {
  const visited = [];
  walk(ast, {
    enter(node) {
      visited.push(node.type);
      if (skipPredicate(node)) {
        this.skip();
      }
    },
  });
  return visited;
}
test/contract.mjs
import { strict as assert } from 'node:assert';
import {
  walk,
  collectNodeTypes,
  renameIdentifiers,
  removeNodes,
  walkWithSkip,
} from '../src/index.mjs';

// 1. Verify walk exports a function that traverses an ESTree AST synchronously in enter and leave order
assert.equal(typeof walk, 'function', 'walk must be a function');

const ast = {
  type: 'Program',
  body: [
    {
      type: 'VariableDeclaration',
      kind: 'const',
      declarations: [
        {
          type: 'VariableDeclarator',
          id: { type: 'Identifier', name: 'greeting' },
          init: { type: 'Literal', value: 'hello' },
        },
      ],
    },
  ],
};

const enterOrder = [];
const leaveOrder = [];
walk(ast, {
  enter(node) {
    enterOrder.push(node.type);
  },
  leave(node) {
    leaveOrder.push(node.type);
  },
});

assert.deepEqual(
  enterOrder,
  ['Program', 'VariableDeclaration', 'VariableDeclarator', 'Identifier', 'Literal'],
  'enter callbacks must visit nodes top-down'
);
assert.deepEqual(
  leaveOrder,
  ['Identifier', 'Literal', 'VariableDeclarator', 'VariableDeclaration', 'Program'],
  'leave callbacks must visit nodes bottom-up'
);

// 2. Verify walk callbacks receive node, parent, prop and index arguments
let checkedCallbackArgs = false;
walk(ast, {
  enter(node, parent, prop, index) {
    if (node.type === 'VariableDeclaration') {
      assert.equal(parent.type, 'Program');
      assert.equal(prop, 'body');
      assert.equal(index, 0);
      checkedCallbackArgs = true;
    }
  },
});
assert.ok(checkedCallbackArgs, 'callback args parent, prop and index must be provided');

// 3. Verify walk this.skip skips descending into child nodes of current AST node
const blockAst = {
  type: 'Program',
  body: [
    {
      type: 'BlockStatement',
      body: [
        {
          type: 'ExpressionStatement',
          expression: { type: 'Identifier', name: 'inner' },
        },
      ],
    },
    {
      type: 'ExpressionStatement',
      expression: { type: 'Identifier', name: 'outer' },
    },
  ],
};

const visitedTypes = walkWithSkip(blockAst, (node) => node.type === 'BlockStatement');
assert.deepEqual(
  visitedTypes,
  ['Program', 'BlockStatement', 'ExpressionStatement', 'Identifier'],
  'BlockStatement children should have been skipped'
);

// 4. Verify walk this.replace substitutes matched AST node in parent tree
const replaceAst = {
  type: 'Program',
  body: [
    {
      type: 'ExpressionStatement',
      expression: { type: 'Identifier', name: 'foo' },
    },
  ],
};

renameIdentifiers(replaceAst, { foo: 'bar' });
assert.equal(replaceAst.body[0].expression.name, 'bar', 'Identifier foo should be replaced with bar');

// 5. Verify walk this.remove deletes matched AST node from parent array container
const removeAst = {
  type: 'Program',
  body: [
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'keep1' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'drop' } },
    { type: 'ExpressionStatement', expression: { type: 'Identifier', name: 'keep2' } },
  ],
};

removeNodes(removeAst, (node) => node.type === 'ExpressionStatement' && node.expression.name === 'drop');
assert.equal(removeAst.body.length, 2, 'Dropped node should be removed from body');
assert.equal(removeAst.body[0].expression.name, 'keep1');
assert.equal(removeAst.body[1].expression.name, 'keep2');

// 6. Verify collectNodeTypes helper
const collected = collectNodeTypes(ast);
assert.deepEqual(collected, ['Program', 'VariableDeclaration', 'VariableDeclarator', 'Identifier', 'Literal']);

console.log('CONTRACT PASS: estree-walker.walk verified');

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

аноним