CodeSampleX

Ejemplo

@eslint/plugin-kit 0.7.3: TextSourceCodeBase.traverse

Muestra verificada para npm @eslint/plugin-kit 0.7.3: TextSourceCodeBase.traverse. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:93bb9b8bdb50d0ebbc1e50028c621ebc587e06491855a02d7f3eb1c8d386ca1f

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-05

Caso

HOW
Objetivo
verify TextSourceCodeBase.traverse in pkg:npm/%40eslint/plugin-kit@0.7.3
Paquetes
Símbolos
  • TextSourceCodeBase.traverse
Creado
2026-09-05T16:37:46Z

Contrato

  1. TextSourceCodeBase.prototype.traverse throws an error when called directly without subclass implementation
  2. Subclasses implement traverse to yield VisitNodeStep instances for AST nodes with enter and exit phases
  3. Subclasses can yield CallMethodStep instances during traversal to trigger custom analyzer steps
  4. Traversing an AST while recording parent information enables getParent and getAncestors queries on the source code instance
  5. traverse can be implemented as a generator yielding steps lazily and supports early termination

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 TextSourceCodeBase.traverse in pkg:npm/%40eslint/plugin-kit@0.7.3
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40eslint/plugin-kit@0.7.3
Demonstrate these symbols/APIs:
  - TextSourceCodeBase.traverse

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:60343aae236ab67fd32132decf7b1c042d960f556bf5b655c349e2154463a125","contract":["TextSourceCodeBase.prototype.traverse throws an error when called directly without subclass implementation","Subclasses implement traverse to yield VisitNodeStep instances for AST nodes with enter and exit phases","Subclasses can yield CallMethodStep instances during traversal to trigger custom analyzer steps","Traversing an AST while recording parent information enables getParent and getAncestors queries on the source code instance","traverse can be implemented as a generator yielding steps lazily and supports early termination"],"goal":"verify TextSourceCodeBase.traverse in pkg:npm/%40eslint/plugin-kit@0.7.3","kind":"HOW","packages":["pkg:npm/%40eslint/plugin-kit@0.7.3"],"schemaVersion":1,"symbols":["TextSourceCodeBase.traverse"]},"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/%40eslint/plugin-kit@0.7.3"],"schemaVersion":1,"subject":"pkg:npm/%40eslint/plugin-kit@0.7.3","symbols":["TextSourceCodeBase.traverse"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-eslint-plugin-kit",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-eslint-plugin-kit",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@eslint/plugin-kit": "0.7.3"
      }
    },
    "node_modules/@eslint/core": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz",
      "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==",
      "license": "Apache-2.0",
      "dependencies": {
        "@types/json-schema": "^7.0.15"
      },
      "engines": {
        "node": "^20.19.0 || ^22.13.0 || >=24"
      }
    },
    "node_modules/@eslint/plugin-kit": {
      "version": "0.7.3",
      "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.3.tgz",
      "integrity": "sha512-IkO+/KEUvwbVpiURZg+P7zF74z5Jxe0UgJxVni+RtoHQ6IZieXaO02kmadomap/q+l6bc/jdPGGqTjhuZnuz1Q==",
      "license": "Apache-2.0",
      "dependencies": {
        "@eslint/core": "^1.2.1",
        "levn": "^0.4.1"
      },
      "engines": {
        "node": "^20.19.0 || ^22.13.0 || >=24"
      }
    },
    "node_modules/@types/json-schema": {
      "version": "7.0.15",
      "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
      "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",
      "license": "MIT"
    },
    "node_modules/levn": {
      "version": "0.4.1",
      "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
      "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==",
      "license": "MIT",
      "dependencies": {
        "prelude-ls": "^1.2.1",
        "type-check": "~0.4.0"
      },
      "engines": {
        "node": ">= 0.8.0"
      }
    },
    "node_modules/prelude-ls": {
      "version": "1.2.1",
      "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
      "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==",
      "license": "MIT",
      "engines": {
        "node": ">= 0.8.0"
      }
    },
    "node_modules/type-check": {
      "version": "0.4.0",
      "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz",
      "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==",
      "license": "MIT",
      "dependencies": {
        "prelude-ls": "^1.2.1"
      },
      "engines": {
        "node": ">= 0.8.0"
      }
    }
  }
}
package.json
{
  "name": "sample-eslint-plugin-kit",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "@eslint/plugin-kit": "0.7.3"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify TextSourceCodeBase.traverse in pkg:npm/%40eslint/plugin-kit@0.7.3",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40eslint/plugin-kit@0.7.3"
  ],
  "symbols": [
    "TextSourceCodeBase.traverse"
  ]
}
src/index.mjs
import { TextSourceCodeBase, VisitNodeStep, CallMethodStep } from '@eslint/plugin-kit';

/**
 * Custom TextSourceCode implementation demonstrating AST traversal.
 */
export class TraversableSourceCode extends TextSourceCodeBase {
  #parents = new Map();

  /**
   * Returns the parent of the given node if recorded during traversal.
   * @param {object} node AST node
   * @returns {object|undefined}
   */
  getParent(node) {
    return this.#parents.get(node);
  }

  /**
   * Traverses the AST and yields traversal steps.
   * @returns {Iterable<VisitNodeStep|CallMethodStep>}
   */
  *traverse() {
    const self = this;

    function* walk(node, parent) {
      if (parent) {
        self.#parents.set(node, parent);
      }

      yield new VisitNodeStep({
        target: node,
        phase: 1,
        args: [node, parent],
      });

      if (node && Array.isArray(node.children)) {
        for (const child of node.children) {
          yield* walk(child, node);
        }
      }

      yield new VisitNodeStep({
        target: node,
        phase: 2,
        args: [node, parent],
      });
    }

    yield* walk(this.ast, undefined);
  }
}

export { TextSourceCodeBase, VisitNodeStep, CallMethodStep };
export default TraversableSourceCode;
test/contract.mjs
import assert from 'node:assert/strict';
import { TextSourceCodeBase, VisitNodeStep, CallMethodStep, TraversableSourceCode } from '../src/index.mjs';

// 1. TextSourceCodeBase.prototype.traverse throws an error when called directly without subclass implementation
{
  const base = new TextSourceCodeBase({
    text: 'const x = 1;',
    ast: { type: 'Program', body: [] },
  });

  assert.throws(
    () => base.traverse(),
    {
      name: 'Error',
      message: 'Not implemented.',
    },
  );
}

// 2. Subclasses implement traverse to yield VisitNodeStep instances for AST nodes with enter and exit phases
{
  class StepSourceCode extends TextSourceCodeBase {
    *traverse() {
      yield new VisitNodeStep({
        target: this.ast,
        phase: 1,
        args: [this.ast],
      });
      yield new VisitNodeStep({
        target: this.ast,
        phase: 2,
        args: [this.ast],
      });
    }
  }

  const root = { type: 'Program' };
  const source = new StepSourceCode({ text: 'var a = 1;', ast: root });
  const steps = Array.from(source.traverse());

  assert.equal(steps.length, 2);
  assert.equal(steps[0].type, 'visit');
  assert.equal(steps[0].kind, 1);
  assert.equal(steps[0].phase, 1);
  assert.equal(steps[0].target, root);
  assert.deepEqual(steps[0].args, [root]);

  assert.equal(steps[1].type, 'visit');
  assert.equal(steps[1].kind, 1);
  assert.equal(steps[1].phase, 2);
  assert.equal(steps[1].target, root);
}

// 3. Subclasses can yield CallMethodStep instances during traversal to trigger custom analyzer steps
{
  class HookSourceCode extends TextSourceCodeBase {
    *traverse() {
      yield new CallMethodStep({
        target: 'onBeforeTraverse',
        args: ['scope1'],
      });
      yield new VisitNodeStep({
        target: this.ast,
        phase: 1,
        args: [this.ast],
      });
      yield new CallMethodStep({
        target: 'onAfterTraverse',
        args: ['scope1', true],
      });
    }
  }

  const root = { type: 'Program' };
  const source = new HookSourceCode({ text: 'var a = 1;', ast: root });
  const steps = Array.from(source.traverse());

  assert.equal(steps.length, 3);
  assert.equal(steps[0].type, 'call');
  assert.equal(steps[0].kind, 2);
  assert.equal(steps[0].target, 'onBeforeTraverse');
  assert.deepEqual(steps[0].args, ['scope1']);

  assert.equal(steps[1].type, 'visit');
  assert.equal(steps[1].target, root);

  assert.equal(steps[2].type, 'call');
  assert.equal(steps[2].kind, 2);
  assert.equal(steps[2].target, 'onAfterTraverse');
  assert.deepEqual(steps[2].args, ['scope1', true]);
}

// 4. Traversing an AST while recording parent information enables getParent and getAncestors queries on the source code instance
{
  const child = { type: 'Identifier', name: 'foo' };
  const parent = { type: 'ExpressionStatement', children: [child] };
  const root = { type: 'Program', children: [parent] };

  const source = new TraversableSourceCode({ text: 'foo;', ast: root });

  // Before traversal, parents are not yet recorded
  assert.equal(source.getParent(child), undefined);

  // Traverse through AST
  const steps = Array.from(source.traverse());
  assert.equal(steps.length, 6); // 3 nodes * 2 (enter + exit)

  // After traversal, getParent and getAncestors are populated
  assert.equal(source.getParent(child), parent);
  assert.equal(source.getParent(parent), root);
  assert.deepEqual(source.getAncestors(child), [root, parent]);
  assert.deepEqual(source.getAncestors(parent), [root]);
}

// 5. traverse can be implemented as a generator yielding steps lazily and supports early termination
{
  let yieldedCount = 0;
  class LazySourceCode extends TextSourceCodeBase {
    *traverse() {
      for (let i = 0; i < 100; i++) {
        yieldedCount++;
        yield new VisitNodeStep({
          target: { type: 'Item', index: i },
          phase: 1,
          args: [i],
        });
      }
    }
  }

  const source = new LazySourceCode({ text: '', ast: {} });
  for (const step of source.traverse()) {
    if (step.args[0] === 2) {
      break;
    }
  }

  // Early break stopped iteration at 3 items
  assert.equal(yieldedCount, 3);
}

console.log('Contract assertions passed.');

Seeder de origen

anónimo