0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/packages/integrations/deno/src/index.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

200 lines
5.1 KiB
TypeScript
Raw Normal View History

import type { AstroAdapter, AstroIntegration } from 'astro';
import esbuild from 'esbuild';
import * as fs from 'node:fs';
import * as npath from 'node:path';
import { fileURLToPath } from 'node:url';
interface BuildConfig {
server: URL;
serverEntry: string;
assets: string;
}
interface Options {
port?: number;
hostname?: string;
}
const SHIM = `globalThis.process = {
argv: [],
env: Deno.env.toObject(),
2022-06-27 16:22:26 -05:00
};`;
2023-02-17 13:21:11 -05:00
const DENO_VERSION = `0.177.0`;
// REF: https://github.com/denoland/deno/tree/main/ext/node/polyfills
const COMPATIBLE_NODE_MODULES = [
'assert',
'assert/strict',
'async_hooks',
'buffer',
'child_process',
'cluster',
'console',
'constants',
'crypto',
'dgram',
'diagnostics_channel',
'dns',
'events',
'fs',
'fs/promises',
'http',
// 'http2',
'https',
'inspector',
'module',
'net',
'os',
'path',
'path/posix',
'path/win32',
'perf_hooks',
'process',
'punycode',
'querystring',
'readline',
'repl',
'stream',
'stream/promises',
'stream/web',
'string_decoder',
'sys',
'timers',
'timers/promises',
// 'tls',
'trace_events',
'tty',
'url',
'util',
'util/types',
// 'v8',
// 'vm',
// 'wasi',
// 'webcrypto',
'worker_threads',
'zlib',
];
// We shim deno-specific imports so we can run the code in Node
2023-02-17 13:21:11 -05:00
// to prerender pages. In the final Deno build, this import is
// replaced with the Deno-specific contents listed below.
const DENO_IMPORTS_SHIM = `@astrojs/deno/__deno_imports.js`;
const DENO_IMPORTS = `export { Server } from "https://deno.land/std@${DENO_VERSION}/http/server.ts"
export { serveFile } from 'https://deno.land/std@${DENO_VERSION}/http/file_server.ts';
2023-02-17 13:21:11 -05:00
export { fromFileUrl } from "https://deno.land/std@${DENO_VERSION}/path/mod.ts";`;
export function getAdapter(args?: Options): AstroAdapter {
return {
name: '@astrojs/deno',
serverEntrypoint: '@astrojs/deno/server.js',
args: args ?? {},
exports: ['stop', 'handle', 'start', 'running'],
};
}
const denoImportsShimPlugin = {
2023-02-17 13:21:11 -05:00
name: '@astrojs/deno:shim',
setup(build: esbuild.PluginBuild) {
build.onLoad({ filter: /__deno_imports\.js$/ }, async () => {
2023-02-17 13:21:11 -05:00
return {
contents: DENO_IMPORTS,
loader: 'js',
};
});
},
};
const denoRenameNodeModulesPlugin = {
name: '@astrojs/esbuild-rename-node-modules',
setup(build: esbuild.PluginBuild) {
const filter = new RegExp(COMPATIBLE_NODE_MODULES.map((mod) => `(^${mod}$)`).join('|'));
build.onResolve({ filter }, (args) => ({ path: 'node:' + args.path, external: true }));
},
};
export default function createIntegration(args?: Options): AstroIntegration {
let _buildConfig: BuildConfig;
let _vite: any;
return {
name: '@astrojs/deno',
hooks: {
'astro:config:done': ({ setAdapter, config }) => {
setAdapter(getAdapter(args));
_buildConfig = config.build;
2022-07-24 23:20:38 -05:00
if (config.output === 'static') {
feat: hybrid output (#6991) * update config schema * adapt default route `prerender` value * adapt error message for hybrid output * core hybrid output support * add JSDocs for hybrid output * dev server hybrid output support * defer hybrid output check * update endpoint request warning * support `output=hybrid` in integrations * put constant variable out of for loop * revert: reapply back ssr plugin in ssr mode * change `prerender` option default * apply `prerender` by default in hybrid mode * simplfy conditional * update config schema * add `isHybridOutput` helper * more readable prerender condition * set default prerender value if no export is found * only add `pagesVirtualModuleId` ro rollup input in `output=static` * don't export vite plugin * remove unneeded check * don't prerender when it shouldn't * extract fallback `prerender` meta Extract the fallback `prerender` module meta out of the `scan` function. It shouldn't be its responsibility to handle that * pass missing argument to function * test: update cloudflare integration tests * test: update tests of vercel integration * test: update tests of node integration * test: update tests of netlify func integration * test: update tests of netlify edge integration * throw when `hybrid` mode is malconfigured * update node integraiton `output` warning * test(WIP): skip node prerendering tests for now * remove non-existant import * test: bring back prerendering tests * remove outdated comments * test: refactor test to support windows paths * remove outdated comments * apply sarah review Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> * docs: `experiment.hybridOutput` jsodcs * test: prevent import from being cached * refactor: extract hybrid output check to function * add `hybrid` to output warning in adapter hooks * chore: changeset * add `.js` extension to import * chore: use spaces instead of tabs for gh formating * resolve merge conflict * chore: move test to another file for consitency --------- Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca> Co-authored-by: Matthew Phillips <matthew@skypack.dev>
2023-05-17 08:23:20 -05:00
console.warn(
`[@astrojs/deno] \`output: "server"\` or \`output: "hybrid"\` is required to use this adapter.`
);
2022-07-24 23:20:38 -05:00
console.warn(
`[@astrojs/deno] Otherwise, this adapter is not required to deploy a static site to Deno.`
);
}
},
'astro:build:setup': ({ vite, target }) => {
2022-03-30 07:43:13 -05:00
if (target === 'server') {
_vite = vite;
vite.resolve = vite.resolve ?? {};
vite.resolve.alias = vite.resolve.alias ?? {};
vite.build = vite.build ?? {};
vite.build.rollupOptions = vite.build.rollupOptions ?? {};
vite.build.rollupOptions.external = vite.build.rollupOptions.external ?? [];
const aliases = [{ find: 'react-dom/server', replacement: 'react-dom/server.browser' }];
if (Array.isArray(vite.resolve.alias)) {
vite.resolve.alias = [...vite.resolve.alias, ...aliases];
} else {
for (const alias of aliases) {
(vite.resolve.alias as Record<string, string>)[alias.find] = alias.replacement;
}
}
vite.ssr = {
noExternal: COMPATIBLE_NODE_MODULES,
};
if (Array.isArray(vite.build.rollupOptions.external)) {
2023-02-17 13:21:11 -05:00
vite.build.rollupOptions.external.push(DENO_IMPORTS_SHIM);
} else if (typeof vite.build.rollupOptions.external !== 'function') {
2023-02-17 13:21:11 -05:00
vite.build.rollupOptions.external = [
vite.build.rollupOptions.external,
DENO_IMPORTS_SHIM,
];
}
}
2022-03-30 07:43:13 -05:00
},
'astro:build:done': async () => {
const entryUrl = new URL(_buildConfig.serverEntry, _buildConfig.server);
const pth = fileURLToPath(entryUrl);
await esbuild.build({
target: 'esnext',
platform: 'browser',
entryPoints: [pth],
outfile: pth,
allowOverwrite: true,
format: 'esm',
bundle: true,
external: [
...COMPATIBLE_NODE_MODULES.map((mod) => `node:${mod}`),
'@astrojs/markdown-remark',
],
plugins: [denoImportsShimPlugin, denoRenameNodeModulesPlugin],
banner: {
js: SHIM,
2022-06-27 16:22:26 -05:00
},
});
// Remove chunks, if they exist. Since we have bundled via esbuild these chunks are trash.
try {
2022-06-06 11:03:17 -05:00
const chunkFileNames =
_vite?.build?.rollupOptions?.output?.chunkFileNames ?? `chunks/chunk.[hash].mjs`;
const chunkPath = npath.dirname(chunkFileNames);
const chunksDirUrl = new URL(chunkPath + '/', _buildConfig.server);
await fs.promises.rm(chunksDirUrl, { recursive: true, force: true });
} catch {}
2022-06-06 11:03:17 -05:00
},
},
};
}