Something went wrong. Try again.
Monorepo for the nibling.run platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165// Builtin registry: the guest-side analogue of an import map.// `node:*` specifiers and bare builtin names resolve here (the kernel classifies the// specifier; this table supplies the module object). Unknown ids throw// ERR_UNKNOWN_BUILTIN_MODULE, matching Node's require of an unknown builtin.// Page-level import maps cannot reach the worker realm — this registry is the// runtime's equivalent mechanism for guest code.import type { RequireContext } from "./modules";import { makeModule } from "./module";import { makeVm } from "./vm";import { makeOs } from "./os";import { isBuiltinId, type BuiltinId } from "../shared/builtin-ids";import { assert, strict } from "./assert";import { makeAsyncHooks } from "./async_hooks";import { cluster } from "./cluster";import type { Console } from "./console";import * as diagnosticsChannel from "./diagnostics_channel";import { dgram } from "./dgram";import { makeDns } from "./dns";import { makePerfHooks } from "./perf_hooks";import { v8 } from "./v8";import { crypto } from "./crypto";import { EventEmitter } from "./events";import { makeFs } from "./fs";import { Blob, Buffer, File, INSPECT_MAX_BYTES, constants as bufferConstants, isAscii, isUtf8, kMaxLength, kStringMaxLength, resolveObjectURL, transcode,} from "./buffer";import { Stream, streamConsumers, streamWeb } from "./stream";import { StringDecoder } from "./string_decoder";import { qs } from "./querystring";import { http2 } from "./http2";import { https } from "./https";import { inspector } from "./inspector";import { inspectorPromises } from "./inspector-promises";import { net } from "./net";import { makePath } from "./path";import { timersPromises } from "./timers";import { makeReadline } from "./readline/index";import { sea } from "./sea";import { makeWasi } from "./wasi";import { makeTest } from "./test";import { makeTestReporters } from "./test-reporters";import { tls } from "./tls";import { traceEvents } from "./trace_events";import { tty } from "./tty";import { makeUrl } from "./url";import { makeUtil } from "./util";import { types as utilTypes } from "./util/types";import { makeZlib } from "./zlib";
export interface BuiltinContext extends RequireContext {}
/** One factory per builtin id; the shared id list is the key set, so a builtin the * kernel resolves always has a module here. Each module is built once per worker. */const FACTORIES = { assert: () => assert, "assert/strict": () => strict, async_hooks: (ctx) => makeAsyncHooks((msg, type, code) => ctx.process.emitWarning(msg, type, code)), buffer: () => ({ Buffer, Blob, File, kMaxLength, kStringMaxLength, INSPECT_MAX_BYTES, constants: bufferConstants, atob, btoa, isUtf8, isAscii, resolveObjectURL, transcode, }), child_process: (ctx) => ctx.childProcess.module, cluster: () => cluster, // The global console this runtime installs (main.ts), not a fresh instance: Node's // require("console") is the same object as the global. console: () => globalThis.console as unknown as Console & { Console: typeof Console }, crypto: () => crypto, dgram: () => dgram, diagnostics_channel: () => diagnosticsChannel, dns: (ctx) => makeDns(ctx.loop), "dns/promises": (ctx) => (loadBuiltin("dns", ctx) as ReturnType<typeof makeDns>).promises, events: () => EventEmitter, fs: (ctx) => makeFs(ctx), "fs/promises": (ctx) => (loadBuiltin("fs", ctx) as ReturnType<typeof makeFs>).promises, http: (ctx) => ctx.http, http2: () => http2, https: () => https, inspector: () => inspector, "inspector/promises": () => inspectorPromises, module: (ctx) => makeModule(ctx), net: () => net, os: (ctx) => makeOs(() => ctx.process.env), path: (ctx) => makePath(() => ctx.process.cwd(), () => ctx.process.env), "path/posix": (ctx) => loadBuiltin("path", ctx), "path/win32": (ctx) => (loadBuiltin("path", ctx) as ReturnType<typeof makePath>).win32, perf_hooks: (ctx) => makePerfHooks(ctx.loop), process: (ctx) => ctx.process, querystring: () => qs, readline: (ctx) => makeReadline({ process: () => ctx.process, timers: () => ctx.timers }), "readline/promises": (ctx) => (loadBuiltin("readline", ctx) as ReturnType<typeof makeReadline>).promises, sea: () => sea, stream: () => Stream, "stream/consumers": () => streamConsumers, "stream/promises": (ctx) => (loadBuiltin("stream", ctx) as typeof Stream).promises, "stream/web": () => streamWeb, string_decoder: () => ({ StringDecoder }), // mock.timers patches globalThis, node:timers' own module object and // node:timers/promises' own module object independently (none of the three alias // each other — see mock_timers.ts's TimerHooks); t.assert.snapshot/fileSnapshot read // and write through the kernel's own fs/path, like Node's require('fs')/require( // 'path'). Both reach past test.ts into this file's own loadBuiltin/globalThis // through closures, rather than test.ts importing loadBuiltin itself and creating a // builtins.ts <-> test.ts import cycle. test: (ctx) => makeTest(ctx.process, { timers: { globalTarget: globalThis as unknown as Record<string, unknown>, nodeTimers: () => loadBuiltin("timers", ctx) as Record<string, unknown>, nodeTimersPromises: () => loadBuiltin("timers/promises", ctx) as ReturnType<typeof timersPromises>, abortSignal: () => (typeof AbortSignal === "undefined" ? undefined : (AbortSignal as unknown as { timeout: unknown })), }, fs: { readFileSync: (path, encoding) => (loadBuiltin("fs", ctx) as ReturnType<typeof makeFs>).readFileSync(path, encoding) as string, writeFileSync: (path, data, encoding) => (loadBuiltin("fs", ctx) as ReturnType<typeof makeFs>).writeFileSync(path, data, encoding), mkdirSync: (path, options) => void (loadBuiltin("fs", ctx) as ReturnType<typeof makeFs>).mkdirSync(path, options), dirname: (path) => (loadBuiltin("path", ctx) as ReturnType<typeof makePath>).dirname(path), }, run: { proc: ctx.process, globSync: (patterns, cwd) => (loadBuiltin("fs", ctx) as ReturnType<typeof makeFs>).globSync(patterns, { cwd, exclude: (name: string) => name === "node_modules" }) as string[], // run({isolation:'none'})'s file loader reuses the exact mechanism a guest's // own dynamic import() is rewritten to call (src/kernel/transform.ts): the // test file resolves and loads through the real kernel resolver, CJS and ESM // alike, with no separate code path for "a file run() loads" vs "a file a // guest module imports". importFile: (cwd, absolutePath) => (globalThis as unknown as Record<symbol, { importFrom: (from: string) => (specifier: string) => Promise<unknown> }>)[ Symbol.for("nib.runtime") ]!.importFrom(`${cwd}/`)(absolutePath), }, }), "test/reporters": () => makeTestReporters(), timers: (ctx) => ({ ...ctx.timers, promises: loadBuiltin("timers/promises", ctx) }), "timers/promises": (ctx) => timersPromises(ctx.timers), tls: () => tls, trace_events: () => traceEvents, tty: () => tty, url: (ctx) => makeUrl( (p) => (loadBuiltin("path", ctx) as ReturnType<typeof makePath>).resolve(p), (msg, type, code) => ctx.process.emitWarning(msg, type, code), ), util: (ctx) => makeUtil(ctx.process, () => Boolean((ctx.workerThreads.module as { isMainThread?: boolean }).isMainThread)), "util/types": () => utilTypes, v8: () => v8, vm: (ctx) => makeVm(ctx), wasi: (ctx) => { ctx.process.emitWarning("WASI is an experimental feature and might change at any time", "ExperimentalWarning"); return makeWasi(() => loadBuiltin("fs", ctx) as ReturnType<typeof makeFs>, ctx.process); }, worker_threads: (ctx) => ctx.workerThreads.module, zlib: (ctx) => makeZlib(ctx.loop),} satisfies Record<BuiltinId, (ctx: BuiltinContext) => unknown>;
const loaded = new Map<BuiltinId, unknown>();
export function loadBuiltin(id: string, ctx: BuiltinContext): unknown { if (!isBuiltinId(id)) { throw Object.assign(new Error(`No such built-in module: node:${id}`), { code: "ERR_UNKNOWN_BUILTIN_MODULE" }); } if (!loaded.has(id)) loaded.set(id, FACTORIES[id](ctx)); return loaded.get(id);}