chore: update to vite's hook filter (#3333)

Fixes https://github.com/denoland/fresh/issues/3331
This commit is contained in:
Marvin Hagemeister
2025-09-04 11:16:06 +02:00
committed by GitHub
parent baf774517b
commit b94aab2a1a
10 changed files with 432 additions and 418 deletions
Generated
+12 -59
View File
@@ -16,7 +16,7 @@
"jsr:@std/assert@^1.0.14": "1.0.14", "jsr:@std/assert@^1.0.14": "1.0.14",
"jsr:@std/async@1": "1.0.14", "jsr:@std/async@1": "1.0.14",
"jsr:@std/async@^1.0.13": "1.0.14", "jsr:@std/async@^1.0.13": "1.0.14",
"jsr:@std/bytes@^1.0.2": "1.0.6", "jsr:@std/bytes@^1.0.5": "1.0.6",
"jsr:@std/bytes@^1.0.6": "1.0.6", "jsr:@std/bytes@^1.0.6": "1.0.6",
"jsr:@std/cli@^1.0.19": "1.0.21", "jsr:@std/cli@^1.0.19": "1.0.21",
"jsr:@std/cli@^1.0.21": "1.0.21", "jsr:@std/cli@^1.0.21": "1.0.21",
@@ -41,7 +41,7 @@
"jsr:@std/http@^1.0.15": "1.0.20", "jsr:@std/http@^1.0.15": "1.0.20",
"jsr:@std/internal@^1.0.10": "1.0.10", "jsr:@std/internal@^1.0.10": "1.0.10",
"jsr:@std/internal@^1.0.9": "1.0.10", "jsr:@std/internal@^1.0.9": "1.0.10",
"jsr:@std/io@0.225": "0.225.0", "jsr:@std/io@0.225": "0.225.2",
"jsr:@std/io@0.225.0": "0.225.0", "jsr:@std/io@0.225.0": "0.225.0",
"jsr:@std/json@^1.0.2": "1.0.2", "jsr:@std/json@^1.0.2": "1.0.2",
"jsr:@std/jsonc@1": "1.0.2", "jsr:@std/jsonc@1": "1.0.2",
@@ -58,7 +58,7 @@
"jsr:@std/toml@^1.0.3": "1.0.8", "jsr:@std/toml@^1.0.3": "1.0.8",
"jsr:@std/uuid@^1.0.7": "1.0.9", "jsr:@std/uuid@^1.0.7": "1.0.9",
"jsr:@std/yaml@^1.0.5": "1.0.9", "jsr:@std/yaml@^1.0.5": "1.0.9",
"jsr:@zip-js/zip-js@^2.7.52": "2.7.72", "jsr:@zip-js/zip-js@^2.7.52": "2.7.73",
"npm:@babel/core@^7.28.0": "7.28.3", "npm:@babel/core@^7.28.0": "7.28.3",
"npm:@babel/preset-react@^7.27.1": "7.27.1_@babel+core@7.28.3", "npm:@babel/preset-react@^7.27.1": "7.27.1_@babel+core@7.28.3",
"npm:@mjackson/node-fetch-server@0.7": "0.7.0", "npm:@mjackson/node-fetch-server@0.7": "0.7.0",
@@ -98,10 +98,8 @@
"npm:tailwindcss@^4.1.10": "4.1.12", "npm:tailwindcss@^4.1.10": "4.1.12",
"npm:ts-morph@26": "26.0.0", "npm:ts-morph@26": "26.0.0",
"npm:vite-plugin-inspect@^11.3.2": "11.3.3_vite@7.1.4__@types+node@24.3.0__picomatch@4.0.3_@types+node@24.3.0_@types+node@24.2.0", "npm:vite-plugin-inspect@^11.3.2": "11.3.3_vite@7.1.4__@types+node@24.3.0__picomatch@4.0.3_@types+node@24.3.0_@types+node@24.2.0",
"npm:vite@*": "7.1.3_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0", "npm:vite@*": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
"npm:vite@7.1.3": "7.1.3_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
"npm:vite@7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0", "npm:vite@7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
"npm:vite@^7.1.3": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0",
"npm:vite@^7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0" "npm:vite@^7.1.4": "7.1.4_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0"
}, },
"jsr": { "jsr": {
@@ -247,9 +245,12 @@
"integrity": "e3be62ce42cab0e177c27698e5d9800122f67b766a0bea6ca4867886cbde8cf7" "integrity": "e3be62ce42cab0e177c27698e5d9800122f67b766a0bea6ca4867886cbde8cf7"
}, },
"@std/io@0.225.0": { "@std/io@0.225.0": {
"integrity": "c1db7c5e5a231629b32d64b9a53139445b2ca640d828c26bf23e1c55f8c079b3", "integrity": "c1db7c5e5a231629b32d64b9a53139445b2ca640d828c26bf23e1c55f8c079b3"
},
"@std/io@0.225.2": {
"integrity": "3c740cd4ee4c082e6cfc86458f47e2ab7cb353dc6234d5e9b1f91a2de5f4d6c7",
"dependencies": [ "dependencies": [
"jsr:@std/bytes@^1.0.2" "jsr:@std/bytes@^1.0.5"
] ]
}, },
"@std/json@1.0.2": { "@std/json@1.0.2": {
@@ -318,8 +319,8 @@
"@zip-js/zip-js@2.7.62": { "@zip-js/zip-js@2.7.62": {
"integrity": "11cbe0746fa1e52e6e0a601c89ba97365f16e38a07f139b9d9914f988aec9081" "integrity": "11cbe0746fa1e52e6e0a601c89ba97365f16e38a07f139b9d9914f988aec9081"
}, },
"@zip-js/zip-js@2.7.72": { "@zip-js/zip-js@2.7.73": {
"integrity": "b72877f90aaefa1f1bd265d51f354bb58b6dd0d0e2799c865584acf49eae9115" "integrity": "14c123f0e534377a6f47c5ba5293bb6c0f3e72e78c6a687108011605420a4867"
} }
}, },
"npm": { "npm": {
@@ -2611,16 +2612,6 @@
"reusify@1.1.0": { "reusify@1.1.0": {
"integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==" "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="
}, },
"rollup-plugin-visualizer@6.0.3": {
"integrity": "sha512-ZU41GwrkDcCpVoffviuM9Clwjy5fcUxlz0oMoTXTYsK+tcIFzbdacnrr2n8TXcHxbGKKXtOdjxM2HUS4HjkwIw==",
"dependencies": [
"open@8.4.2",
"picomatch@4.0.3",
"source-map",
"yargs"
],
"bin": true
},
"rollup-plugin-visualizer@6.0.3_rollup@4.50.0": { "rollup-plugin-visualizer@6.0.3_rollup@4.50.0": {
"integrity": "sha512-ZU41GwrkDcCpVoffviuM9Clwjy5fcUxlz0oMoTXTYsK+tcIFzbdacnrr2n8TXcHxbGKKXtOdjxM2HUS4HjkwIw==", "integrity": "sha512-ZU41GwrkDcCpVoffviuM9Clwjy5fcUxlz0oMoTXTYsK+tcIFzbdacnrr2n8TXcHxbGKKXtOdjxM2HUS4HjkwIw==",
"dependencies": [ "dependencies": [
@@ -2942,44 +2933,6 @@
"vite-dev-rpc@1.1.0_vite@7.1.4__@types+node@24.3.0__picomatch@4.0.3_@types+node@24.3.0_@types+node@24.2.0" "vite-dev-rpc@1.1.0_vite@7.1.4__@types+node@24.3.0__picomatch@4.0.3_@types+node@24.3.0_@types+node@24.2.0"
] ]
}, },
"vite@7.1.3_@types+node@24.3.0_picomatch@4.0.3": {
"integrity": "sha512-OOUi5zjkDxYrKhTV3V7iKsoS37VUM7v40+HuwEmcrsf11Cdx9y3DIr2Px6liIcZFwt3XSRpQvFpL3WVy7ApkGw==",
"dependencies": [
"@types/node@24.3.0",
"esbuild",
"fdir",
"picomatch@4.0.3",
"postcss",
"rollup",
"tinyglobby"
],
"optionalDependencies": [
"fsevents"
],
"optionalPeers": [
"@types/node@24.3.0"
],
"bin": true
},
"vite@7.1.3_@types+node@24.3.0_picomatch@4.0.3_@types+node@24.2.0": {
"integrity": "sha512-OOUi5zjkDxYrKhTV3V7iKsoS37VUM7v40+HuwEmcrsf11Cdx9y3DIr2Px6liIcZFwt3XSRpQvFpL3WVy7ApkGw==",
"dependencies": [
"@types/node@24.2.0",
"esbuild",
"fdir",
"picomatch@4.0.3",
"postcss",
"rollup",
"tinyglobby"
],
"optionalDependencies": [
"fsevents"
],
"optionalPeers": [
"@types/node@24.2.0"
],
"bin": true
},
"vite@7.1.4_@types+node@24.3.0_picomatch@4.0.3": { "vite@7.1.4_@types+node@24.3.0_picomatch@4.0.3": {
"integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==", "integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==",
"dependencies": [ "dependencies": [
@@ -3232,7 +3185,7 @@
"dependencies": [ "dependencies": [
"npm:@tailwindcss/vite@^4.1.12", "npm:@tailwindcss/vite@^4.1.12",
"npm:vite-plugin-inspect@^11.3.2", "npm:vite-plugin-inspect@^11.3.2",
"npm:vite@^7.1.3" "npm:vite@^7.1.4"
] ]
} }
} }
+7 -4
View File
@@ -26,14 +26,17 @@ export function buildIdPlugin(): Plugin {
return `\0fresh/build-id`; return `\0fresh/build-id`;
} }
}, },
load(id) { load: {
if (id !== `\0fresh/build-id`) return; filter: {
id: /\0fresh\/build-id/,
return `export let BUILD_ID = ${JSON.stringify(buildId)}; },
handler() {
return `export let BUILD_ID = ${JSON.stringify(buildId)};
export const DENO_DEPLOYMENT_ID = undefined; export const DENO_DEPLOYMENT_ID = undefined;
export function setBuildId(id) { export function setBuildId(id) {
BUILD_ID = id; BUILD_ID = id;
}`; }`;
},
}, },
}; };
} }
@@ -19,25 +19,32 @@ export function clientEntryPlugin(options: ResolvedFreshViteConfig): Plugin {
configResolved(config) { configResolved(config) {
clientEntry = pathWithRoot(options.clientEntry, config.root); clientEntry = pathWithRoot(options.clientEntry, config.root);
}, },
resolveId(id) { resolveId: {
if (id === modName) { filter: {
return `\0${modName}`; id: /(fresh:client-entry|fresh:client-entry-user)/,
} else if (id === modNameUser) { },
return clientEntry; handler(id) {
} if (id === modName) {
return `\0${modName}`;
} else if (id === modNameUser) {
return clientEntry;
}
},
}, },
async load(id) { load: {
if (id !== `\0${modName}`) return; filter: {
id: /\0fresh:client-entry/,
},
async handler() {
let exists = false;
try {
const stat = await Deno.stat(clientEntry);
exists = stat.isFile;
} catch {
exists = false;
}
let exists = false; return `
try {
const stat = await Deno.stat(clientEntry);
exists = stat.isFile;
} catch {
exists = false;
}
return `
${isDev ? 'import "preact/debug"' : ""} ${isDev ? 'import "preact/debug"' : ""}
export * from "fresh/runtime-client"; export * from "fresh/runtime-client";
${exists ? `import "fresh:client-entry-user";` : ""} ${exists ? `import "fresh:client-entry-user";` : ""}
@@ -52,6 +59,7 @@ if (import.meta.hot) {
}); });
} }
`; `;
},
}, },
}; };
} }
@@ -48,37 +48,47 @@ export function clientSnapshot(options: ResolvedFreshViteConfig): Plugin {
islands.add(filePath); islands.add(filePath);
} }
}, },
resolveId(id) {
if (id === modName) {
return `\0${modName}`;
}
},
configureServer(devServer) { configureServer(devServer) {
server = devServer; server = devServer;
}, },
load(id) { resolveId: {
if (id !== `\0${modName}`) return; filter: {
id: /fresh:client-snapshot/,
const imports = Array.from(islands.keys()).map((file, i) => { },
return `export const mod_${i} = await import(${JSON.stringify(file)});`; handler(id) {
}).join("\n"); if (id === modName) {
return `\0${modName}`;
if (isDev && server !== undefined) {
const mod = server.environments.ssr.moduleGraph.getModuleById(
"\0fresh:server-snapshot",
);
if (mod) {
server.environments.ssr.moduleGraph.invalidateModule(mod);
} }
} },
},
load: {
filter: {
id: /\0fresh:client-snapshot/,
},
handler() {
const imports = Array.from(islands.keys()).map((file, i) => {
return `export const mod_${i} = await import(${
JSON.stringify(file)
});`;
}).join("\n");
return `${imports} if (isDev && server !== undefined) {
const mod = server.environments.ssr.moduleGraph.getModuleById(
"\0fresh:server-snapshot",
);
if (mod) {
server.environments.ssr.moduleGraph.invalidateModule(mod);
}
}
return `${imports}
if (import.meta.hot) { if (import.meta.hot) {
import.meta.hot.accept(() => { import.meta.hot.accept(() => {
console.log("accepting client-snapshot") console.log("accepting client-snapshot")
}); });
} }
`; `;
},
}, },
}; };
} }
+41 -31
View File
@@ -10,7 +10,7 @@ import * as path from "@std/path";
import * as babel from "@babel/core"; import * as babel from "@babel/core";
import babelReact from "@babel/preset-react"; import babelReact from "@babel/preset-react";
import { httpAbsolute } from "./patches/http_absolute.ts"; import { httpAbsolute } from "./patches/http_absolute.ts";
import { JS_REG } from "../utils.ts"; import { JS_REG, JSX_REG } from "../utils.ts";
interface DenoState { interface DenoState {
type: RequestedModuleType; type: RequestedModuleType;
@@ -210,40 +210,50 @@ export function deno(): Plugin {
code, code,
}; };
}, },
async transform(_, id, options) { transform: {
// This transform is a hack to be able to re-use Deno's precompile filter: {
// jsx transform. id: JSX_REG,
if (!options?.ssr || !id.endsWith(".tsx") || id.endsWith(".jsx")) { },
return; async handler(_, id, options) {
} // This transform is a hack to be able to re-use Deno's precompile
// jsx transform.
if (!options?.ssr) {
return;
}
let actualId = id; let actualId = id;
if (isDenoSpecifier(id)) { if (isDenoSpecifier(id)) {
const { specifier } = parseDenoSpecifier(id); const { specifier } = parseDenoSpecifier(id);
actualId = specifier; actualId = specifier;
} }
if (path.isAbsolute(actualId)) { actualId = actualId.replace("?commonjs-es-import", "");
actualId = path.toFileUrl(actualId).href;
}
const resolved = await ssrLoader.resolve( if (actualId.startsWith("\0")) {
actualId, actualId = actualId.slice(1);
undefined, }
ResolutionMode.Import, if (path.isAbsolute(actualId)) {
); actualId = path.toFileUrl(actualId).href;
const result = await ssrLoader.load( }
resolved,
RequestedModuleType.Default,
);
if (result.kind === "external") {
return;
}
const code = new TextDecoder().decode(result.code); const resolved = await ssrLoader.resolve(
actualId,
undefined,
ResolutionMode.Import,
);
const result = await ssrLoader.load(
resolved,
RequestedModuleType.Default,
);
if (result.kind === "external") {
return;
}
return { const code = new TextDecoder().decode(result.code);
code,
}; return {
code,
};
},
}, },
}; };
} }
+38 -35
View File
@@ -19,45 +19,48 @@ export function patches(): Plugin {
applyToEnvironment() { applyToEnvironment() {
return true; return true;
}, },
transform(code, id, options) { transform: {
if (!JS_REG.test(id)) return; filter: {
id: JS_REG,
},
handler(code, id, options) {
const presets = [];
if (!options?.ssr && JSX_REG.test(id)) {
presets.push([babelReact, {
runtime: "automatic",
importSource: "preact",
development: isDev,
}]);
}
const presets = []; const plugins: babel.PluginItem[] = [
if (!options?.ssr && JSX_REG.test(id)) { cjsPlugin,
presets.push([babelReact, { removePolyfills,
runtime: "automatic", jsxComments,
importSource: "preact", inlineEnvVarsPlugin(
development: isDev, isDev ? "development" : "production",
}]); ),
} ];
const plugins: babel.PluginItem[] = [ if (!options?.ssr) {
cjsPlugin, plugins.push(denoGlobal);
removePolyfills, }
jsxComments,
inlineEnvVarsPlugin(
isDev ? "development" : "production",
),
];
if (!options?.ssr) { const res = babel.transformSync(code, {
plugins.push(denoGlobal); filename: id,
} babelrc: false,
compact: true,
plugins,
presets,
});
const res = babel.transformSync(code, { if (res?.code) {
filename: id, return {
babelrc: false, code: res.code,
compact: true, map: res.map,
plugins, };
presets, }
}); },
if (res?.code) {
return {
code: res.code,
map: res.map,
};
}
}, },
}; };
} }
@@ -39,21 +39,28 @@ export function serverEntryPlugin(
config.root, config.root,
); );
}, },
resolveId(id) { resolveId: {
if (id === modName) { filter: {
return `\0${modName}`; id: /fresh:server_entry/,
} },
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
},
}, },
load(id) { load: {
if (id !== `\0${modName}`) return; filter: {
id: /\0fresh:server_entry/,
},
handler() {
let code = generateServerEntry({
root: isDev ? path.relative(serverOutDir, root) : "..",
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
let code = generateServerEntry({ code += `
root: isDev ? path.relative(serverOutDir, root) : "..",
serverEntry: path.toFileUrl(serverEntry).href,
snapshotSpecifier: "fresh:server-snapshot",
});
code += `
export function registerStaticFile(prepared) { export function registerStaticFile(prepared) {
snapshot.staticFiles.set(prepared.name, { snapshot.staticFiles.set(prepared.name, {
@@ -64,13 +71,14 @@ export function registerStaticFile(prepared) {
} }
`; `;
if (isDev) { if (isDev) {
code = `import "preact/debug"; code = `import "preact/debug";
${code} ${code}
if (import.meta.hot) import.meta.hot.accept();`; if (import.meta.hot) import.meta.hot.accept();`;
} }
return code; return code;
},
}, },
async writeBundle(_options, bundle) { async writeBundle(_options, bundle) {
const manifest = bundle[".vite/manifest.json"]; const manifest = bundle[".vite/manifest.json"];
@@ -111,202 +111,214 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
viteServer.ws.send("fresh:reload"); viteServer.ws.send("fresh:reload");
}); });
}, },
resolveId(id) { resolveId: {
if (id === modName) { filter: {
return `\0${modName}`; id: /fresh:server-snapshot/,
} },
handler(id) {
if (id === modName) {
return `\0${modName}`;
}
},
}, },
async load(id) { load: {
if (id !== `\0${modName}`) return; filter: {
id: /\0fresh:server-snapshot/,
},
const result = await crawlFsItem({ async handler() {
islandDir: options.islandsDir, const result = await crawlFsItem({
routeDir: options.routeDir, islandDir: options.islandsDir,
ignore: options.ignore, routeDir: options.routeDir,
}); ignore: options.ignore,
for (let i = 0; i < result.islands.length; i++) {
const spec = result.islands[i];
const specName = specToName(spec);
const name = options.namer.getUniqueName(specName);
islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
islandsByFile.add(spec);
}
const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
const entryAssets: string[] = [];
if (isDev && server !== undefined) {
for (const id of islands.keys()) {
const mod = server.environments.client.moduleGraph.getModuleById(
id,
);
if (mod !== undefined) {
const def = islands.get(id);
if (def !== undefined) def.chunk = mod.url;
}
}
islandMods = Array.from(islands.entries()).map(([id, def]) => {
return {
name: def.name,
server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
css: [],
};
}); });
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
const resolvedIslandSpecs = new Map<string, string>();
for (const spec of options.islandSpecifiers.keys()) { for (let i = 0; i < result.islands.length; i++) {
const resolved = await this.resolve(spec); const spec = result.islands[i];
const specName = specToName(spec);
const name = options.namer.getUniqueName(specName);
if (resolved === null) continue; islands.set(spec, { name, chunk: null });
islandSpecByName.set(name, spec);
const id = resolved.id.startsWith("\0") islandsByFile.add(spec);
? resolved.id.slice(1)
: resolved.id;
resolvedIslandSpecs.set(id, spec);
} }
const clientEntryName = "client-entry"; const staticFiles: PendingStaticFile[] = [];
let islandMods: IslandModChunk[] = [];
let clientEntry = "/@id/fresh:client-entry";
let buildId = "";
const entryAssets: string[] = [];
for (const chunk of Object.values(manifest)) { if (isDev && server !== undefined) {
if (chunk.name === clientEntryName) { for (const id of islands.keys()) {
clientEntry = pathToSpec(clientOutDir, chunk.file); const mod = server.environments.client.moduleGraph.getModuleById(
id,
);
if (mod !== undefined) {
const def = islands.get(id);
if (def !== undefined) def.chunk = mod.url;
}
} }
staticFiles.push({ islandMods = Array.from(islands.entries()).map(([id, def]) => {
filePath: path.join(clientOutDir, chunk.file), return {
pathname: chunk.file, name: def.name,
hash: null, server: id,
browser: def.chunk ?? `/@id/fresh-island::${def.name}`,
css: [],
};
}); });
} else {
buildId = await getBuildId(false);
const manifest = JSON.parse(
await Deno.readTextFile(
path.join(clientOutDir, ".vite", "manifest.json"),
),
) as Manifest;
const resolvedIslandSpecs = new Map<string, string>();
if (chunk.css !== undefined) { for (const spec of options.islandSpecifiers.keys()) {
for (let i = 0; i < chunk.css.length; i++) { const resolved = await this.resolve(spec);
const id = chunk.css[i];
const pathname = `/${id}`; if (resolved === null) continue;
staticFiles.push({ const id = resolved.id.startsWith("\0")
filePath: path.join(clientOutDir, id), ? resolved.id.slice(1)
hash: null, : resolved.id;
pathname,
});
if (chunk.name === clientEntryName) { resolvedIslandSpecs.set(id, spec);
entryAssets.push(pathname);
}
}
} }
const namer = new UniqueNamer(); const clientEntryName = "client-entry";
if (chunk.name === "client-snapshot") {
for (const id of chunk.dynamicImports ?? []) {
const mod = manifest[id];
let serverPath = path.join(root, mod.src ?? id); for (const chunk of Object.values(manifest)) {
const idx = mod.src?.indexOf("deno::") ?? -1; if (chunk.name === clientEntryName) {
clientEntry = pathToSpec(clientOutDir, chunk.file);
if (idx > -1 && mod.src) {
const src = mod.src
.slice(idx)
.replace(
/(https?):\/([^/])/,
(_m, protocol, rest) => {
return `${protocol}://${rest}`;
},
);
serverPath = resolvedIslandSpecs.get(src)!;
}
let spec = pathToSpec(clientOutDir, mod.file);
if (spec.startsWith("./")) {
spec = spec.slice(1);
}
const chunkCss = mod.css?.map((id) => `/${id}`) ?? [];
const name = namer.getUniqueName(specToName(id));
islandMods.push({
name,
browser: spec,
server: serverPath,
css: chunkCss,
});
} }
}
}
if (await fsAdapter.isDirectory(publicDir)) {
const entries = await fsAdapter.walk(
publicDir,
{
followSymlinks: false,
includeDirs: false,
includeFiles: true,
skip: options.ignore,
},
);
for await (const entry of entries) {
const relative = path.relative(publicDir, entry.path);
const filePath = path.join(clientOutDir, relative);
try {
await Deno.mkdir(path.dirname(filePath), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
await Deno.copyFile(entry.path, filePath);
staticFiles.push({ staticFiles.push({
filePath, filePath: path.join(clientOutDir, chunk.file),
pathname: chunk.file,
hash: null, hash: null,
pathname: relative,
}); });
if (chunk.css !== undefined) {
for (let i = 0; i < chunk.css.length; i++) {
const id = chunk.css[i];
const pathname = `/${id}`;
staticFiles.push({
filePath: path.join(clientOutDir, id),
hash: null,
pathname,
});
if (chunk.name === clientEntryName) {
entryAssets.push(pathname);
}
}
}
const namer = new UniqueNamer();
if (chunk.name === "client-snapshot") {
for (const id of chunk.dynamicImports ?? []) {
const mod = manifest[id];
let serverPath = path.join(root, mod.src ?? id);
const idx = mod.src?.indexOf("deno::") ?? -1;
if (idx > -1 && mod.src) {
const src = mod.src
.slice(idx)
.replace(
/(https?):\/([^/])/,
(_m, protocol, rest) => {
return `${protocol}://${rest}`;
},
);
serverPath = resolvedIslandSpecs.get(src)!;
}
let spec = pathToSpec(clientOutDir, mod.file);
if (spec.startsWith("./")) {
spec = spec.slice(1);
}
const chunkCss = mod.css?.map((id) => `/${id}`) ?? [];
const name = namer.getUniqueName(specToName(id));
islandMods.push({
name,
browser: spec,
server: serverPath,
css: chunkCss,
});
}
}
}
if (await fsAdapter.isDirectory(publicDir)) {
const entries = await fsAdapter.walk(
publicDir,
{
followSymlinks: false,
includeDirs: false,
includeFiles: true,
skip: options.ignore,
},
);
for await (const entry of entries) {
const relative = path.relative(publicDir, entry.path);
const filePath = path.join(clientOutDir, relative);
try {
await Deno.mkdir(path.dirname(filePath), { recursive: true });
} catch (err) {
if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
await Deno.copyFile(entry.path, filePath);
staticFiles.push({
filePath,
hash: null,
pathname: relative,
});
}
} }
} }
}
const code = await generateSnapshotServer({ const code = await generateSnapshotServer({
outDir: path.join(clientOutDir, ".."), outDir: path.join(clientOutDir, ".."),
staticFiles, staticFiles,
buildId, buildId,
clientEntry, clientEntry,
entryAssets, entryAssets,
fsRoutesFiles: result.routes, fsRoutesFiles: result.routes,
islands: islandMods, islands: islandMods,
writeSpecifier: (file) => { writeSpecifier: (file) => {
const def = islands.get(file); const def = islands.get(file);
if (def) { if (def) {
return `fresh-island::${def.name}`; return `fresh-island::${def.name}`;
} }
return path.toFileUrl(file).href; return path.toFileUrl(file).href;
}, },
}); });
return code; return code;
},
}, },
}, { }, {
name: "fresh:island-resolver", name: "fresh:island-resolver",
resolveId(id) { resolveId: {
if (id.startsWith("fresh-island::")) { filter: {
id: /^fresh-island::.*/,
},
handler(id) {
let name = id.slice("fresh-island::".length); let name = id.slice("fresh-island::".length);
if (JS_REG.test(name)) { if (JS_REG.test(name)) {
@@ -315,7 +327,7 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] {
const spec = islandSpecByName.get(name); const spec = islandSpecByName.get(name);
if (spec !== undefined) return spec; if (spec !== undefined) return spec;
} },
}, },
}]; }];
} }
@@ -51,91 +51,98 @@ export function checkImports(pluginOptions: CheckImportOptions): Plugin {
configResolved(config) { configResolved(config) {
root = pathWithRoot(config.root); root = pathWithRoot(config.root);
}, },
async resolveId(id, importer, options) { resolveId: {
if ( filter: {
id.startsWith("\0") || id.startsWith("/@fs/") || id: [
id.startsWith("fresh-island::") || id.startsWith("fresh:") || /^(?!\0|[\\/]@fs[\\/]|fresh-island::|fresh:)/,
id.includes("node_modules") || /[\\/]node_modules[\\/]/,
importer && ],
},
async handler(id, importer, options) {
if (
importer &&
(importer.startsWith("\0") || importer.includes("node_modules") || (importer.startsWith("\0") || importer.includes("node_modules") ||
importer.includes("deno::")) importer.includes("deno::"))
) { ) {
return; return;
} }
const env = options.ssr ? "ssr" : "client"; const env = options.ssr ? "ssr" : "client";
let result: ImportCheckDiagnostic | undefined; let result: ImportCheckDiagnostic | undefined;
if (id.startsWith(".")) { if (id.startsWith(".")) {
const resolved = await this.resolve(id, importer, options); const resolved = await this.resolve(id, importer, options);
if (resolved !== null) { if (resolved !== null) {
const key = `${env}::${resolved.id}::${importer}`; const key = `${env}::${resolved.id}::${importer}`;
if (!seen.has(key)) { if (!seen.has(key)) {
result = check(pluginOptions, resolved.id, env); result = check(pluginOptions, resolved.id, env);
}
seen.add(key);
}
} else {
const key = `${env}::${id}::${importer}`;
if (!seen.has(key)) {
result = check(pluginOptions, id, env);
} }
seen.add(key); seen.add(key);
} }
} else {
const key = `${env}::${id}::${importer}`;
if (!seen.has(key)) {
result = check(pluginOptions, id, env);
}
seen.add(key);
}
if (result) { if (result) {
const label = result.type === "warn" const label = result.type === "warn"
? cl.inverse(cl.yellow(` WARN `)) ? cl.inverse(cl.yellow(` WARN `))
: cl.inverse(cl.red(` ERROR `)); : cl.inverse(cl.red(` ERROR `));
// deno-lint-ignore no-console // deno-lint-ignore no-console
console.log(); console.log();
// deno-lint-ignore no-console // deno-lint-ignore no-console
console.log(); console.log();
// deno-lint-ignore no-console // deno-lint-ignore no-console
console.log(`${label} ${result.message}`); console.log(`${label} ${result.message}`);
// deno-lint-ignore no-console // deno-lint-ignore no-console
console.log(); console.log();
if (importer !== undefined) { if (importer !== undefined) {
const ancestors = findAncestors(this, importer, isDev); const ancestors = findAncestors(this, importer, isDev);
if (ancestors && ancestors.length > 0) { if (ancestors && ancestors.length > 0) {
// deno-lint-ignore no-console
console.log(`The specifier ${cl.cyan(`"${id}"`)} was imported in:`);
ancestors.forEach((spec) => {
if (path.isAbsolute(spec)) {
spec = path.relative(root, spec);
}
// deno-lint-ignore no-console // deno-lint-ignore no-console
console.log(` - ${cl.cyan(spec)}`); console.log(
}); `The specifier ${cl.cyan(`"${id}"`)} was imported in:`,
);
ancestors.forEach((spec) => {
if (path.isAbsolute(spec)) {
spec = path.relative(root, spec);
}
// deno-lint-ignore no-console
console.log(` - ${cl.cyan(spec)}`);
});
// deno-lint-ignore no-console
console.log();
}
}
if (result.hint) {
// deno-lint-ignore no-console
console.log(cl.bold(` hint: `) + result.hint);
// deno-lint-ignore no-console // deno-lint-ignore no-console
console.log(); console.log();
} }
}
if (result.hint) { if (result.type === "error") {
// deno-lint-ignore no-console this.error({
console.log(cl.bold(` hint: `) + result.hint); message: result.message,
// deno-lint-ignore no-console id: importer,
console.log(); });
} else {
this.warn({
message: result.message,
id: importer,
});
}
} }
},
if (result.type === "error") {
this.error({
message: result.message,
id: importer,
});
} else {
this.warn({
message: result.message,
id: importer,
});
}
}
}, },
}; };
} }
+1 -1
View File
@@ -6,7 +6,7 @@
}, },
"imports": { "imports": {
"@tailwindcss/vite": "npm:@tailwindcss/vite@^4.1.12", "@tailwindcss/vite": "npm:@tailwindcss/vite@^4.1.12",
"vite": "npm:vite@^7.1.3", "vite": "npm:vite@^7.1.4",
"vite-plugin-inspect": "npm:vite-plugin-inspect@^11.3.2" "vite-plugin-inspect": "npm:vite-plugin-inspect@^11.3.2"
} }
} }