CodeSampleX

Exemplo

enhanced-resolve 5.24.5

Amostra verificada para npm enhanced-resolve 5.24.5. O contrato rodou em node 22 · linux debian/x64 · docker e passou: enhancedResolve provides synchronous…

sha256:c79d4bd6dd381bab532e823220542ae5a68d4e4a97dbaae116e26fb9af11c1a6

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-19

Caso

HOW
Objetivo
verify pkg:npm/enhanced-resolve@5.24.5
Pacotes
Ambiente
node 22.23.2
Criado
2026-09-18T21:01:41Z

Contrato

  1. enhancedResolve provides synchronous and promise-based path resolution
  2. createSyncResolver creates synchronous resolvers with custom options such as extensions and aliases
  3. createAsyncResolver creates promise-based asynchronous resolvers with custom options
  4. resolver resolves extensionless file paths when matching extensions are configured
  5. resolver redirects module request paths using configured aliases
  6. resolveSync and resolveAsync helper functions resolve file paths relative to context directory
  7. resolver throws or rejects with an error when target cannot be resolved
  8. resolver resolves installed dependencies from node_modules

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 pkg:npm/enhanced-resolve@5.24.5
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/enhanced-resolve@5.24.5

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:b4185cd6419ca326b45df8efd748cc5faff7a6e66c24c8b3932308243d062279","contract":["enhancedResolve provides synchronous and promise-based path resolution","createSyncResolver creates synchronous resolvers with custom options such as extensions and aliases","createAsyncResolver creates promise-based asynchronous resolvers with custom options","resolver resolves extensionless file paths when matching extensions are configured","resolver redirects module request paths using configured aliases","resolveSync and resolveAsync helper functions resolve file paths relative to context directory","resolver throws or rejects with an error when target cannot be resolved","resolver resolves installed dependencies from node_modules"],"goal":"verify pkg:npm/enhanced-resolve@5.24.5","kind":"HOW","packages":["pkg:npm/enhanced-resolve@5.24.5"],"schemaVersion":1},"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/enhanced-resolve@5.24.5"],"schemaVersion":1,"subject":"pkg:npm/enhanced-resolve@5.24.5","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-enhanced-resolve",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-enhanced-resolve",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "enhanced-resolve": "5.24.5"
      }
    },
    "node_modules/enhanced-resolve": {
      "version": "5.24.5",
      "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.24.5.tgz",
      "integrity": "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A==",
      "license": "MIT",
      "dependencies": {
        "graceful-fs": "^4.2.4",
        "tapable": "^2.3.3"
      },
      "engines": {
        "node": ">=10.13.0"
      }
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "node_modules/tapable": {
      "version": "2.3.3",
      "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz",
      "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==",
      "license": "MIT",
      "engines": {
        "node": ">=6"
      },
      "funding": {
        "type": "opencollective",
        "url": "https://opencollective.com/webpack"
      }
    }
  }
}
package.json
{
  "name": "sample-enhanced-resolve",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for enhanced-resolve@5.24.5",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "enhanced-resolve": "5.24.5"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/enhanced-resolve@5.24.5",
  "kind": "HOW",
  "packages": [
    "pkg:npm/enhanced-resolve@5.24.5"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

const enhancedResolve = require('enhanced-resolve');

/**
 * Creates a synchronous resolver with the given options.
 *
 * @param {object} [options={}] - Options for enhanced-resolve (extensions, alias, modules, etc.).
 * @returns {(contextPath: string, request: string) => string} Resolver function.
 */
function createSyncResolver(options = {}) {
  return enhancedResolve.create.sync(options);
}

/**
 * Creates a Promise-based asynchronous resolver with the given options.
 *
 * @param {object} [options={}] - Options for enhanced-resolve.
 * @returns {(contextPath: string, request: string) => Promise<string>} Resolver function.
 */
function createAsyncResolver(options = {}) {
  const resolver = enhancedResolve.create(options);
  return function (contextPath, request) {
    return new Promise((resolve, reject) => {
      resolver({}, contextPath, request, {}, (err, result) => {
        if (err) {
          reject(err);
        } else {
          resolve(result);
        }
      });
    });
  };
}

/**
 * Synchronously resolves a request relative to a base directory.
 *
 * @param {string} contextPath - Base directory path.
 * @param {string} request - Module name or file path to resolve.
 * @param {object} [options={}] - Resolver options.
 * @returns {string} Absolute resolved file path.
 */
function resolveSync(contextPath, request, options = {}) {
  const resolver = createSyncResolver(options);
  return resolver(contextPath, request);
}

/**
 * Asynchronously resolves a request relative to a base directory returning a Promise.
 *
 * @param {string} contextPath - Base directory path.
 * @param {string} request - Module name or file path to resolve.
 * @param {object} [options={}] - Resolver options.
 * @returns {Promise<string>} Resolves with the absolute resolved file path.
 */
async function resolveAsync(contextPath, request, options = {}) {
  const resolver = createAsyncResolver(options);
  return resolver(contextPath, request);
}

module.exports = {
  enhancedResolve,
  createSyncResolver,
  createAsyncResolver,
  resolveSync,
  resolveAsync
};
test/contract.mjs
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootDir = path.resolve(__dirname, '..');

const {
  enhancedResolve,
  createSyncResolver,
  createAsyncResolver,
  resolveSync,
  resolveAsync
} = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof enhancedResolve, 'function', 'enhancedResolve must be a function');
  assert.equal(typeof enhancedResolve.sync, 'function', 'enhancedResolve.sync must be a function');
  assert.equal(typeof enhancedResolve.promise, 'function', 'enhancedResolve.promise must be a function');
  assert.equal(typeof enhancedResolve.create, 'function', 'enhancedResolve.create must be a function');
  assert.equal(typeof enhancedResolve.create.sync, 'function', 'enhancedResolve.create.sync must be a function');
  assert.equal(typeof createSyncResolver, 'function', 'createSyncResolver must be a function');
  assert.equal(typeof createAsyncResolver, 'function', 'createAsyncResolver must be a function');
  assert.equal(typeof resolveSync, 'function', 'resolveSync must be a function');
  assert.equal(typeof resolveAsync, 'function', 'resolveAsync must be a function');

  // 2. Direct synchronous resolution with enhancedResolve.sync
  const pkgPathSync = enhancedResolve.sync(rootDir, './package.json');
  assert.ok(typeof pkgPathSync === 'string' && pkgPathSync.endsWith('package.json'), 'enhancedResolve.sync should resolve package.json');

  // 3. Direct promise resolution with enhancedResolve.promise
  const pkgPathPromise = await enhancedResolve.promise(rootDir, './package.json');
  assert.ok(typeof pkgPathPromise === 'string' && pkgPathPromise.endsWith('package.json'), 'enhancedResolve.promise should resolve package.json');

  // 4. Extension auto-resolving with createSyncResolver
  const extResolver = createSyncResolver({
    extensions: ['.json', '.js', '.mjs']
  });
  const resolvedWithoutExt = extResolver(rootDir, './package');
  assert.ok(typeof resolvedWithoutExt === 'string' && resolvedWithoutExt.endsWith('package.json'), 'extResolver should resolve ./package to package.json');

  // 5. Alias mapping with createSyncResolver
  const aliasResolver = createSyncResolver({
    alias: {
      '@pkg': path.resolve(rootDir, 'package.json')
    }
  });
  const resolvedAlias = aliasResolver(rootDir, '@pkg');
  assert.ok(typeof resolvedAlias === 'string' && resolvedAlias.endsWith('package.json'), 'aliasResolver should resolve @pkg alias');

  // 6. Asynchronous resolution with createAsyncResolver
  const asyncExtResolver = createAsyncResolver({
    extensions: ['.json', '.js', '.mjs']
  });
  const asyncResolved = await asyncExtResolver(rootDir, './package');
  assert.ok(typeof asyncResolved === 'string' && asyncResolved.endsWith('package.json'), 'asyncExtResolver should resolve ./package');

  // 7. resolveSync and resolveAsync helper functions
  const helperSyncRes = resolveSync(rootDir, './package.json');
  assert.ok(typeof helperSyncRes === 'string' && helperSyncRes.endsWith('package.json'), 'resolveSync helper should resolve package.json');

  const helperAsyncRes = await resolveAsync(rootDir, './package.json');
  assert.ok(typeof helperAsyncRes === 'string' && helperAsyncRes.endsWith('package.json'), 'resolveAsync helper should resolve package.json');

  // 8. Error handling on nonexistent files
  assert.throws(
    () => {
      resolveSync(rootDir, './non_existent_file_xyz.ext');
    },
    {
      name: 'Error',
      message: /Can't resolve '\.\/non_existent_file_xyz\.ext'/
    },
    'resolveSync should throw for nonexistent target'
  );

  await assert.rejects(
    async () => {
      await resolveAsync(rootDir, './non_existent_file_xyz.ext');
    },
    {
      name: 'Error',
      message: /Can't resolve '\.\/non_existent_file_xyz\.ext'/
    },
    'resolveAsync should reject for nonexistent target'
  );

  // 9. Resolving installed package from node_modules
  const tapableResolved = resolveSync(rootDir, 'tapable');
  assert.ok(typeof tapableResolved === 'string' && tapableResolved.includes('tapable'), 'should resolve installed tapable package');

  console.log('All enhanced-resolve contract tests passed successfully.');
}

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

Seeder de origem

anônimo