CodeSampleX

Пример

typescript 7.0.2: Construct and validate TypeScript AST nodes using createBinaryExpression and createCallExpression

Проверенный пример — npm typescript 7.0.2: Construct and validate TypeScript AST nodes using createBinaryExpression and createCallExpression. Контракт…

sha256:12aa274d62a50e0a7c65f2c61b3d6cb0c40e661f2a2519f8320091b44adf729d

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

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

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

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

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

Окружение Контракт Этапы Запуск
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-20

Кейс

HOW
Цель
Construct and validate TypeScript AST nodes using createBinaryExpression and createCallExpression
Пакеты
Символы
  • createBinaryExpression
  • createCallExpression
Создан
2026-08-20T04:22:30Z

Контракт

  1. buildBinaryExpression constructs binary AST expressions with specified operator tokens and validates them with isBinaryExpression
  2. buildCallExpression constructs call expression AST nodes with callee identifier and arguments validating them with isCallExpression
  3. buildFunctionDeclaration constructs a function declaration AST enclosing return statements and parameter declarations
  4. inspectAstNode identifies and categorizes AST node kinds and syntactic structures using type guards

Файлы

  • 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: Construct and validate TypeScript AST nodes using createBinaryExpression and createCallExpression
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/typescript@7.0.2
Demonstrate these symbols/APIs:
  - createBinaryExpression
  - createCallExpression

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:0913fc764589939e803264469932fe0273bba17c6f15892a5f75fad268b6047b","contract":["buildBinaryExpression constructs binary AST expressions with specified operator tokens and validates them with isBinaryExpression","buildCallExpression constructs call expression AST nodes with callee identifier and arguments validating them with isCallExpression","buildFunctionDeclaration constructs a function declaration AST enclosing return statements and parameter declarations","inspectAstNode identifies and categorizes AST node kinds and syntactic structures using type guards"],"goal":"Construct and validate TypeScript AST nodes using createBinaryExpression and createCallExpression","kind":"HOW","packages":["pkg:npm/typescript@7.0.2"],"schemaVersion":1,"symbols":["createBinaryExpression","createCallExpression"]},"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@7.0.2"],"schemaVersion":1,"symbols":["createBinaryExpression","createCallExpression"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "typescript-ast-factory-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "typescript-ast-factory-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "typescript": "7.0.2"
      }
    },
    "node_modules/@typescript/typescript-aix-ppc64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
      "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
      "cpu": [
        "ppc64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "aix"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-darwin-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
      "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-darwin-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
      "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "darwin"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-freebsd-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
      "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-freebsd-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
      "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "freebsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-arm": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
      "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
      "cpu": [
        "arm"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
      "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-loong64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
      "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
      "cpu": [
        "loong64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-mips64el": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
      "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
      "cpu": [
        "mips64el"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-ppc64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
      "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
      "cpu": [
        "ppc64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-riscv64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
      "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
      "cpu": [
        "riscv64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-s390x": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
      "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
      "cpu": [
        "s390x"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-linux-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
      "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "linux"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-netbsd-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
      "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "netbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-netbsd-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
      "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "netbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-openbsd-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
      "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "openbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-openbsd-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
      "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "openbsd"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-sunos-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
      "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "sunos"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-win32-arm64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
      "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
      "cpu": [
        "arm64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/@typescript/typescript-win32-x64": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
      "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
      "cpu": [
        "x64"
      ],
      "license": "Apache-2.0",
      "optional": true,
      "os": [
        "win32"
      ],
      "engines": {
        "node": ">=16.20.0"
      }
    },
    "node_modules/typescript": {
      "version": "7.0.2",
      "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
      "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
      "license": "Apache-2.0",
      "bin": {
        "tsc": "bin/tsc"
      },
      "engines": {
        "node": ">=16.20.0"
      },
      "optionalDependencies": {
        "@typescript/typescript-aix-ppc64": "7.0.2",
        "@typescript/typescript-darwin-arm64": "7.0.2",
        "@typescript/typescript-darwin-x64": "7.0.2",
        "@typescript/typescript-freebsd-arm64": "7.0.2",
        "@typescript/typescript-freebsd-x64": "7.0.2",
        "@typescript/typescript-linux-arm": "7.0.2",
        "@typescript/typescript-linux-arm64": "7.0.2",
        "@typescript/typescript-linux-loong64": "7.0.2",
        "@typescript/typescript-linux-mips64el": "7.0.2",
        "@typescript/typescript-linux-ppc64": "7.0.2",
        "@typescript/typescript-linux-riscv64": "7.0.2",
        "@typescript/typescript-linux-s390x": "7.0.2",
        "@typescript/typescript-linux-x64": "7.0.2",
        "@typescript/typescript-netbsd-arm64": "7.0.2",
        "@typescript/typescript-netbsd-x64": "7.0.2",
        "@typescript/typescript-openbsd-arm64": "7.0.2",
        "@typescript/typescript-openbsd-x64": "7.0.2",
        "@typescript/typescript-sunos-x64": "7.0.2",
        "@typescript/typescript-win32-arm64": "7.0.2",
        "@typescript/typescript-win32-x64": "7.0.2"
      }
    }
  }
}
package.json
{
  "name": "typescript-ast-factory-sample",
  "version": "1.0.0",
  "description": "Minimal sample demonstrating createBinaryExpression and createCallExpression AST factory APIs in TypeScript",
  "type": "module",
  "main": "src/index.mjs",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "typescript": "7.0.2"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Construct and validate TypeScript AST nodes using createBinaryExpression and createCallExpression",
  "kind": "HOW",
  "packages": [
    "pkg:npm/typescript@7.0.2"
  ],
  "symbols": [
    "createBinaryExpression",
    "createCallExpression"
  ]
}
src/index.mjs
import {
  createBinaryExpression,
  createCallExpression,
  createIdentifier,
  createNumericLiteral,
  createStringLiteral,
  createToken,
  createBlock,
  createReturnStatement,
  createFunctionDeclaration,
  createParameterDeclaration,
} from 'typescript/unstable/ast/factory';

import {
  isBinaryExpression,
  isCallExpression,
  isIdentifier,
  isNumericLiteral,
  isStringLiteral,
  isFunctionDeclaration,
  isReturnStatement,
  isBlock,
  isToken,
} from 'typescript/unstable/ast/is';

import {
  SyntaxKind,
  formatSyntaxKind,
} from 'typescript/unstable/ast';

/**
 * Converts a primitive value or name into an AST node.
 *
 * @param {string | number | object} value - Primitive value or AST node.
 * @returns {object} AST node.
 */
function toAstNode(value) {
  if (typeof value === 'number') {
    return createNumericLiteral(String(value));
  }
  if (typeof value === 'string') {
    return createIdentifier(value);
  }
  return value;
}

/**
 * Constructs a binary expression AST node with the specified operands and operator token.
 *
 * @param {string | number | object} left - Left operand (identifier name, literal, or node).
 * @param {number} operatorKind - SyntaxKind token kind for the binary operator.
 * @param {string | number | object} right - Right operand (identifier name, literal, or node).
 * @returns {object} BinaryExpression AST node.
 */
export function buildBinaryExpression(left, operatorKind, right) {
  const leftNode = toAstNode(left);
  const rightNode = toAstNode(right);
  const operatorToken = createToken(operatorKind);
  return createBinaryExpression(undefined, leftNode, undefined, operatorToken, rightNode);
}

/**
 * Constructs a call expression AST node with a callee and argument list.
 *
 * @param {string | object} callee - Callee identifier name or AST expression node.
 * @param {Array<string | number | object>} [args=[]] - Argument expressions or literals.
 * @returns {object} CallExpression AST node.
 */
export function buildCallExpression(callee, args = []) {
  const calleeNode = typeof callee === 'string' ? createIdentifier(callee) : callee;
  const argNodes = args.map((arg) => {
    if (typeof arg === 'string' && arg.startsWith('"') && arg.endsWith('"')) {
      return createStringLiteral(arg.slice(1, -1));
    }
    return toAstNode(arg);
  });
  return createCallExpression(calleeNode, undefined, undefined, argNodes, 0);
}

/**
 * Constructs a function declaration AST node with parameters and body statements.
 *
 * @param {string} name - Function name.
 * @param {string[]} params - Parameter names.
 * @param {object[]} statements - Array of AST statement nodes.
 * @returns {object} FunctionDeclaration AST node.
 */
export function buildFunctionDeclaration(name, params, statements) {
  const nameNode = createIdentifier(name);
  const paramNodes = params.map((param) =>
    createParameterDeclaration(undefined, undefined, createIdentifier(param), undefined, undefined, undefined)
  );
  const block = createBlock(statements, true);
  return createFunctionDeclaration(
    undefined,
    undefined,
    nameNode,
    undefined,
    paramNodes,
    undefined,
    block
  );
}

/**
 * Inspects an AST node and returns structural metadata using type guards.
 *
 * @param {object} node - AST node to inspect.
 * @returns {{
 *   kind: number,
 *   kindName: string,
 *   isBinary: boolean,
 *   isCall: boolean,
 *   isIdentifier: boolean,
 *   isFunction: boolean,
 *   isBlock: boolean,
 *   isReturn: boolean
 * }} Node inspection metadata.
 */
export function inspectAstNode(node) {
  if (!node || typeof node !== 'object') {
    throw new TypeError('Expected an AST node object');
  }
  return {
    kind: node.kind,
    kindName: formatSyntaxKind(node.kind),
    isBinary: isBinaryExpression(node),
    isCall: isCallExpression(node),
    isIdentifier: isIdentifier(node),
    isFunction: isFunctionDeclaration(node),
    isBlock: isBlock(node),
    isReturn: isReturnStatement(node),
  };
}

export {
  createBinaryExpression,
  createCallExpression,
  createIdentifier,
  createNumericLiteral,
  createStringLiteral,
  createToken,
  createBlock,
  createReturnStatement,
  createFunctionDeclaration,
  createParameterDeclaration,
  isBinaryExpression,
  isCallExpression,
  isIdentifier,
  isNumericLiteral,
  isStringLiteral,
  isFunctionDeclaration,
  isReturnStatement,
  isBlock,
  isToken,
  SyntaxKind,
  formatSyntaxKind,
};
test/contract.mjs
import assert from 'node:assert/strict';
import {
  buildBinaryExpression,
  buildCallExpression,
  buildFunctionDeclaration,
  inspectAstNode,
  createReturnStatement,
  createNumericLiteral,
  SyntaxKind,
  formatSyntaxKind,
  isBinaryExpression,
  isCallExpression,
  isIdentifier,
  isFunctionDeclaration,
  isToken,
} from '../src/index.mjs';

// Contract 1: buildBinaryExpression constructs binary AST expressions with specified operator tokens and validates them with isBinaryExpression
{
  const binaryNode = buildBinaryExpression('total', SyntaxKind.PlusToken, 42);

  assert.ok(binaryNode, 'Binary expression node should be created');
  assert.strictEqual(isBinaryExpression(binaryNode), true, 'Node should satisfy isBinaryExpression type guard');
  assert.strictEqual(formatSyntaxKind(binaryNode.kind), 'BinaryExpression', 'Kind name should be BinaryExpression');

  assert.strictEqual(isIdentifier(binaryNode.left), true, 'Left child should be an Identifier');
  assert.strictEqual(isToken(binaryNode.operatorToken), true, 'Operator token should satisfy isToken');
  assert.strictEqual(binaryNode.operatorToken.kind, SyntaxKind.PlusToken, 'Operator should be PlusToken');
  assert.strictEqual(formatSyntaxKind(binaryNode.right.kind), 'NumericLiteral', 'Right child should be NumericLiteral');

  // Nested binary expression: (a * b) + c
  const mulNode = buildBinaryExpression('a', SyntaxKind.AsteriskToken, 'b');
  const complexBinary = buildBinaryExpression(mulNode, SyntaxKind.PlusToken, 'c');
  assert.strictEqual(isBinaryExpression(complexBinary), true, 'Complex binary expression should be binary');
  assert.strictEqual(isBinaryExpression(complexBinary.left), true, 'Left child of complex binary should be binary');
}

// Contract 2: buildCallExpression constructs call expression AST nodes with callee identifier and arguments validating them with isCallExpression
{
  const callNode = buildCallExpression('calculateMetrics', ['"alpha"', 100, 'flag']);

  assert.ok(callNode, 'Call expression node should be created');
  assert.strictEqual(isCallExpression(callNode), true, 'Node should satisfy isCallExpression type guard');
  assert.strictEqual(formatSyntaxKind(callNode.kind), 'CallExpression', 'Kind name should be CallExpression');

  assert.strictEqual(isIdentifier(callNode.expression), true, 'Callee should be an Identifier');
  assert.strictEqual(callNode.arguments.length, 3, 'Call expression should have 3 arguments');
  assert.strictEqual(formatSyntaxKind(callNode.arguments[0].kind), 'StringLiteral', 'First argument should be StringLiteral');
  assert.strictEqual(formatSyntaxKind(callNode.arguments[1].kind), 'NumericLiteral', 'Second argument should be NumericLiteral');
  assert.strictEqual(formatSyntaxKind(callNode.arguments[2].kind), 'Identifier', 'Third argument should be Identifier');
}

// Contract 3: buildFunctionDeclaration constructs a function declaration AST enclosing return statements and parameter declarations
{
  const returnExpr = buildBinaryExpression('x', SyntaxKind.AsteriskToken, 'y');
  const returnStmt = createReturnStatement(returnExpr);
  const fnNode = buildFunctionDeclaration('multiply', ['x', 'y'], [returnStmt]);

  assert.ok(fnNode, 'Function declaration node should be created');
  assert.strictEqual(isFunctionDeclaration(fnNode), true, 'Node should satisfy isFunctionDeclaration type guard');
  assert.strictEqual(formatSyntaxKind(fnNode.kind), 'FunctionDeclaration', 'Kind name should be FunctionDeclaration');

  assert.strictEqual(isIdentifier(fnNode.name), true, 'Function name should be an Identifier');
  assert.strictEqual(fnNode.parameters.length, 2, 'Function should have 2 parameters');
  assert.strictEqual(isIdentifier(fnNode.parameters[0].name), true, 'First parameter name should be Identifier');
  assert.strictEqual(isIdentifier(fnNode.parameters[1].name), true, 'Second parameter name should be Identifier');

  assert.strictEqual(fnNode.body.statements.length, 1, 'Function body should have 1 statement');
  assert.strictEqual(formatSyntaxKind(fnNode.body.statements[0].kind), 'ReturnStatement', 'Statement should be ReturnStatement');
}

// Contract 4: inspectAstNode identifies and categorizes AST node kinds and syntactic structures using type guards
{
  const binary = buildBinaryExpression('width', SyntaxKind.SlashToken, 2);
  const infoBinary = inspectAstNode(binary);

  assert.strictEqual(infoBinary.kindName, 'BinaryExpression', 'info.kindName should match');
  assert.strictEqual(infoBinary.isBinary, true, 'info.isBinary should be true');
  assert.strictEqual(infoBinary.isCall, false, 'info.isCall should be false');
  assert.strictEqual(infoBinary.isFunction, false, 'info.isFunction should be false');

  const call = buildCallExpression('logEvent', ['"click"']);
  const infoCall = inspectAstNode(call);

  assert.strictEqual(infoCall.kindName, 'CallExpression', 'info.kindName should match');
  assert.strictEqual(infoCall.isCall, true, 'info.isCall should be true');
  assert.strictEqual(infoCall.isBinary, false, 'info.isBinary should be false');

  assert.throws(
    () => inspectAstNode(null),
    { name: 'TypeError' },
    'inspectAstNode should throw TypeError for invalid input'
  );
}

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

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

аноним