CodeSampleX

サンプル

@babel/types 7.29.8: functionDeclaration

検証済みサンプル — npm @babel/types 7.29.8: functionDeclaration. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました: types.functionDeclaration creates a…

sha256:5c838ecf833b6e52d9852ed2669f09e42b55b27b575dc5d1371645b79b12e40d

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 npm

検証実行環境

環境 コントラクト ステージ 実行日
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-23

ケース

HOW
ゴール
verify @babel/types.functionDeclaration in pkg:npm/%40babel/types@7.29.8
パッケージ
シンボル
  • @babel/types.functionDeclaration
作成日
2026-08-23T04:35:37Z

コントラクト

  1. types.functionDeclaration creates a FunctionDeclaration AST node with specified identifier, parameters, body, and default generator and async flags set to false
  2. types.functionDeclaration creates async and generator function declarations when async or generator flags are set to true
  3. types.functionDeclaration creates anonymous function declarations when null is provided as the identifier
  4. types.isFunctionDeclaration returns true for FunctionDeclaration nodes with optional property matching and false for non-FunctionDeclaration nodes
  5. types.assertFunctionDeclaration succeeds for valid FunctionDeclaration nodes and throws an Error for invalid or mismatching nodes
  6. FunctionDeclaration nodes integrate with parameter patterns including Identifier, AssignmentPattern, and RestElement
  7. types.cloneNode produces an independent equivalent copy of a FunctionDeclaration node

ファイル

  • 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: verify @babel/types.functionDeclaration in pkg:npm/%40babel/types@7.29.8
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40babel/types@7.29.8
Demonstrate these symbols/APIs:
  - @babel/types.functionDeclaration

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:2e784e999f63742ed53590dd6322c8eab1e5b5977da3de465d52a7f512f1fe6b","contract":["types.functionDeclaration creates a FunctionDeclaration AST node with specified identifier, parameters, body, and default generator and async flags set to false","types.functionDeclaration creates async and generator function declarations when async or generator flags are set to true","types.functionDeclaration creates anonymous function declarations when null is provided as the identifier","types.isFunctionDeclaration returns true for FunctionDeclaration nodes with optional property matching and false for non-FunctionDeclaration nodes","types.assertFunctionDeclaration succeeds for valid FunctionDeclaration nodes and throws an Error for invalid or mismatching nodes","FunctionDeclaration nodes integrate with parameter patterns including Identifier, AssignmentPattern, and RestElement","types.cloneNode produces an independent equivalent copy of a FunctionDeclaration node"],"goal":"verify @babel/types.functionDeclaration in pkg:npm/%40babel/types@7.29.8","kind":"HOW","packages":["pkg:npm/%40babel/types@7.29.8"],"schemaVersion":1,"symbols":["@babel/types.functionDeclaration"]},"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/%40babel/types@7.29.8"],"schemaVersion":1,"subject":"pkg:npm/%40babel/types@7.29.8","symbols":["@babel/types.functionDeclaration"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-babel-types-function-declaration",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-babel-types-function-declaration",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@babel/types": "7.29.8"
      }
    },
    "node_modules/@babel/helper-string-parser": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
      "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-validator-identifier": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/types": {
      "version": "7.29.8",
      "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
      "integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-string-parser": "^7.29.7",
        "@babel/helper-validator-identifier": "^7.29.7"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-babel-types-function-declaration",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @babel/types.functionDeclaration",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@babel/types": "7.29.8"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @babel/types.functionDeclaration in pkg:npm/%40babel/types@7.29.8",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40babel/types@7.29.8"
  ],
  "symbols": [
    "@babel/types.functionDeclaration"
  ]
}
src/index.js
const t = require('@babel/types');

/**
 * Creates a FunctionDeclaration AST node.
 * @param {string|object|null} id - Identifier node or string name, or null for anonymous functions.
 * @param {Array<object>} params - List of pattern AST nodes (e.g. Identifier, AssignmentPattern, RestElement).
 * @param {object|Array<object>} body - BlockStatement node or array of statement nodes.
 * @param {boolean} [generator=false] - Whether this is a generator function.
 * @param {boolean} [async=false] - Whether this is an async function.
 * @returns {object} FunctionDeclaration AST node.
 */
function createFunctionDeclaration(id, params, body, generator = false, async = false) {
  const idNode = typeof id === 'string' ? t.identifier(id) : id;
  const bodyBlock = Array.isArray(body) ? t.blockStatement(body) : body;
  return t.functionDeclaration(idNode, params, bodyBlock, generator, async);
}

/**
 * Creates an async FunctionDeclaration AST node.
 * @param {string|object|null} id
 * @param {Array<object>} params
 * @param {object|Array<object>} body
 * @returns {object}
 */
function createAsyncFunctionDeclaration(id, params, body) {
  return createFunctionDeclaration(id, params, body, false, true);
}

/**
 * Creates a generator FunctionDeclaration AST node.
 * @param {string|object|null} id
 * @param {Array<object>} params
 * @param {object|Array<object>} body
 * @returns {object}
 */
function createGeneratorFunctionDeclaration(id, params, body) {
  return createFunctionDeclaration(id, params, body, true, false);
}

/**
 * Creates an anonymous FunctionDeclaration AST node (e.g., default export).
 * @param {Array<object>} params
 * @param {object|Array<object>} body
 * @param {boolean} [generator=false]
 * @param {boolean} [async=false]
 * @returns {object}
 */
function createAnonymousFunctionDeclaration(params, body, generator = false, async = false) {
  return createFunctionDeclaration(null, params, body, generator, async);
}

/**
 * Creates a FunctionDeclaration with parameters, default values, and rest elements.
 * @param {string} name
 * @param {Array<{ name: string, defaultValue?: object }>} standardParams
 * @param {string} [restParamName]
 * @param {Array<object>} [statements=[]]
 * @returns {object}
 */
function createFunctionWithComplexParams(name, standardParams, restParamName, statements = []) {
  const id = t.identifier(name);
  const params = standardParams.map((p) => {
    const paramId = t.identifier(p.name);
    if (p.defaultValue) {
      return t.assignmentPattern(paramId, p.defaultValue);
    }
    return paramId;
  });

  if (restParamName) {
    params.push(t.restElement(t.identifier(restParamName)));
  }

  return t.functionDeclaration(id, params, t.blockStatement(statements));
}

/**
 * Checks if a node is a FunctionDeclaration, optionally matching properties.
 * @param {object} node
 * @param {object} [opts]
 * @returns {boolean}
 */
function isFunctionDeclarationNode(node, opts) {
  return t.isFunctionDeclaration(node, opts);
}

/**
 * Asserts that a node is a FunctionDeclaration, throwing an error if not.
 * @param {object} node
 * @param {object} [opts]
 */
function assertFunctionDeclarationNode(node, opts) {
  t.assertFunctionDeclaration(node, opts);
}

/**
 * Clones a FunctionDeclaration AST node.
 * @param {object} node
 * @returns {object}
 */
function cloneFunctionDeclaration(node) {
  return t.cloneNode(node);
}

module.exports = {
  t,
  createFunctionDeclaration,
  createAsyncFunctionDeclaration,
  createGeneratorFunctionDeclaration,
  createAnonymousFunctionDeclaration,
  createFunctionWithComplexParams,
  isFunctionDeclarationNode,
  assertFunctionDeclarationNode,
  cloneFunctionDeclaration,
};
test/contract.mjs
import assert from 'node:assert';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const {
  t,
  createFunctionDeclaration,
  createAsyncFunctionDeclaration,
  createGeneratorFunctionDeclaration,
  createAnonymousFunctionDeclaration,
  createFunctionWithComplexParams,
  isFunctionDeclarationNode,
  assertFunctionDeclarationNode,
  cloneFunctionDeclaration,
} = require('../src/index.js');

async function runContract() {
  // 1. types.functionDeclaration creates a FunctionDeclaration AST node with specified identifier, parameters, body, and default generator and async flags set to false
  const idNode = t.identifier('computeTotal');
  const paramNode = t.identifier('items');
  const returnStmt = t.returnStatement(paramNode);
  const bodyBlock = t.blockStatement([returnStmt]);

  const fnNode = createFunctionDeclaration(idNode, [paramNode], bodyBlock);
  assert.strictEqual(fnNode.type, 'FunctionDeclaration');
  assert.strictEqual(fnNode.id.type, 'Identifier');
  assert.strictEqual(fnNode.id.name, 'computeTotal');
  assert.strictEqual(fnNode.params.length, 1);
  assert.strictEqual(fnNode.params[0], paramNode);
  assert.strictEqual(fnNode.body.type, 'BlockStatement');
  assert.strictEqual(fnNode.body.body.length, 1);
  assert.strictEqual(fnNode.body.body[0], returnStmt);
  assert.strictEqual(fnNode.generator, false);
  assert.strictEqual(fnNode.async, false);

  // String identifier convenience helper
  const fnFromString = createFunctionDeclaration('sum', [], []);
  assert.strictEqual(fnFromString.type, 'FunctionDeclaration');
  assert.strictEqual(fnFromString.id.name, 'sum');
  assert.strictEqual(fnFromString.body.type, 'BlockStatement');

  // 2. types.functionDeclaration creates async and generator function declarations when async or generator flags are set to true
  const asyncFn = createAsyncFunctionDeclaration('fetchData', [t.identifier('url')], []);
  assert.strictEqual(asyncFn.type, 'FunctionDeclaration');
  assert.strictEqual(asyncFn.id.name, 'fetchData');
  assert.strictEqual(asyncFn.async, true);
  assert.strictEqual(asyncFn.generator, false);

  const genFn = createGeneratorFunctionDeclaration('range', [t.identifier('max')], []);
  assert.strictEqual(genFn.type, 'FunctionDeclaration');
  assert.strictEqual(genFn.id.name, 'range');
  assert.strictEqual(genFn.async, false);
  assert.strictEqual(genFn.generator, true);

  const asyncGenFn = createFunctionDeclaration('streamNumbers', [], [], true, true);
  assert.strictEqual(asyncGenFn.type, 'FunctionDeclaration');
  assert.strictEqual(asyncGenFn.async, true);
  assert.strictEqual(asyncGenFn.generator, true);

  // 3. types.functionDeclaration creates anonymous function declarations when null is provided as the identifier
  const anonFn = createAnonymousFunctionDeclaration([t.identifier('event')], []);
  assert.strictEqual(anonFn.type, 'FunctionDeclaration');
  assert.strictEqual(anonFn.id, null);
  assert.strictEqual(anonFn.params.length, 1);
  assert.strictEqual(anonFn.params[0].name, 'event');
  assert.strictEqual(anonFn.generator, false);
  assert.strictEqual(anonFn.async, false);

  // 4. types.isFunctionDeclaration returns true for FunctionDeclaration nodes with optional property matching and false for non-FunctionDeclaration nodes
  assert.strictEqual(isFunctionDeclarationNode(fnNode), true);
  assert.strictEqual(isFunctionDeclarationNode(fnNode, { id: idNode }), true);
  assert.strictEqual(isFunctionDeclarationNode(fnNode, { async: false }), true);
  assert.strictEqual(isFunctionDeclarationNode(fnNode, { async: true }), false);
  assert.strictEqual(isFunctionDeclarationNode(asyncFn, { async: true }), true);
  assert.strictEqual(isFunctionDeclarationNode(genFn, { generator: true }), true);
  assert.strictEqual(isFunctionDeclarationNode(anonFn, { id: null }), true);

  const idOnly = t.identifier('notAFunction');
  assert.strictEqual(isFunctionDeclarationNode(idOnly), false);
  assert.strictEqual(isFunctionDeclarationNode(null), false);
  assert.strictEqual(isFunctionDeclarationNode(undefined), false);

  // 5. types.assertFunctionDeclaration succeeds for valid FunctionDeclaration nodes and throws an Error for invalid or mismatching nodes
  assertFunctionDeclarationNode(fnNode);
  assertFunctionDeclarationNode(asyncFn, { async: true });
  assertFunctionDeclarationNode(genFn, { generator: true });
  assertFunctionDeclarationNode(anonFn, { id: null });

  assert.throws(
    () => assertFunctionDeclarationNode(idOnly),
    (err) => err instanceof Error,
    'assertFunctionDeclaration on non-FunctionDeclaration node must throw'
  );
  assert.throws(
    () => assertFunctionDeclarationNode(fnNode, { async: true }),
    (err) => err instanceof Error,
    'assertFunctionDeclaration with mismatching async option must throw'
  );

  // 6. FunctionDeclaration nodes integrate with parameter patterns including Identifier, AssignmentPattern, and RestElement
  const complexFn = createFunctionWithComplexParams(
    'processRequest',
    [
      { name: 'endpoint' },
      { name: 'retries', defaultValue: t.numericLiteral(3) },
      { name: 'timeout', defaultValue: t.numericLiteral(5000) },
    ],
    'restOptions',
    [t.returnStatement(t.identifier('endpoint'))]
  );
  assert.strictEqual(complexFn.type, 'FunctionDeclaration');
  assert.strictEqual(complexFn.id.name, 'processRequest');
  assert.strictEqual(complexFn.params.length, 4);
  assert.strictEqual(complexFn.params[0].type, 'Identifier');
  assert.strictEqual(complexFn.params[0].name, 'endpoint');
  assert.strictEqual(complexFn.params[1].type, 'AssignmentPattern');
  assert.strictEqual(complexFn.params[1].left.name, 'retries');
  assert.strictEqual(complexFn.params[1].right.value, 3);
  assert.strictEqual(complexFn.params[2].type, 'AssignmentPattern');
  assert.strictEqual(complexFn.params[2].left.name, 'timeout');
  assert.strictEqual(complexFn.params[2].right.value, 5000);
  assert.strictEqual(complexFn.params[3].type, 'RestElement');
  assert.strictEqual(complexFn.params[3].argument.name, 'restOptions');

  // 7. types.cloneNode produces an independent equivalent copy of a FunctionDeclaration node
  const clonedFn = cloneFunctionDeclaration(fnNode);
  assert.notStrictEqual(clonedFn, fnNode, 'cloned FunctionDeclaration should have separate object identity');
  assert.notStrictEqual(clonedFn.id, fnNode.id, 'cloned id should have separate object identity');
  assert.notStrictEqual(clonedFn.body, fnNode.body, 'cloned body should have separate object identity');
  assert.strictEqual(clonedFn.type, 'FunctionDeclaration');
  assert.strictEqual(clonedFn.id.name, 'computeTotal');
  assert.strictEqual(t.isNodesEquivalent(clonedFn, fnNode), true);

  const clonedComplex = cloneFunctionDeclaration(complexFn);
  assert.notStrictEqual(clonedComplex, complexFn);
  assert.strictEqual(t.isNodesEquivalent(clonedComplex, complexFn), true);

  console.log('All contract assertions passed successfully.');
}

runContract().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

オリジンシーダー

匿名