Cómo solucionar que la IA rompa el runtime de Cloudflare Workers
Los agentes de IA importan módulos integrados de Node.js como fs, crypto y path en Cloudflare Workers, lo que provoca errores de ejecución porque el runtime de Workers no es Node.js.
El agente escribe código que funciona localmente bajo Node.js pero falla al implementar o ejecutar en Cloudflare Workers porque el runtime de Workers es un aislado V8, no Node.js.
El síntoma
El agente importa módulos integrados de Node.js o paquetes npm que internamente requieren APIs de Node.js.
// worker.ts — WRONGimport { createHash } from "crypto"; // Node built-in — not availableimport { readFileSync } from "fs"; // Node built-in — not availableimport { resolve } from "path"; // Node built-in — not availableimport { IncomingMessage } from "http"; // Node built-in — not available
export default { async fetch(request: Request, env: Env) { const hash = createHash("sha256").update("data").digest("hex"); return new Response(hash); },};// Error at runtime: Cannot read properties of undefined (reading 'createHash')Por qué ocurre
La mayoría de los datos de entrenamiento de agentes están orientados a Node.js. El modelo sabe que crypto, fs y path funcionan para hash, acceso a archivos y manipulación de rutas, por lo que recurre a ellos. No distingue el runtime de Workers de Node.js a menos que se le indique explícitamente.
Cómo identificarlo
import ... from "crypto"/"fs"/"path"/"http"/"stream"en archivos del Worker.wrangler devfunciona perowrangler deploylanza una advertencia de empaquetado sobre módulos de Node.js no resueltos.- La sección de indicadores de compatibilidad de Wrangler en
wrangler.tomlfalta o usa una fecha anterior a2022-11-30. - Dependencias que internamente usan
require("node:...")sin un shim de compatibilidad para Workers.
Cómo solucionarlo
Utilice APIs web estándar — están disponibles de forma nativa en Workers.
// worker.ts — CORRECTexport default { async fetch(request: Request, env: Env) { // Web Crypto API — standard, available in Workers const encoder = new TextEncoder(); const data = encoder.encode("data"); const hashBuffer = await crypto.subtle.digest("SHA-256", data); const hashArray = Array.from(new Uint8Array(hashBuffer)); const hash = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); return new Response(hash); },};# wrangler.toml — enable Node.js compat shims for packages that need themcompatibility_date = "2024-09-23"compatibility_flags = ["nodejs_compat"][ ] No imports from "crypto", "fs", "path", "http", "stream", "os", "buffer" (use node: prefix + nodejs_compat flag if unavoidable)[ ] Use crypto.subtle for hashing/signing (Web Crypto API)[ ] Use env bindings (KV, R2, D1) instead of fs for storage[ ] Set compatibility_date to a recent date in wrangler.toml[ ] Add nodejs_compat flag only for third-party packages that require it[ ] Run "wrangler deploy --dry-run" to catch bundling errors before deployingInstrucción de corrección
This code imports Node.js built-in modules (crypto, fs, path, http) that arenot available in the Cloudflare Workers runtime. Rewrite it using Web StandardAPIs: crypto.subtle for hashing/encryption, the Fetch API for HTTP, andCloudflare bindings (KV, R2, D1) for storage. If a third-party dependencyrequires Node.js APIs, add nodejs_compat to compatibility_flags in wrangler.tomland note that in a comment.Prueba
# Dry-run deploy to catch Node.js module errorswrangler deploy --dry-run --outdir dist 2>&1 | grep -i "error\|unresolved\|node:" && echo "FAIL" || echo "OK"
# Check for raw Node built-in importsgrep -rn '^import.*from "(crypto|fs|path|http|stream|os)"' src/ \ && echo "FAIL: Node.js built-in import found" || echo "OK"