diff --git a/src/http/core.ts b/src/http/core.ts index 977dfdf..f0264fb 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -9,6 +9,7 @@ import { acquireBody, type BodyReader } from './body'; import type { RouteDef, HttpOptions } from './types'; import type { StreamEncoder } from '../encoders'; import type { Bus } from '../bus'; +import { nodeRequire } from '../node-require'; /** * `randomUUID`, from wherever this runtime keeps it. Resolved once, at import. @@ -23,15 +24,15 @@ import type { Bus } from '../bus'; * CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly * why that job is pinned to the floor rather than to the current release. * - * The fallback is reached only by a runtime that lacks the global, so workerd never evaluates the - * `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`. + * The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it. + * It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on + * every distribution of this package and not just the bundled ones. */ const randomUUID: () => string = (() => { const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto; if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!(); - // eslint-disable-next-line @typescript-eslint/no-require-imports - return (require('node:crypto') as { randomUUID: () => string }).randomUUID; + return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID; })(); /** diff --git a/src/http/server.ts b/src/http/server.ts index 32ad05e..6f9033d 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -11,6 +11,7 @@ import { mergeInjectedHeaders } from './headers'; import { handle, correlateRequest, type HandleResult, type Preflight } from './core'; import type { BodyFailure, BodyReader } from './body'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; +import { nodeRequire } from '../node-require'; interface HandlerConfig { routes: RouteDef[]; @@ -44,10 +45,8 @@ export function createHttpServer( // Node http/https are loaded lazily so importing createApp stays edge/workerd-safe // (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen(). - // eslint-disable-next-line @typescript-eslint/no-require-imports - const nodeHttp = require('http') as typeof import('http'); - // eslint-disable-next-line @typescript-eslint/no-require-imports - const nodeHttps = require('https') as typeof import('https'); + const nodeHttp = nodeRequire('http'); + const nodeHttps = nodeRequire('https'); // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) const server: http.Server = (opts?.tls diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index 8f9307e..1c0d8d8 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -1,6 +1,7 @@ import { channel } from '../channel'; import type { App } from '../app/types'; import type { WsRequest, WsSocket } from './ws-core'; +import { nodeRequire } from '../node-require'; /** * Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket @@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor { if (platform) return platform; - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('ws') as SocketCtor; + return nodeRequire('ws'); } /** diff --git a/src/http/ws.ts b/src/http/ws.ts index f738067..b22d684 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -3,14 +3,14 @@ import { channel } from '../channel'; import type { Bus } from '../bus'; import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import type { WsRouteDef, MeshControl } from './types'; +import { nodeRequire } from '../node-require'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ function loadWss(): any | null { try { // `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket // support don't fail. When absent this throws and we fall back to null (501 on upgrade). - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('ws').WebSocketServer; + return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer; } catch { return null; } diff --git a/src/multipart.ts b/src/multipart.ts index 3e03cab..d525388 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -1,6 +1,7 @@ // src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency. import { Readable } from 'stream'; import { HttpError } from './signals'; +import { nodeRequire } from './node-require'; /** A single uploaded file part decoded from a multipart body. */ export interface UploadedFile { @@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm try { // `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is // lazy-required and its absence surfaces as a clear 501 rather than a load-time crash. - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('busboy'); + return nodeRequire('busboy'); } catch { return null; } diff --git a/src/node-require.ts b/src/node-require.ts new file mode 100644 index 0000000..a9c7e27 --- /dev/null +++ b/src/node-require.ts @@ -0,0 +1,44 @@ +// src/node-require.ts — one `require` that survives being published as source. + +type Require = (id: string) => T; + +interface NodeProcess { + cwd?: () => string; + getBuiltinModule?: (id: string) => unknown; +} + +let cached: Require | null | undefined; + +function resolveRequire(): Require | undefined { + // The CJS build has a native one, and tsup gives the ESM build one through a `createRequire` + // banner (tsup.config.ts). Both npm paths stop here. + if (typeof require === 'function') return require as Require; + + // JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`. + // `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all + // three do it *synchronously* — which is the whole requirement, since every caller here sits on + // a sync path that a dynamic `import()` could not serve. + const proc = (globalThis as { process?: NodeProcess }).process; + const nodeModule = proc?.getBuiltinModule?.('node:module') as + { createRequire?: (from: string) => Require } | undefined; + if (!nodeModule?.createRequire || !proc?.cwd) return undefined; + + // Resolve from the application's directory rather than from this file: served from JSR this + // module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer + // dependency such as `busboy` is installed in the app that asked for it. + return nodeModule.createRequire(`${proc.cwd()}/`); +} + +/** + * Loads a Node builtin or an installed package, synchronously. + * + * Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely + * out of reach. Every caller already guards for that and reports it in its own terms; what they + * must not do is report it when the module is in fact reachable, which is what a bare `require` + * caused on JSR by failing with `ReferenceError` before any of them was consulted. + */ +export function nodeRequire(id: string): T { + if (cached === undefined) cached = resolveRequire() ?? null; + if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`); + return cached(id); +} diff --git a/src/views.ts b/src/views.ts index 210ab9c..ee07a8b 100644 --- a/src/views.ts +++ b/src/views.ts @@ -3,6 +3,7 @@ import type { TransformerFn } from './metadata'; import type { HtmlMeta } from './metadata'; +import { nodeRequire } from './node-require'; /** Escape the five HTML-significant characters so interpolated data can't inject markup. */ export function escapeHtml(s: string): string { @@ -58,12 +59,12 @@ export interface ViewsContext { /** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is. * node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe - * (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */ + * (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. + * Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no + * filesystem should hear about it here rather than at the first request. */ function readViewFile(views: string | undefined, path: string): string { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const nodePath = require('node:path') as typeof import('node:path'); - // eslint-disable-next-line @typescript-eslint/no-require-imports - const fs = require('node:fs') as typeof import('node:fs'); + const nodePath = nodeRequire('node:path'); + const fs = nodeRequire('node:fs'); const base = views ?? process.cwd(); const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path); @@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver { let nodePath: typeof import('node:path'); try { - // eslint-disable-next-line @typescript-eslint/no-require-imports - fs = require('node:fs'); - // eslint-disable-next-line @typescript-eslint/no-require-imports - nodePath = require('node:path'); + fs = nodeRequire('node:fs'); + nodePath = nodeRequire('node:path'); } catch { throw new Error( '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', diff --git a/test/deno/views.test.ts b/test/deno/views.test.ts new file mode 100644 index 0000000..4aff1f4 --- /dev/null +++ b/test/deno/views.test.ts @@ -0,0 +1,76 @@ +// `@Html` and `static` under the real Deno runtime, importing `src/` the way JSR serves it. +// +// This is the shape the JSR package actually ships: no bundler ran, so tsup's `createRequire` +// banner (tsup.config.ts) never existed and the lazy `require('node:fs')` in `src/views.ts` has +// nothing to resolve. Every other Deno test here imports `src/` too, but none of them touches a +// path that loads a Node builtin lazily — which is how a package that dies at boot on Deno kept a +// green suite. Run with: npm run test:deno +import 'npm:reflect-metadata'; +import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; +import { createApp, Route, Get, Html, Module } from '../../src/index.ts'; + +// Committed fixtures rather than a temp dir, so the suite keeps running without `--allow-write`. +const dir = 'test/fixtures/views'; + +@Route('/') +class Views { + @Get('/dash') @Html('dash.html') dash() {} + @Get('/user') @Html('user.html', { template: true }) user() { + return { name: 'Deno' }; + } +} + +@Module({ mountpoint: '/', controllers: [Views] }) +class M {} + +Deno.test("@Html file mode reads the file — the require path resolves without tsup's banner", async () => { + const app = createApp({ modules: [M], views: dir }); + const res = await app.fetch(new Request('http://x/dash')); + assertEquals(res.status, 200); + assertEquals(await res.text(), '

Dash

'); + await app.close(); +}); + +Deno.test('@Html template mode renders', async () => { + const app = createApp({ modules: [M], views: dir }); + const res = await app.fetch(new Request('http://x/user')); + assertStringIncludes(await res.text(), 'Hi Deno'); + await app.close(); +}); + +// Deno has a filesystem, so `static` must not report the runtime as the reason for anything. +Deno.test('static: true builds a resolver instead of blaming the runtime', async () => { + const app = createApp({ modules: [], static: dir }); + const res = await app.fetch(new Request('http://x/asset.txt')); + assertEquals(res.status, 200); + assertEquals(await res.text(), 'served'); + await app.close(); +}); + +// The other half of the shim: `node:fs` above comes from `process.getBuiltinModule`, but `busboy` +// is an npm package and has to be resolved from the application's own `node_modules`. On JSR that +// failed as a `ReferenceError` under the catch that reports "busboy not installed" — the one +// diagnosis guaranteed to send a reader to reinstall a package they already have. +Deno.test('multipart resolves the busboy peer dependency instead of reporting it missing', async () => { + const { createApp: create, Route: R, Post, Module: Mod, body } = await import('../../src/index.ts'); + + @R('/') + class Upload { + @Post('/up') up(@body() b: { fields: Record; files: Record }) { + return { name: b.fields.name, filename: b.files.file.filename }; + } + } + + @Mod({ mountpoint: '/', controllers: [Upload] }) + class UploadMod {} + + const app = create({ modules: [UploadMod] }); + const form = new FormData(); + form.set('name', 'joe'); + form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }), 'p.png'); + + const res = await app.fetch(new Request('http://x/up', { method: 'POST', body: form })); + assertEquals(res.status, 200); + assertEquals(await res.json(), { name: 'joe', filename: 'p.png' }); + await app.close(); +}); diff --git a/test/fixtures/views/asset.txt b/test/fixtures/views/asset.txt new file mode 100644 index 0000000..0d3564a --- /dev/null +++ b/test/fixtures/views/asset.txt @@ -0,0 +1 @@ +served \ No newline at end of file diff --git a/test/fixtures/views/dash.html b/test/fixtures/views/dash.html new file mode 100644 index 0000000..1288d45 --- /dev/null +++ b/test/fixtures/views/dash.html @@ -0,0 +1 @@ +

Dash

\ No newline at end of file diff --git a/test/fixtures/views/user.html b/test/fixtures/views/user.html new file mode 100644 index 0000000..d3e1277 --- /dev/null +++ b/test/fixtures/views/user.html @@ -0,0 +1 @@ +

Hi {{ name }}

\ No newline at end of file