Supported JS APIs
Golem’s JavaScript runtime uses wasm-rquickjs . This reference follows its current API inventory. It provides Web APIs and Node.js-compatible modules, not a complete browser or Node.js runtime. Read the limitations below before choosing a library.
Feature Flags
The runtime generated by wasm-rquickjs has optional features. These are runtime build options, not settings in an agent definition. Availability depends on the runtime included in your SDK build.
| Feature | Default | Description |
|---|---|---|
logging | ✅ On | Routes the console API through host logging |
http | ✅ On | Enables fetch and the HTTP client APIs |
sqlite | ❌ Off | Enables node:sqlite with embedded SQLite |
timezone | ✅ On | Enables IANA timezones for Intl.DateTimeFormat |
typescript-runtime | ❌ Off | Strips TypeScript types when loading runtime modules |
typescript-transform-runtime | ❌ Off | Also transforms TypeScript syntax such as enums and runtime namespaces |
Runtime TypeScript support is separate from compiling a TypeScript agent with the SDK’s normal build tools.
WIT–JS Type Mappings
| WIT Type | JS Type | Notes |
|---|---|---|
char | string | — |
string | string | — |
s8, u8, s16, u16, s32, u32 | number | — |
s64, u64 | bigint | — |
f32, f64 | number | — |
option<T> | T | undefined | Nested options encoded differently |
list<T> | T[] | — |
result<T, E> | { tag: "ok", val: T } | { tag: "err", val: E } | — |
tuple<A, B, C> | Array | — |
enum { a, b, c } | "a" | "b" | "c" | Matches WIT case names |
flags { a, b, c } | { a: boolean, b: boolean, c: boolean } | Keys are camelCase |
record { .. } | Object | Field names are camelCase |
variant { .. } | { tag: "x", val: X } | val is undefined for unit cases |
An imported function with a result<T, E> return type returns T on success and throws E on failure, rather than returning the tagged object in the table. An asynchronous import rejects with the same error value. Structured errors retain their fields; string coercion renders their payload as JSON.
Mapping Limitations
- Maximum of 26 function parameters
- Anonymous interface exports/imports are not supported
- Imported individual functions into the world are not supported (only whole interfaces)
Available JavaScript APIs
Web Platform APIs
Console
Depends on wasi:logging (if logging feature is enabled), otherwise core WASI.
assert,clear,count,countReset,debug,dir,dirXml,error,group,groupCollapsed,groupEnd,info,log,table,time,timeEnd,timeLog,trace,warn
HTTP (fetch)
Requires http feature flag. Depends on wasi:http.
fetch,Headers,Request,Response,FormData,Blob,File
URL
URL(includingcreateObjectURL,revokeObjectURL)URLSearchParams
Streams
Implemented via web-streams-polyfill .
ByteLengthQueuingStrategy,CountQueuingStrategyReadableStream,ReadableStreamDefaultReader,ReadableStreamBYOBReader,ReadableStreamDefaultController,ReadableByteStreamController,ReadableStreamBYOBRequestWritableStream,WritableStreamDefaultControllerTransformStream,TransformStreamDefaultController
Timers
setTimeout,clearTimeout,setInterval,clearInterval,setImmediate
Abort Controller
AbortController,AbortSignal,DOMException
Encoding
TextEncoder,TextDecoder,TextDecoderStream,TextEncoderStream
Messaging
MessageChannel,MessagePort
Events
Event,EventTarget,CustomEvent
Intl (Internationalization)
Minimal en-US implementation — all locale inputs are accepted but resolved to en-US. When the timezone feature is enabled (default), DateTimeFormat supports all ~590 IANA timezones via chrono-tz.
Intl.DateTimeFormat—format(),formatToParts(),resolvedOptions(),supportedLocalesOf()Intl.NumberFormat—format(),formatToParts(),resolvedOptions(),supportedLocalesOf()Intl.Collator—compare(),resolvedOptions(),supportedLocalesOf()Intl.PluralRules—select(),selectRange(),resolvedOptions(),supportedLocalesOf()Intl.getCanonicalLocales(),Intl.supportedValuesOf()
Crypto (global)
crypto.randomUUID,crypto.getRandomValues
Performance (global)
performance.now()uses a monotonic clock and is not affected by wall-clock adjustments.performance.timeOriginis the deployment wall-clock origin paired with that timeline.- The global object is shared with
node:perf_hooks.
Structured Clone
Via ungap/structured-clone :
structuredClone
Node.js-Compatible Modules
⚠️ Golem does not support
node:net,node:dgramandnode:dns. These modules use WASI sockets, which the worker executor refuses by default: every TCP connect, UDP send, bind and DNS lookup fails. Only an operator can turn WASI sockets on, with the executor settingagent_sockets.enabled. For HTTP, usefetchor thenode:httpclient, which do not use WASI sockets.
node:assert
ok,equal,notEqual,strictEqual,notStrictEqualdeepEqual,notDeepEqual,deepStrictEqual,notDeepStrictEqual,partialDeepStrictEqualthrows,doesNotThrow,rejects,doesNotRejectifError,match,doesNotMatch,failAssertionError,CallTrackerstrict— strict mode variant
node:async_hooks
AsyncLocalStorage—run,exit,getStore,enterWith,disable,snapshot,bindAsyncResource—runInAsyncScope,asyncId,triggerAsyncId,bindcreateHook— stub (returns enable/disable no-ops)executionAsyncId,triggerAsyncId,executionAsyncResource— stubs
Context propagates through Promise.prototype.then, catch, and finally, and through setTimeout and setInterval.
⚠️ Limitation: Context is not propagated across
awaitboundaries.
node:buffer
Buffer,Blob,File,SlowBufferresolveObjectURL,isAscii,isUtf8INSPECT_MAX_BYTES,kMaxLength,kStringMaxLength,constants
node:child_process
The runtime cannot create operating-system subprocesses. A limited compatibility adapter runs JavaScript targets invoked through process.execPath inline, with separate argument, environment, and working-directory views. It also recognizes npm’s literal sh -c form for plain Node commands and executable Node shebang files.
Other executables, unsupported shells and shell syntax, and unsupported shebangs fail with ENOSYS. Inline execution does not create a fresh JavaScript runtime or a subprocess.
ChildProcess,exec,execFile,fork,spawn,execSync,execFileSync,spawnSync
node:cluster (stub)
Clustering not supported in WASM.
isPrimary,isMaster,isWorker,fork,disconnect,setupPrimary
node:constants
Merged constants from os.constants, fs.constants, and crypto.constants (signal numbers, errno values, file flags, etc.)
node:crypto
- Hashing:
createHash,createHmac,hash,getHashes - Ciphers:
createCipheriv,createDecipheriv,getCiphers- Supported ciphers:
aes-128/256-cbc,aes-128/256-ctr,aes-128/256-gcm,aes-128/192/256-wrap,id-aes128/192/256-wrap,id-aes128/192/256-wrap-pad,des-ede3-cbc,des3-wrap,chacha20-poly1305
- Supported ciphers:
- Signing:
createSign,createVerify(Ed25519, ECDSA with P-256, P-384, secp256k1) - Keys:
createPublicKey,createPrivateKey,createSecretKey,KeyObject,generateKeyPairSync,generateKeyPair - ECDH:
createECDH,ECDH,diffieHellman,getCurves - Certificate:
Certificate(verifySpkac,exportPublicKey,exportChallenge) - Random:
randomBytes,randomFillSync,randomFill,randomInt,randomUUID,pseudoRandomBytes,prng,rng - KDF:
pbkdf2,pbkdf2Sync,scrypt,scryptSync,hkdf,hkdfSync - Primes:
generatePrime,generatePrimeSync,checkPrime,checkPrimeSync - Other:
timingSafeEqual,getFips,setFips,secureHeapUsed
node:dgram (not supported)
UDP datagram sockets built on WASI sockets. Golem does not support this module: the worker executor refuses WASI sockets by default, so binds and sends fail.
dgram.createSocket(type[, listener])—udp4orudp6socket.bind,socket.send,socket.sendto,socket.connect,socket.disconnect,socket.closesocket.address(),socket.remoteAddress()socket.setTTL,socket.setRecvBufferSize/getRecvBufferSize,socket.setSendBufferSize/getSendBufferSizesocket.ref()/socket.unref()— no-op- Events:
message,listening,close,error,connect
⚠️ Multicast operations throw
ENOSYS.
node:diagnostics_channel
channel,subscribe,unsubscribe,hasSubscribers,tracingChannelChannel—subscribe,unsubscribe,publish,bindStore,unbindStore,runStores,hasSubscribers,nameTracingChannel—subscribe,unsubscribe,hasSubscribers,traceSync,tracePromise,traceCallback- Built-in HTTP diagnostics channels:
http.client.request.created,http.client.request.start,http.client.request.error,http.client.response.finish
node:dns (not supported)
DNS resolution via WASI sockets. Golem does not support this module: the worker executor refuses WASI sockets by default, so lookups fail.
lookup,lookupService,resolve,resolve4,resolve6resolveAny,resolveCname,resolveCaa,resolveMx,resolveNaptr,resolveNs,resolvePtr,resolveSoa,resolveSrv,resolveTxt,resolveTlsareverse,setServers,getServers,setDefaultResultOrder,getDefaultResultOrderResolverclasspromises— promise-based API- Error constants:
NODATA,FORMERR,SERVFAIL,NOTFOUND,NOTIMP,REFUSED,BADQUERY,BADNAME,BADFAMILY,BADRESP,CONNREFUSED,TIMEOUT,EOF,FILE,NOMEM,DESTRUCTION,BADSTR,BADFLAGS,NONAME,BADHINTS,NOTINITIALIZED,LOADIPHLPAPI,ADDRGETNETWORKPARAMS,CANCELLED,ADDRCONFIG,V4MAPPED,ALL
node:domain
Deprecated error-handling domains.
domain.create()/domain.createDomain(),domain.active,domain._stackDomainclass (extendsEventEmitter):run,add,remove,bind,intercept,enter,exit,dispose,members,parentprocess.domain— reflects active domain- Error decoration:
error.domain,error.domainEmitter,error.domainBound,error.domainThrown - EventEmitter integration and propagation through
process.nextTick,setTimeout, andsetInterval
⚠️ Only synchronous errors and explicitly bound callbacks are captured. There is no general asynchronous context propagation through
async_hooks.
node:events
EventEmitter—on,once,off,addListener,removeListener,removeAllListeners,emit,listenerCount,eventNames,listeners,rawListeners,prependListener,prependOnceListener,setMaxListeners,getMaxListeners- Static:
once,on,getEventListeners,getMaxListeners,setMaxListeners,addAbortListener,errorMonitor,captureRejections Event,EventTarget,CustomEvent
node:fs
Comprehensive filesystem API on WASI filesystem.
Symbolic links persist in the filesystem. Targets must be relative; absolute targets fail with EINVAL without creating a link. Windows local development requires Developer Mode or equivalent symlink privileges. This restriction does not affect non-link filesystem operations.
- Sync:
readFileSync,writeFileSync,appendFileSync,openSync,closeSync,readSync,writeSync,ftruncateSync,fsyncSync,fdatasyncSync,statSync,lstatSync,fstatSync,statfsSync,readdirSync,accessSync,existsSync,realpathSync,truncateSync,copyFileSync,linkSync,symlinkSync,readlinkSync,chmodSync,fchmodSync,lchmodSync,chownSync,fchownSync,lchownSync,utimesSync,futimesSync,lutimesSync,unlinkSync,renameSync,mkdirSync,rmdirSync,rmSync,mkdtempSync,opendirSync,readvSync,writevSync,cpSync - Async (callback):
readFile,writeFile,appendFile,open,close,read,write,stat,lstat,fstat,statfs,ftruncate,fsync,fdatasync,readdir,access,exists,realpath,truncate,copyFile,link,symlink,readlink,chmod,fchmod,lchmod,chown,fchown,lchown,utimes,futimes,lutimes,unlink,rename,mkdir,rmdir,rm,mkdtemp,opendir,watch,watchFile,unwatchFile,readv,writev,cp,openAsBlob - Streams:
createReadStream,createWriteStream - Classes:
Stats,Dirent,Dir,FSWatcher,StatWatcher,ReadStream,WriteStream - Constants:
F_OK,R_OK,W_OK,X_OK,O_RDONLY,O_WRONLY,O_RDWR,O_CREAT,O_EXCL,O_TRUNC,O_APPEND, and more
node:fs/promises
FileHandle,open,readFile,writeFile,appendFile,unlink,rename,mkdir,rmdir,rm,stat,lstat,readdir,opendir,access,realpath,truncate,copyFile,link,symlink,readlink,chmod,lchmod,chown,lchown,utimes,lutimes,mkdtemp,cp,watch,statfs,constants
node:http / node:https
Requires http feature flag. Client uses wasi:http (TLS transparent). Socket-backed servers use WASI sockets and are not supported; to serve HTTP with an http.createServer request listener, mount the server as a custom HTTP router with nodeHttpHandler from @golemcloud/golem-ts-sdk/http-router.
http.request,http.get,http.METHODS,http.STATUS_CODES,http.maxHeaderSize,http.validateHeaderName,http.validateHeaderValuehttp.Agent,http.globalAgenthttp.OutgoingMessage,http.ClientRequest,http.IncomingMessagehttps.request,https.gethttp.createServer,http.Server,http.ServerResponsehttp.ServerResponse.writeContinue,writeProcessing,writeEarlyHints- Server-side
IncomingMessagewithmethod,url,headers,rawHeaders,httpVersion,socket, etc. node:_http_common—_checkIsHttpToken,_checkInvalidHeaderChar- Supports: keep-alive, chunked transfer encoding, content-length bodies, sequential pipelining, idle connection cleanup
⚠️ Not yet supported: HTTP Upgrade, CONNECT tunnels, client-side 1xx events, server-side timeout enforcement,
https.createServer(), clientlookup/autoSelectFamilyoptions, and custom per-requestcreateConnectiontransports. Custom AgentcreateConnectionhooks are ignored with a warning: they cannot route or isolate traffic. All outbound requests use the host HTTP client.
node:http2 (stub)
connect,createServer,createSecureServer,Http2ServerRequest,Http2ServerResponse
node:inspector (stub)
No V8 inspector in WASM.
Session,open,close,url,waitForDebugger,console,Network
node:module
require,require.resolve,createRequire,builtinModules,isBuiltin,runMain,_nodeModulePathsstripTypeScriptTypes— strip and transform modes, when runtime TypeScript support is enabled
Package resolution supports package.json main, exports, and imports, including subpaths and wildcard patterns. CommonJS resolution recognizes golem, node, require, module-sync, and default conditions. ES module resolution uses import instead of require.
With runtime TypeScript support, .mts files are ES modules and .cts files are CommonJS. .ts files follow the nearest package type and Node-style syntax classification. ES module imports require explicit file extensions. The runtime does not type-check, read tsconfig.json, strip types inside node_modules, or support .tsx. Syntax that needs transformation, such as enums and runtime namespaces, requires typescript-transform-runtime.
node:net (not supported)
TCP sockets and servers on WASI sockets. Golem does not support this module: the worker executor refuses WASI sockets by default, so connects and listens fail.
net.createServer,net.createConnection,net.connectnet.isIP,net.isIPv4,net.isIPv6net.getDefaultAutoSelectFamily/net.setDefaultAutoSelectFamily— stubsnet.Socket(extendsstream.Duplex):connect,write,end,destroy,resetAndDestroy,setTimeout,setNoDelay,setKeepAlive,address,ref,unref; properties:remoteAddress,remotePort,remoteFamily,localAddress,localPort,localFamily,bytesRead,bytesWritten,connecting,pending,readyState; events:connect,ready,data,end,close,error,timeout,drain,lookupnet.Server(extendsEventEmitter):listen,close,address,getConnections,ref,unref; properties:listening,maxConnections; events:listening,connection,close,error,dropnet.BlockList,net.SocketAddress,net.Stream
⚠️ Not supported: IPC/Unix domain sockets, Happy Eyeballs /
autoSelectFamily,clusterintegration.
node:os
arch,platform,type,release,version,machine,hostname,homedir,tmpdir,endiannesscpus,loadavg,freemem,totalmem,uptime,availableParallelismnetworkInterfaces,userInfo,getPriority,setPriorityEOL,devNull,constants
node:path
sep,delimiter,basename,dirname,extname,isAbsolute,join,normalize,relative,resolve,parse,format,matchesGlob,toNamespacedPath,posix
node:perf_hooks
performance—now(),timeOrigin,mark(),measure(),getEntries(),getEntriesByName(),getEntriesByType(),clearMarks(),clearMeasures(),toJSON()PerformanceEntry,PerformanceObservermonitorEventLoopDelay,createHistogram,constants
node:process
- Properties:
argv,argv0,env,pid,ppid,platform('wasi'),arch('wasm32'),version,versions,config,features,execArgv,execPath,exitCode,stdout,stderr - Methods:
exit,cwd,nextTick,hrtime,hrtime.bigint,uptime,cpuUsage,memoryUsage,kill,abort,emitWarning - User/Group:
getuid,getgid,geteuid,getegid,getgroups,setuid,setgid - Extends
EventEmitter— supportson('uncaughtException'),on('unhandledRejection'), etc.
node:punycode
decode,encode,toASCII,toUnicode,ucs2,version
node:querystring
stringify/encode,parse/decode,escape,unescape,unescapeBuffer
node:readline
createInterface,Interface,clearLine,clearScreenDown,cursorTo,moveCursor,emitKeypressEventsreadline/promises— promise-based API
node:repl (stub)
start,REPLServer,Recoverable,builtinModules
node:sqlite
Requires sqlite feature flag. Synchronous API with embedded SQLite engine.
DatabaseSync—prepare,exec,close,open,isOpen,isTransaction,createSession,applyChangeset,enableLoadExtension,function,aggregate,backupStatementSync—run,get,all,iterate,columns,setReadBigInts,setAllowBareNamedParameters,sourceSQL,expandedSQLSession—changeset,patchset,close- Constants:
SQLITE_CHANGESET_OMIT,SQLITE_CHANGESET_REPLACE,SQLITE_CHANGESET_ABORT
⚠️
loadExtension()throws — native extensions cannot be loaded in WASM.
node:stream
Readable(withfrom,fromWeb,toWeb,wrap,map,filter,flatMap,take,drop,toArray,forEach,reduce,some,every,find)Writable,Duplex,Transform,PassThrough,Streampipeline,finished,compose,duplexPair,addAbortSignalgetDefaultHighWaterMark,setDefaultHighWaterMark,isDisturbed,destroystream/consumers—arrayBuffer,blob,buffer,json,textstream/promises— promise-basedpipelineandfinished
node:string_decoder
StringDecoder
node:test
Built-in test runner.
test,describe/suite,it,before,after,beforeEach,afterEachmock— function mockingrun— programmatic test execution
node:timers
setTimeout,setInterval,setImmediate,clearTimeout,clearIntervaltimers/promises— promise-basedsetTimeout,setInterval,setImmediate
node:tls (stub)
TLS is handled transparently by the WASI-HTTP layer.
SecureContext,TLSSocket,Server,connect,createServer,createSecureContext,checkServerIdentity,getCiphers,rootCertificatesDEFAULT_MIN_VERSION,DEFAULT_MAX_VERSION,DEFAULT_ECDH_CURVE
node:trace_events
createTracing({ categories })— creates aTracinghandleTracing#enable()/Tracing#disable(),Tracing#enabled,Tracing#categoriesgetEnabledCategories()
⚠️ No native trace sink — API-surface compatibility only.
node:tty
isatty,ReadStream,WriteStream
node:url
URL,URLSearchParamsparse,resolve,format(legacy)domainToASCII,domainToUnicodefileURLToPath,pathToFileURL,urlToHttpOptions
node:util
format,inspect,deprecate,debugLog,log- Type checks:
isArray,isBoolean,isNull,isNullOrUndefined,isNumber,isString,isSymbol,isUndefined,isRegExp,isObject,isDate,isError,isFunction,isPrimitive,isBuffer promisify,callbackifyparseEnv,styleText,getCallSite,getCallSites,toUSVString,_extendTextEncoder,TextDecoder
node:v8
getHeapStatistics,getHeapSpaceStatistics,getHeapSnapshot,getHeapCodeStatisticssetFlagsFromString,writeHeapSnapshot,takeCoverage,stopCoverageserialize,deserialize,Serializer,Deserializer,DefaultSerializer,DefaultDeserializer
node:vm
runInNewContext,runInContext,runInThisContext,createContext,isContext,compileFunctionScript,createScriptSourceTextModule(experimental — limitedexport const/export let/export varsupport)
These are synchronous compatibility contexts within one JavaScript runtime. They are not a security sandbox: code shares the component’s capabilities and filesystem access. For asynchronous jobs in fresh runtimes, see Fresh-runtime execution.
node:worker_threads (stub)
Workers not supported in single-threaded WASM.
isMainThread,parentPort,workerData,threadId,resourceLimitsWorker,BroadcastChannel,MessagePort,MessageChannelmarkAsUntransferable,moveMessagePortToContext,receiveMessageOnPortgetEnvironmentData,setEnvironmentData
node:zlib
- Classes:
Deflate,Inflate,Gzip,Gunzip,DeflateRaw,InflateRaw,Unzip,BrotliCompress,BrotliDecompress - Factory:
createGzip,createGunzip,createDeflate,createInflate,createDeflateRaw,createInflateRaw,createUnzip,createBrotliCompress,createBrotliDecompress - Async:
gzip,gunzip,deflate,inflate,deflateRaw,inflateRaw,unzip,brotliCompress,brotliDecompress - Sync:
gzipSync,gunzipSync,deflateSync,inflateSync,deflateRawSync,inflateRawSync,unzipSync,brotliCompressSync,brotliDecompressSync crc32,constants,codes
Internal / Compatibility Modules
internal/url—isURLinternal/http—kOutHeaderssymbolbase64-js—byteLength,toByteArray,fromByteArrayieee754—read,write
Fresh-runtime execution
The wasm-rquickjs:execution module runs JavaScript asynchronously in a fresh runtime:
startJavaScript(options)returns livestdoutandstderrreadable streams, aresultpromise resolving to{ value, overflowed }, andcancel().runJavaScript(options)collects output and resolves to{ value, overflowed, stdout, stderr }.
Pass exactly one of entry (a module path) or source (an asynchronous function body). Inline source supports await and return, but not static import or export declarations. Results cross the runtime boundary through structured clone.
Options include cwd, argv, env, timeoutMs, maxBytes, and overflow. The environment is an explicit allowlist and defaults to empty; jobs do not inherit environment variables. Output is bounded to 1 MiB per stream by default, with a maximum of 64 MiB. Overflow rejects the job by default; overflow: "truncate" keeps bounded output and sets overflowed instead. TypeScript entry files and inline language: "typescript" require runtime TypeScript support.
Each job has fresh globals, timers, process state, and module caches. It is not a security sandbox: jobs share the enclosing component’s host capabilities and filesystem. cwd controls path resolution, not filesystem access.
Cancellation is cooperative and cannot interrupt a tight loop already running on the same thread. Use a positive timeoutMs for a best-effort execution budget, not an exact deadline. An unfinished job must be cancelled or given a timeout before the enclosing invocation can finish. At most eight jobs can be active, and jobs cannot start nested execution jobs.
See the upstream execution API for the complete options and execution limits.
Built-in Language Features (from QuickJS)
These come from QuickJS itself and are available globally without any import:
Globals: parseInt, parseFloat, isNaN, isFinite, quickMicrotask, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, unescape, Infinity, NaN, undefined
Full built-in objects with all standard methods:
Object, Function, Error, Generator, Iterator, Array, Number, Boolean, String, Symbol, Map, Set, WeakMap, WeakSet, GeneratorFunction, Math, Reflect, RegExp, JSON, Promise, AsyncFunction, AsyncIterator, AsyncGeneratorFunction, AsyncGenerator, Date, BigInt, ArrayBuffer, SharedArrayBuffer
Typed Arrays: Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, BigInt64Array, BigUint64Array, Float32Array, Float64Array, Float16Array
Other: DataView, Atomics, Performance, WeakRef, FinalizationRegistry, Callsite, Proxy