Skip to content

Commit

Permalink
refactor(cloudflare): improve node compat + add tests (#3067)
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 authored Feb 5, 2025
1 parent ccfda71 commit c99b22f
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 8 deletions.
13 changes: 6 additions & 7 deletions src/presets/cloudflare/unenv/preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@ import type { Plugin } from "rollup";
import { fileURLToPath } from "mlly";
import { join } from "pathe";

export const cloudflareExternals = [
"cloudflare:email",
"cloudflare:sockets",
"cloudflare:workers",
"cloudflare:workflows",
] as const;

// Built-in APIs provided by workerd with nodejs compatibility
// https://github.com/cloudflare/workers-sdk/blob/main/packages/unenv-preset/src/preset.ts
export const nodeCompatModules = [
Expand Down Expand Up @@ -65,11 +58,17 @@ export const unenvCfPreset: Preset = {
sys: resolvePresetRuntime("util"),
"node:sys": resolvePresetRuntime("util"),
},
inject: {
"globalThis.Buffer": ["node:buffer", "Buffer"],
},
};

export const hybridNodePlugin: Plugin = {
name: "nitro:cloudflare:hybrid-node-compat",
resolveId(id) {
if (id.startsWith("cloudflare:")) {
return { id, external: true };
}
if (id.startsWith("#workerd/node:")) {
return { id: id.slice("#workerd/".length), external: true };
}
Expand Down
54 changes: 54 additions & 0 deletions test/fixture/routes/node-compat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import nodeAsyncHooks from "node:async_hooks";
import nodeCrypto from "node:crypto";

const nodeCompatTests = {
buffer: {
Buffer: () => {
const _Buffer = Buffer;
return _Buffer && !("__unenv__" in _Buffer);
},
"globalThis.Buffer": () => {
const _Buffer = globalThis.Buffer;
return _Buffer && !("__unenv__" in _Buffer);
},
},
crypto: {
createHash: () => {
return nodeCrypto
.createHash("sha256")
.update("hello")
.digest("hex")
.startsWith("2cf24");
},
},
async_hooks: {
AsyncLocalStorage: async () => {
if ("__unenv__" in nodeAsyncHooks.AsyncLocalStorage) {
return false;
}
const ctx = new nodeAsyncHooks.AsyncLocalStorage();
const rand = Math.random();
return ctx.run(rand, async () => {
await new Promise<void>((r) => r());
if (ctx.getStore() !== rand) {
return false;
}
return true;
});
},
},
};

export default eventHandler(async (event) => {
const results: Record<string, boolean> = {};
for (const [group, groupTests] of Object.entries(nodeCompatTests)) {
for (const [name, test] of Object.entries(groupTests)) {
results[`${group}:${name}`] = !!(await test());
}
}
return new Response(JSON.stringify(results, null, 2), {
headers: {
"Content-Type": "application/json",
},
});
});
2 changes: 1 addition & 1 deletion test/presets/cloudflare-module-legacy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { describe } from "vitest";

import { setupTest, testNitro } from "../tests";

describe("nitro:preset:cloudflare-module", async () => {
describe("nitro:preset:cloudflare-module-legacy", async () => {
const ctx = await setupTest("cloudflare-module-legacy", {});

testNitro(ctx, () => {
Expand Down
12 changes: 12 additions & 0 deletions test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -799,4 +799,16 @@ export function testNitro(
sqlts: "--",
});
});

it.skipIf(
["cloudflare-worker", "cloudflare-module-legacy", "vercel-edge"].includes(
ctx.preset
)
)("nodejs compatibility", async () => {
const { data, status } = await callHandler({ url: "/node-compat" });
expect(status).toBe(200);
for (const key in data) {
expect(data[key], key).toBe(true);
}
});
}

0 comments on commit c99b22f

Please sign in to comment.