summaryrefslogtreecommitdiff
path: root/packages/integrations/vercel/src
diff options
context:
space:
mode:
authorGravatar Matthew Phillips <matthew@skypack.dev> 2024-09-10 12:56:21 -0400
committerGravatar GitHub <noreply@github.com> 2024-09-10 12:56:21 -0400
commite41ab33f93084262984cb33c5535c0792db6fa6f (patch)
tree81181c8cb19b739f0a0456e951e8bc07a7c7a5dc /packages/integrations/vercel/src
parent90a7b4ddaccd9a806721a0581525d858702cf7a2 (diff)
downloadastro-e41ab33f93084262984cb33c5535c0792db6fa6f.tar.gz
astro-e41ab33f93084262984cb33c5535c0792db6fa6f.tar.zst
astro-e41ab33f93084262984cb33c5535c0792db6fa6f.zip
Set the workspace root when doing nft scan (#381)
* Debuggin * Changeset * More info for debugging * filter more * Fix the underlying issue * fix formatting * block entire linuxbrew root * ignore home entirely * Set the base to the workspace root * more debuggin * make it be a URL * cleanup * Fix tests * Apply to Vercel as well * Fix build * format code * Vendor searchRoot for vercel * formatting --------- Co-authored-by: Alexander Niebuhr <alexander@nbhr.io>
Diffstat (limited to 'packages/integrations/vercel/src')
-rw-r--r--packages/integrations/vercel/src/lib/nft.ts16
-rw-r--r--packages/integrations/vercel/src/lib/searchRoot.ts101
-rw-r--r--packages/integrations/vercel/src/serverless/adapter.ts15
3 files changed, 116 insertions, 16 deletions
diff --git a/packages/integrations/vercel/src/lib/nft.ts b/packages/integrations/vercel/src/lib/nft.ts
index 61dcd8f9e..baf069b07 100644
--- a/packages/integrations/vercel/src/lib/nft.ts
+++ b/packages/integrations/vercel/src/lib/nft.ts
@@ -1,7 +1,9 @@
import { relative as relativePath } from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { copyFilesToFolder } from '@astrojs/internal-helpers/fs';
+import { appendForwardSlash } from '@astrojs/internal-helpers/path';
import type { AstroIntegrationLogger } from 'astro';
+import { searchForWorkspaceRoot } from './searchRoot.js';
export async function copyDependenciesToFunction(
{
@@ -10,12 +12,14 @@ export async function copyDependenciesToFunction(
includeFiles,
excludeFiles,
logger,
+ root,
}: {
entry: URL;
outDir: URL;
includeFiles: URL[];
excludeFiles: URL[];
logger: AstroIntegrationLogger;
+ root: URL;
},
// we want to pass the caching by reference, and not by value
cache: object
@@ -23,11 +27,8 @@ export async function copyDependenciesToFunction(
const entryPath = fileURLToPath(entry);
logger.info(`Bundling function ${relativePath(fileURLToPath(outDir), entryPath)}`);
- // Get root of folder of the system (like C:\ on Windows or / on Linux)
- let base = entry;
- while (fileURLToPath(base) !== fileURLToPath(new URL('../', base))) {
- base = new URL('../', base);
- }
+ // Set the base to the workspace root
+ const base = pathToFileURL(appendForwardSlash(searchForWorkspaceRoot(fileURLToPath(root))));
// The Vite bundle includes an import to `@vercel/nft` for some reason,
// and that trips up `@vercel/nft` itself during the adapter build. Using a
@@ -36,9 +37,6 @@ export async function copyDependenciesToFunction(
const { nodeFileTrace } = await import('@vercel/nft');
const result = await nodeFileTrace([entryPath], {
base: fileURLToPath(base),
- // If you have a route of /dev this appears in source and NFT will try to
- // scan your local /dev :8
- ignore: ['/dev/**'],
cache,
});
diff --git a/packages/integrations/vercel/src/lib/searchRoot.ts b/packages/integrations/vercel/src/lib/searchRoot.ts
new file mode 100644
index 000000000..832f6e498
--- /dev/null
+++ b/packages/integrations/vercel/src/lib/searchRoot.ts
@@ -0,0 +1,101 @@
+// Taken from: https://github.com/vitejs/vite/blob/1a76300cd16827f0640924fdc21747ce140c35fb/packages/vite/src/node/server/searchRoot.ts
+// MIT license
+// See https://github.com/vitejs/vite/blob/1a76300cd16827f0640924fdc21747ce140c35fb/LICENSE
+import fs from 'node:fs';
+import { dirname, join } from 'node:path';
+
+// https://github.com/vitejs/vite/issues/2820#issuecomment-812495079
+const ROOT_FILES = [
+ // '.git',
+
+ // https://pnpm.io/workspaces/
+ 'pnpm-workspace.yaml',
+
+ // https://rushjs.io/pages/advanced/config_files/
+ // 'rush.json',
+
+ // https://nx.dev/latest/react/getting-started/nx-setup
+ // 'workspace.json',
+ // 'nx.json',
+
+ // https://github.com/lerna/lerna#lernajson
+ 'lerna.json',
+];
+
+export function tryStatSync(file: string): fs.Stats | undefined {
+ try {
+ // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
+ return fs.statSync(file, { throwIfNoEntry: false });
+ } catch {
+ // Ignore errors
+ }
+}
+
+export function isFileReadable(filename: string): boolean {
+ if (!tryStatSync(filename)) {
+ return false;
+ }
+
+ try {
+ // Check if current process has read permission to the file
+ fs.accessSync(filename, fs.constants.R_OK);
+
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// npm: https://docs.npmjs.com/cli/v7/using-npm/workspaces#installing-workspaces
+// yarn: https://classic.yarnpkg.com/en/docs/workspaces/#toc-how-to-use-it
+function hasWorkspacePackageJSON(root: string): boolean {
+ const path = join(root, 'package.json');
+ if (!isFileReadable(path)) {
+ return false;
+ }
+ try {
+ const content = JSON.parse(fs.readFileSync(path, 'utf-8')) || {};
+ return !!content.workspaces;
+ } catch {
+ return false;
+ }
+}
+
+function hasRootFile(root: string): boolean {
+ return ROOT_FILES.some((file) => fs.existsSync(join(root, file)));
+}
+
+function hasPackageJSON(root: string) {
+ const path = join(root, 'package.json');
+ return fs.existsSync(path);
+}
+
+/**
+ * Search up for the nearest `package.json`
+ */
+export function searchForPackageRoot(current: string, root = current): string {
+ if (hasPackageJSON(current)) return current;
+
+ const dir = dirname(current);
+ // reach the fs root
+ if (!dir || dir === current) return root;
+
+ return searchForPackageRoot(dir, root);
+}
+
+/**
+ * Search up for the nearest workspace root
+ */
+export function searchForWorkspaceRoot(
+ current: string,
+ root = searchForPackageRoot(current)
+): string {
+ if (hasRootFile(current)) return current;
+ if (hasWorkspacePackageJSON(current)) return current;
+
+ const dir = dirname(current);
+ // reach the fs root
+ if (!dir || dir === current) return root;
+
+ return searchForWorkspaceRoot(dir, root);
+}
diff --git a/packages/integrations/vercel/src/serverless/adapter.ts b/packages/integrations/vercel/src/serverless/adapter.ts
index c589c9265..e50bd4190 100644
--- a/packages/integrations/vercel/src/serverless/adapter.ts
+++ b/packages/integrations/vercel/src/serverless/adapter.ts
@@ -369,7 +369,7 @@ export default function vercelServerless({
? getRouteFuncName(route)
: getFallbackFuncName(entryFile);
- await builder.buildServerlessFolder(entryFile, func);
+ await builder.buildServerlessFolder(entryFile, func, _config.root);
routeDefinitions.push({
src: route.pattern.source,
@@ -380,7 +380,7 @@ export default function vercelServerless({
const entryFile = new URL(_serverEntry, _buildTempFolder);
if (isr) {
const isrConfig = typeof isr === 'object' ? isr : {};
- await builder.buildServerlessFolder(entryFile, NODE_PATH);
+ await builder.buildServerlessFolder(entryFile, NODE_PATH, _config.root);
if (isrConfig.exclude?.length) {
const dest = _middlewareEntryPoint ? MIDDLEWARE_PATH : NODE_PATH;
for (const route of isrConfig.exclude) {
@@ -388,14 +388,14 @@ export default function vercelServerless({
routeDefinitions.push({ src: escapeRegex(route), dest });
}
}
- await builder.buildISRFolder(entryFile, '_isr', isrConfig);
+ await builder.buildISRFolder(entryFile, '_isr', isrConfig, _config.root);
for (const route of routes) {
const src = route.pattern.source;
const dest = src.startsWith('^\\/_image') ? NODE_PATH : ISR_PATH;
if (!route.prerender) routeDefinitions.push({ src, dest });
}
} else {
- await builder.buildServerlessFolder(entryFile, NODE_PATH);
+ await builder.buildServerlessFolder(entryFile, NODE_PATH, _config.root);
const dest = _middlewareEntryPoint ? MIDDLEWARE_PATH : NODE_PATH;
for (const route of routes) {
if (!route.prerender) routeDefinitions.push({ src: route.pattern.source, dest });
@@ -485,7 +485,7 @@ class VercelBuilder {
readonly runtime = getRuntime(process, logger)
) {}
- async buildServerlessFolder(entry: URL, functionName: string) {
+ async buildServerlessFolder(entry: URL, functionName: string, root: URL) {
const { config, includeFiles, excludeFiles, logger, NTF_CACHE, runtime, maxDuration } = this;
// .vercel/output/functions/<name>.func/
const functionFolder = new URL(`./functions/${functionName}.func/`, config.outDir);
@@ -500,6 +500,7 @@ class VercelBuilder {
includeFiles,
excludeFiles,
logger,
+ root,
},
NTF_CACHE
);
@@ -519,8 +520,8 @@ class VercelBuilder {
});
}
- async buildISRFolder(entry: URL, functionName: string, isr: VercelISRConfig) {
- await this.buildServerlessFolder(entry, functionName);
+ async buildISRFolder(entry: URL, functionName: string, isr: VercelISRConfig, root: URL) {
+ await this.buildServerlessFolder(entry, functionName, root);
const prerenderConfig = new URL(
`./functions/${functionName}.prerender-config.json`,
this.config.outDir