Skip to content

Commit

Permalink
Fix usage of the Image component with the Vercel adapter (#5361)
Browse files Browse the repository at this point in the history
* Revert "Revert "Allow image-pool to be used as its own Worker (#5317)" (#5360)"

This reverts commit 20e60c6.

* Remove special image-pool.js moving around

* Merge in assetIncludes

* changeset

* Copy to chunk folder in SSR too

* Update tidy-shoes-yawn.md
  • Loading branch information
matthewp authored Nov 14, 2022
1 parent 993b58d commit ee75008
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 6 deletions.
6 changes: 6 additions & 0 deletions .changeset/tidy-shoes-yawn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@astrojs/image': patch
'@astrojs/vercel': patch
---

Allows @astrojs/image to be used in Vercel SSR
15 changes: 14 additions & 1 deletion packages/integrations/image/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ export { getPicture } from './lib/get-picture.js';

const PKG_NAME = '@astrojs/image';
const ROUTE_PATTERN = '/_image';
const UNSUPPORTED_ADAPTERS = new Set([
'@astrojs/cloudflare',
'@astrojs/deno',
'@astrojs/netlify/edge-functions',
'@astrojs/vercel/edge',
]);

interface BuildConfig {
client: URL;
Expand Down Expand Up @@ -100,6 +106,13 @@ export default function integration(options: IntegrationOptions = {}): AstroInte
_buildConfig = config.build;
},
'astro:build:start': ({ buildConfig }) => {
const adapterName = _config.adapter?.name;
if (adapterName && UNSUPPORTED_ADAPTERS.has(adapterName)) {
throw new Error(
`@astrojs/image is not supported with the ${adapterName} adapter. Please choose a Node.js compatible adapter.`
);
}

// Backwards compat
if (needsBuildConfig) {
_buildConfig = buildConfig;
Expand Down Expand Up @@ -158,7 +171,7 @@ export default function integration(options: IntegrationOptions = {}): AstroInte
},
'astro:build:ssr': async () => {
if (resolvedOptions.serviceEntryPoint === '@astrojs/image/squoosh') {
await copyWasmFiles(_buildConfig.server);
await copyWasmFiles(new URL('./chunks/', _buildConfig.server));
}
},
},
Expand Down
5 changes: 3 additions & 2 deletions packages/integrations/image/src/loaders/squoosh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { red } from 'kleur/colors';
import { error } from '../utils/logger.js';
import { metadata } from '../utils/metadata.js';
import { isRemoteImage } from '../utils/paths.js';
import { processBuffer } from '../vendor/squoosh/image-pool.js';
import type { Operation } from '../vendor/squoosh/image.js';
import type { OutputFormat, TransformOptions } from './index.js';
import { BaseSSRService } from './index.js';

const imagePoolModulePromise = import('../vendor/squoosh/image-pool.js');

class SquooshService extends BaseSSRService {
async processAvif(image: any, transform: TransformOptions) {
const encodeOptions = transform.quality
Expand Down Expand Up @@ -112,7 +113,7 @@ class SquooshService extends BaseSSRService {
});
throw new Error(`Unknown image output: "${transform.format}" used for ${transform.src}`);
}

const { processBuffer } = await imagePoolModulePromise;
const data = await processBuffer(inputBuffer, operations, transform.format, transform.quality);

return {
Expand Down
3 changes: 2 additions & 1 deletion packages/integrations/image/src/vendor/squoosh/image-pool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { isMainThread } from 'node:worker_threads';
import { cpus } from 'os';
import { fileURLToPath } from 'url';
import type { OutputFormat } from '../../loaders/index.js';
import execOnce from '../../utils/execOnce.js';
import WorkerPool from '../../utils/workerPool.js';
Expand All @@ -12,7 +13,7 @@ const getWorker = execOnce(
// There will be at most 7 workers needed since each worker will take
// at least 1 operation type.
Math.max(1, Math.min(cpus().length - 1, 7)),
'./node_modules/@astrojs/image/dist/vendor/squoosh/image-pool.js'
fileURLToPath(import.meta.url)
);
}
)
Expand Down
3 changes: 2 additions & 1 deletion packages/integrations/vercel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
},
"dependencies": {
"@astrojs/webapi": "^1.1.1",
"@vercel/nft": "^0.22.1"
"@vercel/nft": "^0.22.1",
"fast-glob": "^3.2.11"
},
"devDependencies": {
"astro": "workspace:*",
Expand Down
21 changes: 20 additions & 1 deletion packages/integrations/vercel/src/serverless/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type { AstroAdapter, AstroConfig, AstroIntegration } from 'astro';
import { getVercelOutput, removeDir, writeJson } from '../lib/fs.js';
import { copyDependenciesToFunction } from '../lib/nft.js';
import { getRedirects } from '../lib/redirects.js';
import glob from 'fast-glob';
import { pathToFileURL } from 'url';

const PACKAGE_NAME = '@astrojs/vercel/serverless';

Expand Down Expand Up @@ -66,11 +68,28 @@ export default function vercelServerless({
}
},
'astro:build:done': async ({ routes }) => {
// Merge any includes from `vite.assetsInclude
const inc = includeFiles?.map((file) => new URL(file, _config.root)) || [];
if(_config.vite.assetsInclude) {
const mergeGlobbedIncludes = (globPattern: unknown) => {
if(typeof globPattern === 'string') {
const entries = glob.sync(globPattern).map(p => pathToFileURL(p));
inc.push(...entries);
} else if(Array.isArray(globPattern)) {
for(const pattern of globPattern) {
mergeGlobbedIncludes(pattern);
}
}
};

mergeGlobbedIncludes(_config.vite.assetsInclude);
}

// Copy necessary files (e.g. node_modules/)
const { handler } = await copyDependenciesToFunction({
entry: new URL(serverEntry, buildTempFolder),
outDir: functionFolder,
includeFiles: includeFiles?.map((file) => new URL(file, _config.root)) || [],
includeFiles: inc,
excludeFiles: excludeFiles?.map((file) => new URL(file, _config.root)) || [],
});

Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit ee75008

Please sign in to comment.