fix(jsr): resolve require from source, not from tsup's banner
JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives
the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the
source had nothing to resolve, and one of them was unguarded: `@Html('file')` and
template mode died at boot on Deno with `ReferenceError: require is not defined`.
The two guarded sites were worse than the crash, because they answered confidently
and wrongly. `static` reported *"needs a filesystem and is unavailable on this
runtime (edge)"* while running on Deno, which has one; multipart reported busboy as
not installed while it sat in node_modules. Both blamed the runtime for a packaging
problem, and both named a runtime the reader was not on.
Route all ten call sites through one `nodeRequire`, which prefers the ambient
`require` — so the CJS build and the banner-carrying ESM build behave exactly as
before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`.
Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement:
every caller sits on a sync path a dynamic `import()` could not serve. It resolves
from `process.cwd()`, since a peer dependency like busboy belongs to the application,
not to a module served over https from a registry.
Where neither exists — workerd, where esbuild rewrites the call into its own throwing
stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has
no filesystem" story is finally the true one.
Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno
tests already did that; none of them touched a path that loads a Node builtin lazily,
which is how a package that died at boot kept a green suite.
Closes #69.
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
11 files changed
+145
-23
No files matched your search
+5
-4
@@ -9,6 +9,7 @@ import { acquireBody, type BodyReader } from './body';
|
|||||||
import type { RouteDef, HttpOptions } from './types';
|
import type { RouteDef, HttpOptions } from './types';
|
||||||
import type { StreamEncoder } from '../encoders';
|
import type { StreamEncoder } from '../encoders';
|
||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
|
import { nodeRequire } from '../node-require';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import.
|
* `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
|
* 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.
|
* 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
|
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
|
||||||
* `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`.
|
* 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 randomUUID: () => string = (() => {
|
||||||
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
|
||||||
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
|
||||||
return (require('node:crypto') as { randomUUID: () => string }).randomUUID;
|
|
||||||
})();
|
})();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+3
-4
@@ -11,6 +11,7 @@ import { mergeInjectedHeaders } from './headers';
|
|||||||
import { handle, correlateRequest, type HandleResult, type Preflight } from './core';
|
import { handle, correlateRequest, type HandleResult, type Preflight } from './core';
|
||||||
import type { BodyFailure, BodyReader } from './body';
|
import type { BodyFailure, BodyReader } from './body';
|
||||||
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
|
||||||
|
import { nodeRequire } from '../node-require';
|
||||||
|
|
||||||
interface HandlerConfig {
|
interface HandlerConfig {
|
||||||
routes: RouteDef[];
|
routes: RouteDef[];
|
||||||
@@ -44,10 +45,8 @@ export function createHttpServer(
|
|||||||
|
|
||||||
// Node http/https are loaded lazily so importing createApp stays edge/workerd-safe
|
// 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().
|
// (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 = nodeRequire<typeof import('http')>('http');
|
||||||
const nodeHttp = require('http') as typeof import('http');
|
const nodeHttps = nodeRequire<typeof import('https')>('https');
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
||||||
const nodeHttps = require('https') as typeof import('https');
|
|
||||||
|
|
||||||
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
|
||||||
const server: http.Server = (opts?.tls
|
const server: http.Server = (opts?.tls
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { channel } from '../channel';
|
import { channel } from '../channel';
|
||||||
import type { App } from '../app/types';
|
import type { App } from '../app/types';
|
||||||
import type { WsRequest, WsSocket } from './ws-core';
|
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
|
* 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;
|
if (platform) return platform;
|
||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
return nodeRequire<SocketCtor>('ws');
|
||||||
return require('ws') as SocketCtor;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+2
-2
@@ -3,14 +3,14 @@ import { channel } from '../channel';
|
|||||||
import type { Bus } from '../bus';
|
import type { Bus } from '../bus';
|
||||||
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
|
||||||
import type { WsRouteDef, MeshControl } from './types';
|
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. */
|
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
|
||||||
function loadWss(): any | null {
|
function loadWss(): any | null {
|
||||||
try {
|
try {
|
||||||
// `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket
|
// `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).
|
// 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 nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer;
|
||||||
return require('ws').WebSocketServer;
|
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,7 @@
|
|||||||
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
|
// src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency.
|
||||||
import { Readable } from 'stream';
|
import { Readable } from 'stream';
|
||||||
import { HttpError } from './signals';
|
import { HttpError } from './signals';
|
||||||
|
import { nodeRequire } from './node-require';
|
||||||
|
|
||||||
/** A single uploaded file part decoded from a multipart body. */
|
/** A single uploaded file part decoded from a multipart body. */
|
||||||
export interface UploadedFile {
|
export interface UploadedFile {
|
||||||
@@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm
|
|||||||
try {
|
try {
|
||||||
// `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is
|
// `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.
|
// 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 nodeRequire('busboy');
|
||||||
return require('busboy');
|
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// src/node-require.ts — one `require` that survives being published as source.
|
||||||
|
|
||||||
|
type Require = <T>(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<T>(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<T>(id);
|
||||||
|
}
|
||||||
+8
-9
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
import type { TransformerFn } from './metadata';
|
import type { TransformerFn } from './metadata';
|
||||||
import type { HtmlMeta } 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. */
|
/** Escape the five HTML-significant characters so interpolated data can't inject markup. */
|
||||||
export function escapeHtml(s: string): string {
|
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.
|
/** 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
|
* 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 {
|
function readViewFile(views: string | undefined, path: string): string {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
const nodePath = nodeRequire<typeof import('node:path')>('node:path');
|
||||||
const nodePath = require('node:path') as typeof import('node:path');
|
const fs = nodeRequire<typeof import('node:fs')>('node:fs');
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
||||||
const fs = require('node:fs') as typeof import('node:fs');
|
|
||||||
const base = views ?? process.cwd();
|
const base = views ?? process.cwd();
|
||||||
const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path);
|
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');
|
let nodePath: typeof import('node:path');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
fs = nodeRequire('node:fs');
|
||||||
fs = require('node:fs');
|
nodePath = nodeRequire('node:path');
|
||||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
||||||
nodePath = require('node:path');
|
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
|
'`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.',
|
||||||
|
|||||||
@@ -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(), '<h1>Dash</h1>');
|
||||||
|
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<string, string>; files: Record<string, { filename: string }> }) {
|
||||||
|
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();
|
||||||
|
});
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
served
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
<h1>Dash</h1>
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
<h1>Hi {{ name }}</h1>
|
||||||
Reference in new issue
Block a user