CodeSampleX

Exemplo

@vitest/mocker 4.1.11: automock.automockModule

Amostra verificada para npm @vitest/mocker 4.1.11: automock.automockModule. O contrato rodou em node 22 · linux debian/x64 · docker e passou.

sha256:c83d0b54b71ded5bac9880b6701b42a42448306edac3647ee7160846e3a1cc63

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-01

Caso

HOW
Objetivo
verify @vitest/mocker/automock.automockModule in pkg:npm/%40vitest/mocker@4.1.11
Pacotes
Símbolos
  • @vitest/mocker/automock.automockModule
Ambiente
node 22.23.2
Criado
2026-09-01T17:01:09Z

Contrato

  1. @vitest/mocker/automock exports automockModule as a function
  2. automockModule transforms named function declarations into mocked exports via globalThis['__vitest_mocker__'].mockObject
  3. automockModule transforms named variable declarations (const/let) into mocked properties
  4. automockModule transforms export specifiers (export { local as exported }) into mocked bindings
  5. automockModule transforms default exports with mockType autospy into __vitest_default and re-exports as default
  6. automockModule supports custom globalThisAccessor option injected into globalThis
  7. automockModule wraps parser error with file id and preserves cause when options.id is provided
  8. automockModule rethrows parser error directly when options.id is omitted

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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 @vitest/mocker/automock.automockModule in pkg:npm/%40vitest/mocker@4.1.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40vitest/mocker@4.1.11
Demonstrate these symbols/APIs:
  - @vitest/mocker/automock.automockModule
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:9942f1531a2c25c267f51b5c78ac373f7986b4abfa7db1312aa4114c313511be","constraints":{"executionContext":"node"},"contract":["@vitest/mocker/automock exports automockModule as a function","automockModule transforms named function declarations into mocked exports via globalThis['__vitest_mocker__'].mockObject","automockModule transforms named variable declarations (const/let) into mocked properties","automockModule transforms export specifiers (export { local as exported }) into mocked bindings","automockModule transforms default exports with mockType autospy into __vitest_default and re-exports as default","automockModule supports custom globalThisAccessor option injected into globalThis","automockModule wraps parser error with file id and preserves cause when options.id is provided","automockModule rethrows parser error directly when options.id is omitted"],"goal":"verify @vitest/mocker/automock.automockModule in pkg:npm/%40vitest/mocker@4.1.11","kind":"HOW","packages":["pkg:npm/%40vitest/mocker@4.1.11"],"schemaVersion":1,"symbols":["@vitest/mocker/automock.automockModule"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40vitest/mocker@4.1.11"],"schemaVersion":1,"subject":"pkg:npm/%40vitest/mocker@4.1.11","symbols":["@vitest/mocker/automock.automockModule"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-vitest-mocker-automock",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-vitest-mocker-automock",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@vitest/mocker": "4.1.11"
      }
    },
    "node_modules/@jridgewell/sourcemap-codec": {
      "version": "1.6.0",
      "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
      "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
      "license": "MIT"
    },
    "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/@vitest/mocker": {
      "version": "4.1.11",
      "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
      "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
      "license": "MIT",
      "dependencies": {
        "@vitest/spy": "4.1.11",
        "estree-walker": "^3.0.3",
        "magic-string": "^0.30.21"
      },
      "funding": {
        "url": "https://opencollective.com/vitest"
      },
      "peerDependencies": {
        "msw": "^2.4.9",
        "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
      },
      "peerDependenciesMeta": {
        "msw": {
          "optional": true
        },
        "vite": {
          "optional": true
        }
      }
    },
    "node_modules/@vitest/spy": {
      "version": "4.1.11",
      "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
      "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
      "license": "MIT",
      "funding": {
        "url": "https://opencollective.com/vitest"
      }
    },
    "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"
      }
    },
    "node_modules/magic-string": {
      "version": "0.30.21",
      "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
      "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
      "license": "MIT",
      "dependencies": {
        "@jridgewell/sourcemap-codec": "^1.5.5"
      }
    }
  }
}
package.json
{
  "name": "sample-vitest-mocker-automock",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification of @vitest/mocker/automock.automockModule in @vitest/mocker@4.1.11",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "@vitest/mocker": "4.1.11"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify @vitest/mocker/automock.automockModule in pkg:npm/%40vitest/mocker@4.1.11",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40vitest/mocker@4.1.11"
  ],
  "symbols": [
    "@vitest/mocker/automock.automockModule"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
/**
 * Clean-room helper wrapping @vitest/mocker automock functionality.
 */

/**
 * Automock an ECMAScript module's source code by parsing and wrapping exports.
 *
 * @param {string} code - Module source code
 * @param {'automock'|'autospy'} mockType - Mock strategy type ('automock' or 'autospy')
 * @param {Function} parse - ESTree parser returning AST
 * @param {object} [options] - Options such as globalThisAccessor or id
 * @returns {Promise<import('magic-string').default>} Transformed MagicString output
 */
async function automock(code, mockType, parse, options) {
  const { automockModule } = await import('@vitest/mocker/automock');
  return automockModule(code, mockType, parse, options);
}

module.exports = {
  automock
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { automockModule } from '@vitest/mocker/automock';

const require = createRequire(import.meta.url);
const { automock } = require('../src/index.js');

// 1. Export type verification
assert.equal(typeof automockModule, 'function', 'automockModule must be exported as a function');
assert.equal(typeof automock, 'function', 'src/index.js automock helper must be a function');

// 2. Named function declaration transformation
{
  const code = 'export function calculateTotal(price, tax) { return price + tax; }';
  const parse = () => ({
    body: [
      {
        type: 'ExportNamedDeclaration',
        start: 0,
        end: code.length,
        declaration: {
          type: 'FunctionDeclaration',
          start: 7,
          end: code.length,
          id: { type: 'Identifier', name: 'calculateTotal' }
        }
      }
    ]
  });

  const ms = automockModule(code, 'automock', parse);
  const output = ms.toString();

  assert.ok(output.includes('function calculateTotal(price, tax)'), 'Original function body is preserved');
  assert.ok(output.includes('["calculateTotal"]: calculateTotal'), 'Function is attached to current es module object');
  assert.ok(output.includes('globalThis["__vitest_mocker__"].mockObject('), 'Default globalThisAccessor is "__vitest_mocker__"');
  assert.ok(output.includes('mockObject(__vitest_current_es_module__, "automock")'), 'mockType automock is passed to mockObject');
  assert.ok(output.includes('__vitest_mocked_0__ as calculateTotal'), 'Mocked property is re-exported under original name');
}

// 3. Named variable declarations (const / let) transformation
{
  const code = 'export const API_URL = "https://example.com/api";';
  const parse = () => ({
    body: [
      {
        type: 'ExportNamedDeclaration',
        start: 0,
        end: code.length,
        declaration: {
          type: 'VariableDeclaration',
          start: 7,
          end: code.length,
          kind: 'const',
          declarations: [
            {
              type: 'VariableDeclarator',
              start: 13,
              end: code.length,
              id: { type: 'Identifier', name: 'API_URL' }
            }
          ]
        }
      }
    ]
  });

  const ms = automockModule(code, 'automock', parse);
  const output = ms.toString();

  assert.ok(output.includes('const API_URL = "https://example.com/api";'), 'Variable declaration is preserved');
  assert.ok(output.includes('["API_URL"]: API_URL'), 'Variable is included in module object');
  assert.ok(output.includes('__vitest_mocked_0__ as API_URL'), 'Variable is re-exported');
}

// 4. Export specifiers transformation (export { a as b })
{
  const code = 'const internalFn = () => 42;\nexport { internalFn as publicFn };';
  const parse = () => ({
    body: [
      {
        type: 'VariableDeclaration',
        start: 0,
        end: 28
      },
      {
        type: 'ExportNamedDeclaration',
        start: 29,
        end: code.length,
        specifiers: [
          {
            type: 'ExportSpecifier',
            local: { type: 'Identifier', name: 'internalFn' },
            exported: { type: 'Identifier', name: 'publicFn' }
          }
        ]
      }
    ]
  });

  const ms = automockModule(code, 'automock', parse);
  const output = ms.toString();

  assert.ok(output.includes('["internalFn"]: internalFn'), 'Local identifier is assigned in module object');
  assert.ok(output.includes('__vitest_mocked_0__ as publicFn'), 'Exported alias is preserved in export list');
}

// 5. Default export transformation with mockType "autospy"
{
  const code = 'export default class UserService {}';
  const parse = () => ({
    body: [
      {
        type: 'ExportDefaultDeclaration',
        start: 0,
        end: code.length,
        declaration: {
          type: 'ClassDeclaration',
          start: 15,
          end: code.length,
          id: { type: 'Identifier', name: 'UserService' }
        }
      }
    ]
  });

  const ms = automockModule(code, 'autospy', parse);
  const output = ms.toString();

  assert.ok(output.includes('const __vitest_default = class UserService {}'), 'Default export rewritten to const __vitest_default');
  assert.ok(output.includes('["__vitest_default"]: __vitest_default'), 'Default export included in module object');
  assert.ok(output.includes('mockObject(__vitest_current_es_module__, "autospy")'), 'Mock strategy autospy is passed');
  assert.ok(output.includes('__vitest_mocked_0__ as default'), 'Exported as default');
}

// 6. Custom globalThisAccessor option support
{
  const code = 'export function ping() { return "pong"; }';
  const parse = () => ({
    body: [
      {
        type: 'ExportNamedDeclaration',
        start: 0,
        end: code.length,
        declaration: {
          type: 'FunctionDeclaration',
          start: 7,
          end: code.length,
          id: { type: 'Identifier', name: 'ping' }
        }
      }
    ]
  });

  const customAccessor = 'Symbol.for("custom_mocker")';
  const ms = automockModule(code, 'automock', parse, { globalThisAccessor: customAccessor });
  const output = ms.toString();

  assert.ok(output.includes(`globalThis[${customAccessor}].mockObject`), 'Custom globalThisAccessor is injected into output');
}

// 7. Error handling: wraps parse error with file ID when options.id is provided
{
  const code = 'invalid { syntax';
  const syntaxError = new SyntaxError('Unexpected token');
  const parse = () => { throw syntaxError; };

  assert.throws(
    () => automockModule(code, 'automock', parse, { id: '/app/service.js' }),
    (err) => {
      assert.equal(err.message, 'failed to parse /app/service.js', 'Error message includes file ID');
      assert.equal(err.cause, syntaxError, 'Error cause preserves original parser exception');
      return true;
    },
    'Should wrap parse error with id and cause'
  );
}

// 8. Error handling: rethrows parser error directly when options.id is omitted
{
  const code = 'invalid { syntax';
  const customError = new Error('Custom parser failure');
  const parse = () => { throw customError; };

  assert.throws(
    () => automockModule(code, 'automock', parse),
    (err) => err === customError,
    'Should rethrow original error when id is not specified'
  );
}

// 9. Helper wrapper in src/index.js verification
{
  const code = 'export function helper() { return true; }';
  const parse = () => ({
    body: [
      {
        type: 'ExportNamedDeclaration',
        start: 0,
        end: code.length,
        declaration: {
          type: 'FunctionDeclaration',
          start: 7,
          end: code.length,
          id: { type: 'Identifier', name: 'helper' }
        }
      }
    ]
  });

  const ms = await automock(code, 'automock', parse);
  assert.ok(ms.toString().includes('__vitest_mocked_0__ as helper'), 'automock helper transforms module exports');
}

console.log('Contract tests passed successfully.');

Seeder de origem

anônimo