CodeSampleX

샘플

typescript 6.0.3: Transform AST and print modified TypeScript code using transform and createPrinter

검증된 샘플 — npm typescript 6.0.3: Transform AST and print modified TypeScript code using transform and createPrinter. node 22 · linux alpine/x64 · docker에서…

sha256:04366161774f32322559591a633f220d8c2d3429f965f48087461184aac46e61

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

실행 증거

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

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

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20
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
목표
Transform AST and print modified TypeScript code using transform and createPrinter
패키지
심벌
  • createPrinter
  • transform
생성일
2026-08-20T04:10:22Z

컨트랙트

  1. transformSourceCode applies AST transformations to source code and prints the transformed AST using createPrinter
  2. createIdentifierRenameTransformer renames matching identifiers across functions, variables, and expressions using ts.factory
  3. createRemoveConsoleCallsTransformer removes console.log expression statements from the AST
  4. printAstNode formats and prints individual AST nodes using createPrinter

파일

  • 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: Transform AST and print modified TypeScript code using transform and createPrinter
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/typescript@6.0.3
Demonstrate these symbols/APIs:
  - createPrinter
  - transform

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:a4c91a4fd7643aa298d8b9946729a8336543d9fdc6c435522b9e5aeb6caa4cb1","contract":["transformSourceCode applies AST transformations to source code and prints the transformed AST using createPrinter","createIdentifierRenameTransformer renames matching identifiers across functions, variables, and expressions using ts.factory","createRemoveConsoleCallsTransformer removes console.log expression statements from the AST","printAstNode formats and prints individual AST nodes using createPrinter"],"goal":"Transform AST and print modified TypeScript code using transform and createPrinter","kind":"HOW","packages":["pkg:npm/typescript@6.0.3"],"schemaVersion":1,"symbols":["createPrinter","transform"]},"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/typescript@6.0.3"],"schemaVersion":1,"symbols":["createPrinter","transform"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "typescript-transform-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "typescript-transform-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "typescript": "6.0.3"
      }
    },
    "node_modules/typescript": {
      "version": "6.0.3",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
      "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc",
        "tsserver": "bin/tsserver"
      },
      "engines": {
        "node": ">=14.17"
      }
    }
  }
}
package.json
{
  "name": "typescript-transform-sample",
  "version": "1.0.0",
  "description": "Demonstrates AST transformation and printing using transform and createPrinter in TypeScript",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "typescript": "6.0.3"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Transform AST and print modified TypeScript code using transform and createPrinter",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@6.0.3"
  ],
  "symbols": [
    "createPrinter",
    "transform"
  ]
}
src/index.mjs
import ts from 'typescript';

/**
 * Transforms TypeScript source code using custom AST transformers and prints the result.
 *
 * @param {string} sourceText - TypeScript source code.
 * @param {Array<ts.TransformerFactory<ts.SourceFile>>} transformers - Custom AST transformer factories.
 * @param {ts.PrinterOptions} [printerOptions={}] - Options for ts.createPrinter.
 * @param {string} [fileName='input.ts'] - Source file name.
 * @returns {string} The transformed and printed TypeScript code.
 */
export function transformSourceCode(sourceText, transformers = [], printerOptions = {}, fileName = 'input.ts') {
  const sourceFile = ts.createSourceFile(
    fileName,
    sourceText,
    ts.ScriptTarget.Latest,
    true,
    ts.ScriptKind.TS
  );

  const transformationResult = ts.transform(sourceFile, transformers);
  const transformedSourceFile = transformationResult.transformed[0];

  const printer = ts.createPrinter({
    newLine: ts.NewLineKind.LineFeed,
    removeComments: false,
    ...printerOptions,
  });

  const output = printer.printFile(transformedSourceFile);
  transformationResult.dispose();

  return output;
}

/**
 * Creates an AST transformer factory that renames identifiers matching oldName to newName.
 *
 * @param {string} oldName - Identifier name to replace.
 * @param {string} newName - Replacement identifier name.
 * @returns {ts.TransformerFactory<ts.SourceFile>}
 */
export function createIdentifierRenameTransformer(oldName, newName) {
  return (context) => {
    const visitor = (node) => {
      if (ts.isIdentifier(node) && node.text === oldName) {
        return ts.factory.createIdentifier(newName);
      }
      return ts.visitEachChild(node, visitor, context);
    };

    return (sourceFile) => ts.visitNode(sourceFile, visitor);
  };
}

/**
 * Creates an AST transformer factory that removes console calls.
 *
 * @returns {ts.TransformerFactory<ts.SourceFile>}
 */
export function createRemoveConsoleCallsTransformer() {
  return (context) => {
    const visitor = (node) => {
      if (ts.isExpressionStatement(node)) {
        const expr = node.expression;
        if (
          ts.isCallExpression(expr) &&
          ts.isPropertyAccessExpression(expr.expression) &&
          ts.isIdentifier(expr.expression.expression) &&
          expr.expression.expression.text === 'console'
        ) {
          return undefined;
        }
      }
      return ts.visitEachChild(node, visitor, context);
    };

    return (sourceFile) => ts.visitNode(sourceFile, visitor);
  };
}

/**
 * Prints an individual AST node with custom printer settings.
 *
 * @param {ts.Node} node - AST node to print.
 * @param {ts.SourceFile} [sourceFile] - Associated source file for token positioning.
 * @param {ts.PrinterOptions} [printerOptions={}] - Options for ts.createPrinter.
 * @returns {string} Formatted code string of the AST node.
 */
export function printAstNode(node, sourceFile = undefined, printerOptions = {}) {
  const printer = ts.createPrinter({
    newLine: ts.NewLineKind.LineFeed,
    removeComments: false,
    ...printerOptions,
  });

  const dummySourceFile = sourceFile || ts.createSourceFile('temp.ts', '', ts.ScriptTarget.Latest);
  return printer.printNode(ts.EmitHint.Unspecified, node, dummySourceFile);
}

export { ts };
test/contract.mjs
import assert from 'node:assert/strict';
import {
  ts,
  transformSourceCode,
  createIdentifierRenameTransformer,
  createRemoveConsoleCallsTransformer,
  printAstNode,
} from '../src/index.mjs';

// Contract 1: transformSourceCode applies AST transformations to source code and prints the transformed AST using createPrinter
{
  const code = `
    function greet(person: string): string {
      return "Hello, " + person;
    }
  `;

  const output = transformSourceCode(code, []);
  assert.ok(typeof output === 'string', 'Output should be a string');
  assert.ok(output.includes('function greet(person: string): string'), 'Should preserve function signature');
  assert.ok(output.includes('return "Hello, " + person;'), 'Should preserve function body');
}

// Contract 2: createIdentifierRenameTransformer renames matching identifiers across functions, variables, and expressions using ts.factory
{
  const code = `
    const oldValue = 42;
    function compute(oldValue: number): number {
      return oldValue * 2;
    }
  `;

  const transformer = createIdentifierRenameTransformer('oldValue', 'newValue');
  const output = transformSourceCode(code, [transformer]);

  assert.ok(!output.includes('oldValue'), 'Source should no longer contain oldValue');
  assert.ok(output.includes('const newValue = 42;'), 'Variable declaration should be renamed to newValue');
  assert.ok(output.includes('function compute(newValue: number): number'), 'Parameter should be renamed to newValue');
  assert.ok(output.includes('return newValue * 2;'), 'Return expression should use newValue');
}

// Contract 3: createRemoveConsoleCallsTransformer removes console.log expression statements from the AST
{
  const code = `
    function processData(data: string[]): number {
      console.log("Starting process");
      const len = data.length;
      console.info("Processed items:", len);
      return len;
    }
  `;

  const transformer = createRemoveConsoleCallsTransformer();
  const output = transformSourceCode(code, [transformer]);

  assert.ok(!output.includes('console.log'), 'console.log statement should be removed');
  assert.ok(!output.includes('console.info'), 'console.info statement should be removed');
  assert.ok(output.includes('const len = data.length;'), 'Other statements should be preserved');
  assert.ok(output.includes('return len;'), 'Return statement should be preserved');
}

// Contract 4: printAstNode formats and prints individual AST nodes using createPrinter
{
  const binaryExpr = ts.factory.createBinaryExpression(
    ts.factory.createIdentifier('width'),
    ts.factory.createToken(ts.SyntaxKind.PlusToken),
    ts.factory.createNumericLiteral('100')
  );

  const printedExpr = printAstNode(binaryExpr);
  assert.strictEqual(printedExpr.trim(), 'width + 100', 'Should print binary expression correctly');

  const varDecl = ts.factory.createVariableStatement(
    [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
    ts.factory.createVariableDeclarationList(
      [
        ts.factory.createVariableDeclaration(
          ts.factory.createIdentifier('API_VERSION'),
          undefined,
          ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
          ts.factory.createStringLiteral('1.0.0')
        ),
      ],
      ts.NodeFlags.Const
    )
  );

  const printedDecl = printAstNode(varDecl);
  assert.ok(printedDecl.includes('export const API_VERSION: string = "1.0.0";'), 'Should print exported const declaration correctly');
}

console.log('All pkg:npm/typescript@6.0.3 contracts passed successfully.');

오리진 시더

익명