-
Notifications
You must be signed in to change notification settings - Fork 518
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add experimental
deno-server
preset (#592)
Co-authored-by: Pooya Parsa <pooya@pi0.io>
- Loading branch information
Showing
12 changed files
with
298 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
import { builtinModules } from "node:module"; | ||
import { isAbsolute, resolve } from "pathe"; | ||
import MagicString from "magic-string"; | ||
import { findStaticImports } from "mlly"; | ||
import inject from "@rollup/plugin-inject"; | ||
import { defineNitroPreset } from "../preset"; | ||
import { writeFile } from "../utils"; | ||
import { ImportMetaRe } from "../rollup/plugins/import-meta"; | ||
|
||
export const denoServer = defineNitroPreset({ | ||
extends: "node-server", | ||
entry: "#internal/nitro/entries/deno-server", | ||
commands: { | ||
preview: "deno task --config ./deno.json start", | ||
}, | ||
rollupConfig: { | ||
output: { | ||
hoistTransitiveImports: false, | ||
}, | ||
plugins: [ | ||
inject({ | ||
modules: { | ||
process: "process", | ||
global: "global", | ||
Buffer: ["buffer", "Buffer"], | ||
setTimeout: ["timers", "setTimeout"], | ||
clearTimeout: ["timers", "clearTimeout"], | ||
setInterval: ["timers", "setInterval"], | ||
clearInterval: ["timers", "clearInterval"], | ||
setImmediate: ["timers", "setImmediate"], | ||
clearImmediate: ["timers", "clearImmediate"], | ||
}, | ||
}), | ||
{ | ||
name: "rollup-plugin-node-deno", | ||
resolveId(id) { | ||
id = id.replace("node:", ""); | ||
if (builtinModules.includes(id)) { | ||
return { | ||
id: `node:${id}`, | ||
moduleSideEffects: false, | ||
external: true, | ||
}; | ||
} | ||
if (isHTTPImport(id)) { | ||
return { | ||
id, | ||
external: true, | ||
}; | ||
} | ||
}, | ||
renderChunk(code) { | ||
const s = new MagicString(code); | ||
const imports = findStaticImports(code); | ||
for (const i of imports) { | ||
if ( | ||
!i.specifier.startsWith(".") && | ||
!isAbsolute(i.specifier) && | ||
!isHTTPImport(i.specifier) && | ||
!i.specifier.startsWith("npm:") | ||
) { | ||
const specifier = i.specifier.replace("node:", ""); | ||
s.replace( | ||
i.code, | ||
i.code.replace( | ||
new RegExp(`(?<quote>['"])${i.specifier}\\k<quote>`), | ||
JSON.stringify( | ||
builtinModules.includes(specifier) | ||
? "node:" + specifier | ||
: "npm:" + specifier | ||
) | ||
) | ||
); | ||
} | ||
} | ||
if (s.hasChanged()) { | ||
return { | ||
code: s.toString(), | ||
map: s.generateMap({ includeContent: true }), | ||
}; | ||
} | ||
}, | ||
}, | ||
{ | ||
name: "inject-process", | ||
renderChunk: { | ||
order: "post", | ||
handler(code, chunk) { | ||
if ( | ||
!chunk.isEntry && | ||
(!ImportMetaRe.test(code) || code.includes("ROLLUP_NO_REPLACE")) | ||
) { | ||
return; | ||
} | ||
|
||
const s = new MagicString(code); | ||
s.prepend("import process from 'node:process';"); | ||
|
||
return { | ||
code: s.toString(), | ||
map: s.generateMap({ includeContent: true }), | ||
}; | ||
}, | ||
}, | ||
}, | ||
], | ||
}, | ||
hooks: { | ||
async compiled(nitro) { | ||
// https://deno.com/manual@v1.34.3/getting_started/configuration_file | ||
const denoJSON = { | ||
tasks: { | ||
start: | ||
"deno run --unstable --allow-net --allow-read --allow-env ./server/index.mjs", | ||
}, | ||
}; | ||
await writeFile( | ||
resolve(nitro.options.output.dir, "deno.json"), | ||
JSON.stringify(denoJSON, null, 2) | ||
); | ||
}, | ||
}, | ||
}); | ||
|
||
const HTTP_IMPORT_RE = /^(https?:)?\/\//; | ||
|
||
function isHTTPImport(id: string) { | ||
return HTTP_IMPORT_RE.test(id); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
import "#internal/nitro/virtual/polyfill"; | ||
import destr from "destr"; | ||
import { nitroApp } from "../app"; | ||
import { useRuntimeConfig } from "#internal/nitro"; | ||
|
||
// @ts-expect-error unknown global Deno | ||
if (Deno.env.get("DEBUG")) { | ||
addEventListener("unhandledrejection", (event) => | ||
console.error("[nitro] [dev] [unhandledRejection]", event.reason) | ||
); | ||
addEventListener("error", (event) => | ||
console.error("[nitro] [dev] [uncaughtException]", event.error) | ||
); | ||
} else { | ||
addEventListener("unhandledrejection", (err) => | ||
console.error("[nitro] [production] [unhandledRejection] " + err) | ||
); | ||
addEventListener("error", (event) => | ||
console.error("[nitro] [production] [uncaughtException] " + event.error) | ||
); | ||
} | ||
|
||
// @ts-expect-error unknown global Deno | ||
// https://deno.land/api@v1.34.3?s=Deno.serve&unstable= | ||
Deno.serve( | ||
{ | ||
// @ts-expect-error unknown global Deno | ||
key: Deno.env.get("NITRO_SSL_KEY"), | ||
// @ts-expect-error unknown global Deno | ||
cert: Deno.env.get("NITRO_SSL_CERT"), | ||
// @ts-expect-error unknown global Deno | ||
port: destr(Deno.env.get("NITRO_PORT") || Deno.env.get("PORT")) || 3000, | ||
// @ts-expect-error unknown global Deno | ||
hostname: Deno.env.get("NITRO_HOST") || Deno.env.get("HOST"), | ||
onListen: (opts) => { | ||
const baseURL = (useRuntimeConfig().app.baseURL || "").replace(/\/$/, ""); | ||
const url = `${opts.hostname}:${opts.port}${baseURL}`; | ||
console.log(`Listening ${url}`); | ||
}, | ||
}, | ||
handler | ||
); | ||
|
||
async function handler(request: Request) { | ||
const url = new URL(request.url); | ||
|
||
// https://deno.land/api?s=Body | ||
let body; | ||
if (request.body) { | ||
body = await request.arrayBuffer(); | ||
} | ||
|
||
const r = await nitroApp.localCall({ | ||
url: url.pathname + url.search, | ||
host: url.hostname, | ||
protocol: url.protocol, | ||
headers: Object.fromEntries(request.headers.entries()), | ||
method: request.method, | ||
redirect: request.redirect, | ||
body, | ||
}); | ||
|
||
// TODO: fix in runtime/static | ||
const responseBody = r.status === 304 ? null : r.body; | ||
return new Response(responseBody, { | ||
// @ts-ignore TODO: Should be HeadersInit instead of string[][] | ||
headers: normalizeOutgoingHeaders(r.headers), | ||
status: r.status, | ||
statusText: r.statusText, | ||
}); | ||
} | ||
|
||
function normalizeOutgoingHeaders( | ||
headers: Record<string, string | string[] | undefined> | ||
) { | ||
return Object.entries(headers).map(([k, v]) => [ | ||
k, | ||
Array.isArray(v) ? v.join(",") : v, | ||
]); | ||
} | ||
|
||
export default {}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { resolve } from "pathe"; | ||
import { describe, it, expect } from "vitest"; | ||
import { execa, execaCommandSync } from "execa"; | ||
import { getRandomPort, waitForPort } from "get-port-please"; | ||
import { setupTest, testNitro } from "../tests"; | ||
|
||
const hasDeno = | ||
execaCommandSync("deno --version", { stdio: "ignore", reject: false }) | ||
.exitCode === 0; | ||
|
||
describe.runIf(hasDeno)("nitro:preset:deno-server", async () => { | ||
const ctx = await setupTest("deno-server"); | ||
testNitro(ctx, async () => { | ||
const port = await getRandomPort(); | ||
const p = execa( | ||
"deno", | ||
["task", "--config", resolve(ctx.outDir, "deno.json"), "start"], | ||
{ | ||
stdio: "inherit", | ||
env: { | ||
PORT: String(port), | ||
}, | ||
} | ||
); | ||
ctx.server = { | ||
url: `http://127.0.0.1:${port}`, | ||
close: () => p.kill(), | ||
} as any; | ||
await waitForPort(port, { delay: 1000, retries: 20 }); | ||
return async ({ url, ...opts }) => { | ||
const res = await ctx.fetch(url, opts); | ||
return res; | ||
}; | ||
}); | ||
}); |
Oops, something went wrong.