Skip to content

Commit

Permalink
middleware to find addon assets
Browse files Browse the repository at this point in the history
  • Loading branch information
patricklx committed Mar 12, 2024
1 parent 06b32b8 commit c7179e7
Showing 1 changed file with 49 additions and 2 deletions.
51 changes: 49 additions & 2 deletions packages/vite/src/assets.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,66 @@
import { ResolverLoader } from '@embroider/core';
import type { Resolver } from '@embroider/core';
import { ResolverLoader, locateEmbroiderWorkingDir } from '@embroider/core';
import type { Plugin } from 'vite';
import * as process from 'process';
import { dirname, join } from 'path';
import { copyFileSync, mkdirpSync } from 'fs-extra';
import { copyFileSync, mkdirpSync, existsSync } from 'fs-extra';
import glob from 'fast-glob';

function findPublicAsset(relativePath: string, resolver: Resolver, embroiderWorkingDir: string) {
const packageCache = resolver.packageCache;
const cwd = process.cwd();
const publicDir = join(cwd, 'public');
// check public path
let pkg = packageCache.ownerOfFile(relativePath);
let p = join(publicDir, relativePath);
if (pkg && pkg.isV2App() && existsSync(p)) {
return '/' + p;
}

for (const engine of resolver.options.engines) {
for (const addon of engine.activeAddons) {
pkg = packageCache.ownerOfFile(addon.root);
if (pkg && pkg.meta && pkg.isV2Addon() && pkg.meta['public-assets']) {
const asset = Object.entries(pkg.meta['public-assets']).find(([_key, a]) => a === relativePath)?.[0];
let local = asset ? join(addon.root, asset) : null;
if (!local?.includes(embroiderWorkingDir) && asset) {
// remap to local path without symlinks so vite can find it
const localNodeModulePath = local?.split('/node_modules/').slice(-1)[0]!;
local = join('node_modules', localNodeModulePath);
}
if (local && existsSync(local)) {
return '/' + local;
}
}
}
}
}

export function assets(): Plugin {
const cwd = process.cwd();
const resolverLoader = new ResolverLoader(cwd);
const embroiderWorkingDir = locateEmbroiderWorkingDir(cwd);
return {
name: 'assets',
enforce: 'pre',
outputOptions(options) {
options.dir = join(process.cwd(), 'dist');
},
configureServer(server) {
server.middlewares.use((req, _res, next) => {
if (req.originalUrl?.includes('?')) {
return next();
}
if (req.originalUrl && req.originalUrl.length > 1) {
const newUrl = findPublicAsset(req.originalUrl, resolverLoader.resolver, embroiderWorkingDir);
if (newUrl) {
req.originalUrl = newUrl;
(req as any).url = newUrl;
}
}
return next();
});
},
async writeBundle(options) {
const engines = resolverLoader.resolver.options.engines;
const pubDir = join(process.cwd(), 'public');
Expand Down

0 comments on commit c7179e7

Please sign in to comment.