diff --git a/deno.lock b/deno.lock index ac896b46..76a96c97 100644 --- a/deno.lock +++ b/deno.lock @@ -67,6 +67,7 @@ "npm:@preact/signals@^2.2.1": "2.2.1_preact@10.27.0", "npm:@prefresh/vite@^2.4.8": "2.4.8_preact@10.27.0_vite@7.1.2__@types+node@24.2.1__picomatch@4.0.3_@types+node@24.2.1_@types+node@24.2.0", "npm:@tailwindcss/postcss@^4.1.10": "4.1.11", + "npm:@tailwindcss/vite@^4.1.12": "4.1.12_vite@7.1.2__@types+node@24.2.1__picomatch@4.0.3__@types+node@24.2.0_@types+node@24.2.0", "npm:@types/babel__core@^7.20.5": "7.20.5", "npm:@types/node@*": "24.2.0", "npm:@types/node@^24.1.0": "24.2.1", @@ -1098,6 +1099,13 @@ "@jridgewell/trace-mapping" ] }, + "@jridgewell/remapping@2.3.5": { + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dependencies": [ + "@jridgewell/gen-mapping", + "@jridgewell/trace-mapping" + ] + }, "@jridgewell/resolve-uri@3.1.2": { "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==" }, @@ -1310,51 +1318,108 @@ "tailwindcss@4.1.11" ] }, + "@tailwindcss/node@4.1.12": { + "integrity": "sha512-3hm9brwvQkZFe++SBt+oLjo4OLDtkvlE8q2WalaD/7QWaeM7KEJbAiY/LJZUaCs7Xa8aUu4xy3uoyX4q54UVdQ==", + "dependencies": [ + "@jridgewell/remapping", + "enhanced-resolve", + "jiti@2.5.1", + "lightningcss", + "magic-string", + "source-map-js", + "tailwindcss@4.1.12" + ] + }, "@tailwindcss/oxide-android-arm64@4.1.11": { "integrity": "sha512-3IfFuATVRUMZZprEIx9OGDjG3Ou3jG4xQzNTvjDoKmU9JdmoCohQJ83MYd0GPnQIu89YoJqvMM0G3uqLRFtetg==", "os": ["android"], "cpu": ["arm64"] }, + "@tailwindcss/oxide-android-arm64@4.1.12": { + "integrity": "sha512-oNY5pq+1gc4T6QVTsZKwZaGpBb2N1H1fsc1GD4o7yinFySqIuRZ2E4NvGasWc6PhYJwGK2+5YT1f9Tp80zUQZQ==", + "os": ["android"], + "cpu": ["arm64"] + }, "@tailwindcss/oxide-darwin-arm64@4.1.11": { "integrity": "sha512-ESgStEOEsyg8J5YcMb1xl8WFOXfeBmrhAwGsFxxB2CxY9evy63+AtpbDLAyRkJnxLy2WsD1qF13E97uQyP1lfQ==", "os": ["darwin"], "cpu": ["arm64"] }, + "@tailwindcss/oxide-darwin-arm64@4.1.12": { + "integrity": "sha512-cq1qmq2HEtDV9HvZlTtrj671mCdGB93bVY6J29mwCyaMYCP/JaUBXxrQQQm7Qn33AXXASPUb2HFZlWiiHWFytw==", + "os": ["darwin"], + "cpu": ["arm64"] + }, "@tailwindcss/oxide-darwin-x64@4.1.11": { "integrity": "sha512-EgnK8kRchgmgzG6jE10UQNaH9Mwi2n+yw1jWmof9Vyg2lpKNX2ioe7CJdf9M5f8V9uaQxInenZkOxnTVL3fhAw==", "os": ["darwin"], "cpu": ["x64"] }, + "@tailwindcss/oxide-darwin-x64@4.1.12": { + "integrity": "sha512-6UCsIeFUcBfpangqlXay9Ffty9XhFH1QuUFn0WV83W8lGdX8cD5/+2ONLluALJD5+yJ7k8mVtwy3zMZmzEfbLg==", + "os": ["darwin"], + "cpu": ["x64"] + }, "@tailwindcss/oxide-freebsd-x64@4.1.11": { "integrity": "sha512-xdqKtbpHs7pQhIKmqVpxStnY1skuNh4CtbcyOHeX1YBE0hArj2romsFGb6yUmzkq/6M24nkxDqU8GYrKrz+UcA==", "os": ["freebsd"], "cpu": ["x64"] }, + "@tailwindcss/oxide-freebsd-x64@4.1.12": { + "integrity": "sha512-JOH/f7j6+nYXIrHobRYCtoArJdMJh5zy5lr0FV0Qu47MID/vqJAY3r/OElPzx1C/wdT1uS7cPq+xdYYelny1ww==", + "os": ["freebsd"], + "cpu": ["x64"] + }, "@tailwindcss/oxide-linux-arm-gnueabihf@4.1.11": { "integrity": "sha512-ryHQK2eyDYYMwB5wZL46uoxz2zzDZsFBwfjssgB7pzytAeCCa6glsiJGjhTEddq/4OsIjsLNMAiMlHNYnkEEeg==", "os": ["linux"], "cpu": ["arm"] }, + "@tailwindcss/oxide-linux-arm-gnueabihf@4.1.12": { + "integrity": "sha512-v4Ghvi9AU1SYgGr3/j38PD8PEe6bRfTnNSUE3YCMIRrrNigCFtHZ2TCm8142X8fcSqHBZBceDx+JlFJEfNg5zQ==", + "os": ["linux"], + "cpu": ["arm"] + }, "@tailwindcss/oxide-linux-arm64-gnu@4.1.11": { "integrity": "sha512-mYwqheq4BXF83j/w75ewkPJmPZIqqP1nhoghS9D57CLjsh3Nfq0m4ftTotRYtGnZd3eCztgbSPJ9QhfC91gDZQ==", "os": ["linux"], "cpu": ["arm64"] }, + "@tailwindcss/oxide-linux-arm64-gnu@4.1.12": { + "integrity": "sha512-YP5s1LmetL9UsvVAKusHSyPlzSRqYyRB0f+Kl/xcYQSPLEw/BvGfxzbH+ihUciePDjiXwHh+p+qbSP3SlJw+6g==", + "os": ["linux"], + "cpu": ["arm64"] + }, "@tailwindcss/oxide-linux-arm64-musl@4.1.11": { "integrity": "sha512-m/NVRFNGlEHJrNVk3O6I9ggVuNjXHIPoD6bqay/pubtYC9QIdAMpS+cswZQPBLvVvEF6GtSNONbDkZrjWZXYNQ==", "os": ["linux"], "cpu": ["arm64"] }, + "@tailwindcss/oxide-linux-arm64-musl@4.1.12": { + "integrity": "sha512-V8pAM3s8gsrXcCv6kCHSuwyb/gPsd863iT+v1PGXC4fSL/OJqsKhfK//v8P+w9ThKIoqNbEnsZqNy+WDnwQqCA==", + "os": ["linux"], + "cpu": ["arm64"] + }, "@tailwindcss/oxide-linux-x64-gnu@4.1.11": { "integrity": "sha512-YW6sblI7xukSD2TdbbaeQVDysIm/UPJtObHJHKxDEcW2exAtY47j52f8jZXkqE1krdnkhCMGqP3dbniu1Te2Fg==", "os": ["linux"], "cpu": ["x64"] }, + "@tailwindcss/oxide-linux-x64-gnu@4.1.12": { + "integrity": "sha512-xYfqYLjvm2UQ3TZggTGrwxjYaLB62b1Wiysw/YE3Yqbh86sOMoTn0feF98PonP7LtjsWOWcXEbGqDL7zv0uW8Q==", + "os": ["linux"], + "cpu": ["x64"] + }, "@tailwindcss/oxide-linux-x64-musl@4.1.11": { "integrity": "sha512-e3C/RRhGunWYNC3aSF7exsQkdXzQ/M+aYuZHKnw4U7KQwTJotnWsGOIVih0s2qQzmEzOFIJ3+xt7iq67K/p56Q==", "os": ["linux"], "cpu": ["x64"] }, + "@tailwindcss/oxide-linux-x64-musl@4.1.12": { + "integrity": "sha512-ha0pHPamN+fWZY7GCzz5rKunlv9L5R8kdh+YNvP5awe3LtuXb5nRi/H27GeL2U+TdhDOptU7T6Is7mdwh5Ar3A==", + "os": ["linux"], + "cpu": ["x64"] + }, "@tailwindcss/oxide-wasm32-wasi@4.1.11": { "integrity": "sha512-Xo1+/GU0JEN/C/dvcammKHzeM6NqKovG+6921MR6oadee5XPBaKOumrJCXvopJ/Qb5TH7LX/UAywbqrP4lax0g==", "dependencies": [ @@ -1367,16 +1432,38 @@ ], "cpu": ["wasm32"] }, + "@tailwindcss/oxide-wasm32-wasi@4.1.12": { + "integrity": "sha512-4tSyu3dW+ktzdEpuk6g49KdEangu3eCYoqPhWNsZgUhyegEda3M9rG0/j1GV/JjVVsj+lG7jWAyrTlLzd/WEBg==", + "dependencies": [ + "@emnapi/core", + "@emnapi/runtime", + "@emnapi/wasi-threads", + "@napi-rs/wasm-runtime", + "@tybys/wasm-util@0.10.0", + "tslib" + ], + "cpu": ["wasm32"] + }, "@tailwindcss/oxide-win32-arm64-msvc@4.1.11": { "integrity": "sha512-UgKYx5PwEKrac3GPNPf6HVMNhUIGuUh4wlDFR2jYYdkX6pL/rn73zTq/4pzUm8fOjAn5L8zDeHp9iXmUGOXZ+w==", "os": ["win32"], "cpu": ["arm64"] }, + "@tailwindcss/oxide-win32-arm64-msvc@4.1.12": { + "integrity": "sha512-iGLyD/cVP724+FGtMWslhcFyg4xyYyM+5F4hGvKA7eifPkXHRAUDFaimu53fpNg9X8dfP75pXx/zFt/jlNF+lg==", + "os": ["win32"], + "cpu": ["arm64"] + }, "@tailwindcss/oxide-win32-x64-msvc@4.1.11": { "integrity": "sha512-YfHoggn1j0LK7wR82TOucWc5LDCguHnoS879idHekmmiR7g9HUtMw9MI0NHatS28u/Xlkfi9w5RJWgz2Dl+5Qg==", "os": ["win32"], "cpu": ["x64"] }, + "@tailwindcss/oxide-win32-x64-msvc@4.1.12": { + "integrity": "sha512-NKIh5rzw6CpEodv/++r0hGLlfgT/gFN+5WNdZtvh6wpU2BpGNgdjvj6H2oFc8nCM839QM1YOhjpgbAONUb4IxA==", + "os": ["win32"], + "cpu": ["x64"] + }, "@tailwindcss/oxide@4.1.11": { "integrity": "sha512-Q69XzrtAhuyfHo+5/HMgr1lAiPP/G40OMFAnws7xcFEYqcypZmdW8eGXaOUIeOl1dzPJBPENXgbjsOyhg2nkrg==", "dependencies": [ @@ -1384,18 +1471,40 @@ "tar" ], "optionalDependencies": [ - "@tailwindcss/oxide-android-arm64", - "@tailwindcss/oxide-darwin-arm64", - "@tailwindcss/oxide-darwin-x64", - "@tailwindcss/oxide-freebsd-x64", - "@tailwindcss/oxide-linux-arm-gnueabihf", - "@tailwindcss/oxide-linux-arm64-gnu", - "@tailwindcss/oxide-linux-arm64-musl", - "@tailwindcss/oxide-linux-x64-gnu", - "@tailwindcss/oxide-linux-x64-musl", - "@tailwindcss/oxide-wasm32-wasi", - "@tailwindcss/oxide-win32-arm64-msvc", - "@tailwindcss/oxide-win32-x64-msvc" + "@tailwindcss/oxide-android-arm64@4.1.11", + "@tailwindcss/oxide-darwin-arm64@4.1.11", + "@tailwindcss/oxide-darwin-x64@4.1.11", + "@tailwindcss/oxide-freebsd-x64@4.1.11", + "@tailwindcss/oxide-linux-arm-gnueabihf@4.1.11", + "@tailwindcss/oxide-linux-arm64-gnu@4.1.11", + "@tailwindcss/oxide-linux-arm64-musl@4.1.11", + "@tailwindcss/oxide-linux-x64-gnu@4.1.11", + "@tailwindcss/oxide-linux-x64-musl@4.1.11", + "@tailwindcss/oxide-wasm32-wasi@4.1.11", + "@tailwindcss/oxide-win32-arm64-msvc@4.1.11", + "@tailwindcss/oxide-win32-x64-msvc@4.1.11" + ], + "scripts": true + }, + "@tailwindcss/oxide@4.1.12": { + "integrity": "sha512-gM5EoKHW/ukmlEtphNwaGx45fGoEmP10v51t9unv55voWh6WrOL19hfuIdo2FjxIaZzw776/BUQg7Pck++cIVw==", + "dependencies": [ + "detect-libc", + "tar" + ], + "optionalDependencies": [ + "@tailwindcss/oxide-android-arm64@4.1.12", + "@tailwindcss/oxide-darwin-arm64@4.1.12", + "@tailwindcss/oxide-darwin-x64@4.1.12", + "@tailwindcss/oxide-freebsd-x64@4.1.12", + "@tailwindcss/oxide-linux-arm-gnueabihf@4.1.12", + "@tailwindcss/oxide-linux-arm64-gnu@4.1.12", + "@tailwindcss/oxide-linux-arm64-musl@4.1.12", + "@tailwindcss/oxide-linux-x64-gnu@4.1.12", + "@tailwindcss/oxide-linux-x64-musl@4.1.12", + "@tailwindcss/oxide-wasm32-wasi@4.1.12", + "@tailwindcss/oxide-win32-arm64-msvc@4.1.12", + "@tailwindcss/oxide-win32-x64-msvc@4.1.12" ], "scripts": true }, @@ -1403,12 +1512,21 @@ "integrity": "sha512-q/EAIIpF6WpLhKEuQSEVMZNMIY8KhWoAemZ9eylNAih9jxMGAYPPWBn3I9QL/2jZ+e7OEz/tZkX5HwbBR4HohA==", "dependencies": [ "@alloc/quick-lru", - "@tailwindcss/node", - "@tailwindcss/oxide", + "@tailwindcss/node@4.1.11", + "@tailwindcss/oxide@4.1.11", "postcss", "tailwindcss@4.1.11" ] }, + "@tailwindcss/vite@4.1.12_vite@7.1.2__@types+node@24.2.1__picomatch@4.0.3__@types+node@24.2.0_@types+node@24.2.0": { + "integrity": "sha512-4pt0AMFDx7gzIrAOIYgYP0KCBuKWqyW8ayrdiLEjoJTT4pKTjrzG/e4uzWtTLDziC+66R9wbUqZBccJalSE5vQ==", + "dependencies": [ + "@tailwindcss/node@4.1.12", + "@tailwindcss/oxide@4.1.12", + "tailwindcss@4.1.12", + "vite@7.1.2_@types+node@24.2.1_picomatch@4.0.3_@types+node@24.2.0" + ] + }, "@trysound/sax@0.2.0": { "integrity": "sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA==" }, @@ -2775,6 +2893,9 @@ "tailwindcss@4.1.11": { "integrity": "sha512-2E9TBm6MDD/xKYe+dvJZAmg3yxIEDNRc0jwlNyDg/4Fil2QcSLjFKGVff0lAf1jjeaArlG/M75Ey/EYr/OJtBA==" }, + "tailwindcss@4.1.12": { + "integrity": "sha512-DzFtxOi+7NsFf7DBtI3BJsynR+0Yp6etH+nRPTbpWnS2pZBaSksv/JGctNwSWzbFjp0vxSqknaUylseZqMDGrA==" + }, "tapable@2.2.2": { "integrity": "sha512-Re10+NauLTMCudc7T5WLFLAwDhQ0JWdrMK+9B2M8zR5hRExKmsRDCBA7/aV/pNJFltmBFO5BAMlQFi/vq3nKOg==" }, @@ -3138,6 +3259,7 @@ "npm:@babel/core@^7.28.0", "npm:@babel/preset-react@^7.27.1", "npm:@prefresh/vite@^2.4.8", + "npm:@tailwindcss/vite@^4.1.12", "npm:@types/babel__core@^7.20.5", "npm:@types/node@^24.1.0", "npm:mime-db@^1.54.0", diff --git a/packages/fresh/src/build_cache.ts b/packages/fresh/src/build_cache.ts index 3b88e60a..91bb048b 100644 --- a/packages/fresh/src/build_cache.ts +++ b/packages/fresh/src/build_cache.ts @@ -19,6 +19,7 @@ export interface BuildSnapshot { fsRoutes: FsRouteFile[]; staticFiles: Map; islands: ServerIslandRegistry; + entryAssets: string[]; } export interface StaticFile { @@ -39,6 +40,7 @@ export interface BuildCache { }; getFsRoutes(): Command[]; readFile(pathname: string): Promise; + getEntryAssets(): string[]; } export class ProdBuildCache implements BuildCache { @@ -54,6 +56,10 @@ export class ProdBuildCache implements BuildCache { this.clientEntry = snapshot.clientEntry; } + getEntryAssets(): string[] { + return this.#snapshot.entryAssets; + } + getFsRoutes(): Command[] { return fsItemsToCommands(this.#snapshot.fsRoutes); } diff --git a/packages/fresh/src/constants.ts b/packages/fresh/src/constants.ts index 0929f62a..faacb8b4 100644 --- a/packages/fresh/src/constants.ts +++ b/packages/fresh/src/constants.ts @@ -8,3 +8,5 @@ export const MINUTE = SECOND * 60; export const HOUR = MINUTE * 60; export const DAY = HOUR * 24; export const WEEK = DAY * 7; + +export const ASSET_CACHE_BUST_KEY = "__frsh_c"; diff --git a/packages/fresh/src/dev/dev_build_cache.ts b/packages/fresh/src/dev/dev_build_cache.ts index e802309b..fd5795b2 100644 --- a/packages/fresh/src/dev/dev_build_cache.ts +++ b/packages/fresh/src/dev/dev_build_cache.ts @@ -81,6 +81,10 @@ export class MemoryBuildCache implements DevBuildCache { this.clientEntry = getClientEntry(config.buildId); } + getEntryAssets(): string[] { + return []; + } + getFsRoutes(): Command[] { return this.#commands; } @@ -247,6 +251,10 @@ export class DiskBuildCache implements DevBuildCache { this.root = config.root; } + getEntryAssets(): string[] { + return []; + } + getFsRoutes(): Command[] { return []; } @@ -357,6 +365,7 @@ export class DiskBuildCache implements DevBuildCache { }, fsRoutesFiles: this.#fsRoutes.files, outDir: root, + entryAssets: [], }), ); @@ -422,6 +431,7 @@ export async function generateSnapshotServer( // deno-lint-ignore no-explicit-any fsRoutesFiles: FsRouteFileNoMod[]; staticFiles: PendingStaticFile[]; + entryAssets: string[]; writeSpecifier: (filePath: string) => string; }, ): Promise { @@ -475,21 +485,13 @@ export async function generateSnapshotServer( const staticFiles = await Promise.all( options.staticFiles.map(async (item) => { - const file = await Deno.open(item.filePath); - const hash = item.hash ? item.hash : await hashContent(file.readable); - const url = new URL(item.pathname, "http://localhost"); - - return { - name: url.pathname, - hash, - filePath: path.isAbsolute(item.filePath) - ? path.relative(outDir, item.filePath) - : item.filePath, - contentType: getContentType(item.filePath), - }; + return await prepareStaticFile(item, outDir); }), ); + const entryAssets = options.entryAssets.map((url) => JSON.stringify(url)) + .join(",\n"); + return `${EDIT_WARNING} import { IslandPreparer } from "fresh/internal"; ${islandImports} @@ -510,12 +512,34 @@ ${ } ]); +export const entryAssets = [${entryAssets}]; + export const fsRoutes = [ ${serializedFsRoutes} ]; `.replaceAll(/\n[\n]+/g, "\n\n"); } +export async function prepareStaticFile( + item: PendingStaticFile, + outDir: string, +): Promise< + { name: string; hash: string; filePath: string; contentType: string } +> { + const file = await Deno.open(item.filePath); + const hash = item.hash ? item.hash : await hashContent(file.readable); + const url = new URL(item.pathname, "http://localhost"); + + return { + name: url.pathname, + hash, + filePath: path.isAbsolute(item.filePath) + ? path.relative(outDir, item.filePath) + : item.filePath, + contentType: getContentType(item.filePath), + }; +} + export function generateServerEntry( options: { root: string; diff --git a/packages/fresh/src/internals.ts b/packages/fresh/src/internals.ts index f2dcd2fb..eaf79f94 100644 --- a/packages/fresh/src/internals.ts +++ b/packages/fresh/src/internals.ts @@ -3,3 +3,4 @@ import * as path from "@std/path"; export { setBuildCache } from "./app.ts"; export { IslandPreparer, ProdBuildCache } from "./build_cache.ts"; export { path }; +export { ASSET_CACHE_BUST_KEY } from "./constants.ts"; diff --git a/packages/fresh/src/internals_dev.ts b/packages/fresh/src/internals_dev.ts index 27ba8825..930f1860 100644 --- a/packages/fresh/src/internals_dev.ts +++ b/packages/fresh/src/internals_dev.ts @@ -6,6 +6,7 @@ export { generateSnapshotServer, type IslandModChunk, type PendingStaticFile, + prepareStaticFile, } from "./dev/dev_build_cache.ts"; export { specToName } from "./dev/builder.ts"; export { pathToSpec, UniqueNamer } from "./utils.ts"; diff --git a/packages/fresh/src/middlewares/static_files.ts b/packages/fresh/src/middlewares/static_files.ts index a26a83a8..6f0c4cac 100644 --- a/packages/fresh/src/middlewares/static_files.ts +++ b/packages/fresh/src/middlewares/static_files.ts @@ -1,5 +1,5 @@ import type { Middleware } from "./mod.ts"; -import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx"; +import { ASSET_CACHE_BUST_KEY } from "../constants.ts"; import { BUILD_ID } from "@fresh/build-id"; import { tracer } from "../otel.ts"; import { getBuildCache } from "../context.ts"; diff --git a/packages/fresh/src/middlewares/static_files_test.ts b/packages/fresh/src/middlewares/static_files_test.ts index 09a70983..b50a8741 100644 --- a/packages/fresh/src/middlewares/static_files_test.ts +++ b/packages/fresh/src/middlewares/static_files_test.ts @@ -2,7 +2,7 @@ import { staticFiles } from "./static_files.ts"; import { serveMiddleware } from "../test_utils.ts"; import type { BuildCache, StaticFile } from "../build_cache.ts"; import { expect } from "@std/expect"; -import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx"; +import { ASSET_CACHE_BUST_KEY } from "../constants.ts"; import { BUILD_ID } from "@fresh/build-id"; import type { Command } from "../commands.ts"; import type { ServerIslandRegistry } from "../context.ts"; @@ -32,6 +32,10 @@ class MockBuildCache implements BuildCache { } } + getEntryAssets(): string[] { + return []; + } + // deno-lint-ignore no-explicit-any getFsRoutes(): Command[] { return []; diff --git a/packages/fresh/src/render.ts b/packages/fresh/src/render.ts index 5588492d..f6bf6262 100644 --- a/packages/fresh/src/render.ts +++ b/packages/fresh/src/render.ts @@ -14,6 +14,7 @@ import type { Context } from "./context.ts"; import { recordSpanError, tracer } from "./otel.ts"; import { DEV_ERROR_OVERLAY_URL } from "./constants.ts"; import { renderToString } from "preact-render-to-string"; +import { escape as escapeHtml } from "@std/html"; export type AsyncAnyComponent

= { ( @@ -74,7 +75,18 @@ export function preactRender( res = `${res}${scripts}`; } if (!state.renderedHtmlHead) { - res = `${res}`; + let head = ``; + + const entryAssets = state.buildCache.getEntryAssets(); + for (let i = 0; i < entryAssets.length; i++) { + const asset = entryAssets[i]; + + if (asset.endsWith(".css")) { + head += ``; + } + } + + res = `${head}${res}`; } if (!state.renderedHtmlTag) { res = `${res}`; diff --git a/packages/fresh/src/runtime/server/preact_hooks.tsx b/packages/fresh/src/runtime/server/preact_hooks.tsx index 4a560ccb..91241d72 100644 --- a/packages/fresh/src/runtime/server/preact_hooks.tsx +++ b/packages/fresh/src/runtime/server/preact_hooks.tsx @@ -12,7 +12,7 @@ import { import type { ReadonlySignal, Signal } from "@preact/signals"; import type { Stringifiers } from "../../jsonify/stringify.ts"; import type { PageProps } from "../../render.ts"; -import { Partial, type PartialProps } from "../shared.ts"; +import { asset, Partial, type PartialProps } from "../shared.ts"; import { stringify } from "../../jsonify/stringify.ts"; import type { Island } from "../../context.ts"; import { @@ -255,9 +255,39 @@ options[OptionsType.DIFF] = (vnode) => { case "html": RENDER_STATE!.renderedHtmlTag = true; break; - case "head": + case "head": { RENDER_STATE!.renderedHtmlHead = true; + + const entryAssets = RENDER_STATE.buildCache.getEntryAssets(); + if (entryAssets.length > 0) { + const items: VNode[] = []; + for (let i = 0; i < entryAssets.length; i++) { + const id = entryAssets[i]; + + if (id.endsWith(".css")) { + items.push( + // deno-lint-ignore no-explicit-any + h("link", { rel: "stylesheet", href: asset(id) } as any), + ); + } + } + + if (Array.isArray(vnode.props.children)) { + vnode.props.children.push(...items); + } else if ( + vnode.props.children !== null && + typeof vnode.props.children === "object" + ) { + // deno-lint-ignore no-explicit-any + items.push(vnode.props.children as any); + vnode.props.children = items; + } else { + vnode.props.children = items; + } + } + break; + } case "body": RENDER_STATE!.renderedHtmlBody = true; break; @@ -487,7 +517,6 @@ function FreshRuntimeScript() { { json: true }, ); - // const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`; const runtimeUrl = buildCache.clientEntry.startsWith(".") ? buildCache.clientEntry.slice(1) : buildCache.clientEntry; diff --git a/packages/fresh/src/runtime/shared_internal.tsx b/packages/fresh/src/runtime/shared_internal.tsx index 9ee40d76..396a8dcb 100644 --- a/packages/fresh/src/runtime/shared_internal.tsx +++ b/packages/fresh/src/runtime/shared_internal.tsx @@ -1,10 +1,10 @@ import type { VNode } from "preact"; +import { ASSET_CACHE_BUST_KEY } from "../constants.ts"; export const DATA_CURRENT = "data-current"; export const DATA_ANCESTOR = "data-ancestor"; export const DATA_FRESH_KEY = "data-frsh-key"; export const CLIENT_NAV_ATTR = "f-client-nav"; -export const ASSET_CACHE_BUST_KEY = "__frsh_c"; export const enum UrlMatchKind { None, diff --git a/packages/fresh/src/test_utils.ts b/packages/fresh/src/test_utils.ts index df87a82d..70237b15 100644 --- a/packages/fresh/src/test_utils.ts +++ b/packages/fresh/src/test_utils.ts @@ -163,6 +163,10 @@ export class MockBuildCache implements BuildCache { this.#files = files; } + getEntryAssets(): string[] { + return []; + } + getFsRoutes(): Command[] { return fsItemsToCommands(this.#files); } diff --git a/packages/plugin-vite/demo/assets/deno-logo.png b/packages/plugin-vite/demo/assets/deno-logo.png new file mode 100644 index 00000000..7b586311 Binary files /dev/null and b/packages/plugin-vite/demo/assets/deno-logo.png differ diff --git a/packages/plugin-vite/demo/assets/style.css b/packages/plugin-vite/demo/assets/style.css new file mode 100644 index 00000000..f1d8c73c --- /dev/null +++ b/packages/plugin-vite/demo/assets/style.css @@ -0,0 +1 @@ +@import "tailwindcss"; diff --git a/packages/plugin-vite/demo/client.ts b/packages/plugin-vite/demo/client.ts new file mode 100644 index 00000000..aac395dd --- /dev/null +++ b/packages/plugin-vite/demo/client.ts @@ -0,0 +1 @@ +import "./assets/style.css"; diff --git a/packages/plugin-vite/demo/islands/tests/IslandAssets.tsx b/packages/plugin-vite/demo/islands/tests/IslandAssets.tsx new file mode 100644 index 00000000..7dad8ee3 --- /dev/null +++ b/packages/plugin-vite/demo/islands/tests/IslandAssets.tsx @@ -0,0 +1,5 @@ +import logo from "../../assets/deno-logo.png"; + +export function IslandAssets() { + return ; +} diff --git a/packages/plugin-vite/demo/routes/tests/assets.tsx b/packages/plugin-vite/demo/routes/tests/assets.tsx new file mode 100644 index 00000000..a6df3689 --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/assets.tsx @@ -0,0 +1,5 @@ +import logo from "../../assets/deno-logo.png"; + +export default function Page() { + return ; +} diff --git a/packages/plugin-vite/demo/routes/tests/island_assets.tsx b/packages/plugin-vite/demo/routes/tests/island_assets.tsx new file mode 100644 index 00000000..2b11c1fa --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/island_assets.tsx @@ -0,0 +1,5 @@ +import { IslandAssets } from "../../islands/tests/IslandAssets.tsx"; + +export default function Page() { + return ; +} diff --git a/packages/plugin-vite/demo/routes/tests/tailwind.tsx b/packages/plugin-vite/demo/routes/tests/tailwind.tsx new file mode 100644 index 00000000..a869dfb9 --- /dev/null +++ b/packages/plugin-vite/demo/routes/tests/tailwind.tsx @@ -0,0 +1,3 @@ +export default function Page() { + return

this should be red

; +} diff --git a/packages/plugin-vite/demo/vite.config.ts b/packages/plugin-vite/demo/vite.config.ts index 653f850e..c52dc3e3 100644 --- a/packages/plugin-vite/demo/vite.config.ts +++ b/packages/plugin-vite/demo/vite.config.ts @@ -1,10 +1,12 @@ import { defineConfig } from "vite"; import { fresh } from "@fresh/plugin-vite"; import inspect from "vite-plugin-inspect"; +import tailwind from "@tailwindcss/vite"; export default defineConfig({ plugins: [ inspect(), fresh(), + tailwind(), ], }); diff --git a/packages/plugin-vite/deno.json b/packages/plugin-vite/deno.json index 810b0ad9..9f670f0a 100644 --- a/packages/plugin-vite/deno.json +++ b/packages/plugin-vite/deno.json @@ -23,6 +23,7 @@ "@babel/preset-react": "npm:@babel/preset-react@^7.27.1", "@deno/loader": "jsr:@deno/loader@^0.3.2", "@prefresh/vite": "npm:@prefresh/vite@^2.4.8", + "@tailwindcss/vite": "npm:@tailwindcss/vite@^4.1.12", "@types/babel__core": "npm:@types/babel__core@^7.20.5", "@types/node": "npm:@types/node@^24.1.0", "mime-db": "npm:mime-db@^1.54.0", diff --git a/packages/plugin-vite/src/mod.ts b/packages/plugin-vite/src/mod.ts index 5161579d..8dab3e81 100644 --- a/packages/plugin-vite/src/mod.ts +++ b/packages/plugin-vite/src/mod.ts @@ -17,6 +17,7 @@ import { patches } from "./plugins/patches.ts"; export function fresh(config?: FreshViteConfig): Plugin[] { const fConfig: ResolvedFreshViteConfig = { serverEntry: config?.serverEntry ?? "main.ts", + clientEntry: config?.clientEntry ?? "client.ts", islandsDir: config?.islandsDir ?? "islands", routeDir: config?.routeDir ?? "routes", ignore: config?.ignore ?? [], @@ -86,6 +87,7 @@ export function fresh(config?: FreshViteConfig): Plugin[] { ssr: { build: { manifest: true, + emitAssets: true, copyPublicDir: false, outDir: config.environments?.ssr?.build?.outDir ?? @@ -108,7 +110,7 @@ export function fresh(config?: FreshViteConfig): Plugin[] { serverEntryPlugin(fConfig), patches(), ...serverSnapshot(fConfig), - clientEntryPlugin(), + clientEntryPlugin(fConfig), clientSnapshot(fConfig), buildIdPlugin(), ...devServer(), diff --git a/packages/plugin-vite/src/plugins/client_entry.ts b/packages/plugin-vite/src/plugins/client_entry.ts index 45c6a3d3..f821be3b 100644 --- a/packages/plugin-vite/src/plugins/client_entry.ts +++ b/packages/plugin-vite/src/plugins/client_entry.ts @@ -1,22 +1,40 @@ import type { Plugin } from "vite"; +import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts"; -export function clientEntryPlugin(): Plugin { +export function clientEntryPlugin(options: ResolvedFreshViteConfig): Plugin { const modName = "fresh:client-entry"; + const modNameUser = "fresh:client-entry-user"; + + let clientEntry = ""; return { name: "fresh:client-entry", applyToEnvironment(env) { return env.name === "client"; }, + configResolved(config) { + clientEntry = pathWithRoot(options.clientEntry, config.root); + }, resolveId(id) { if (id === modName) { return `\0${modName}`; + } else if (id === modNameUser) { + return clientEntry; } }, - load(id) { + async load(id) { if (id !== `\0${modName}`) return; + let exists = false; + try { + const stat = await Deno.stat(clientEntry); + exists = stat.isFile; + } catch { + exists = false; + } + return `export * from "fresh/runtime-client"; +${exists ? `import "fresh:client-entry-user";` : ""} if (import.meta.hot) { import.meta.hot.accept(() => { diff --git a/packages/plugin-vite/src/plugins/deno.ts b/packages/plugin-vite/src/plugins/deno.ts index 1c0476ec..8834c44e 100644 --- a/packages/plugin-vite/src/plugins/deno.ts +++ b/packages/plugin-vite/src/plugins/deno.ts @@ -8,6 +8,7 @@ import { import * as path from "@std/path"; import * as babel from "@babel/core"; import babelReact from "@babel/preset-react"; +import { httpAbsolute } from "./patches/http_absolute.ts"; interface DenoState { type: RequestedModuleType; @@ -43,17 +44,30 @@ export function deno(): Plugin { async resolveId(id, importer, options) { const loader = options?.ssr ? ssrLoader : browserLoader; + const original = id; + + let isHttp = false; + if (id.startsWith("deno-http::")) { + isHttp = true; + id = id.slice("deno-http::".length); + } + importer = isDenoSpecifier(importer) ? parseDenoSpecifier(importer).specifier : importer; + if (id.startsWith("/") && importer && /^https?:\/\//g.test(importer)) { + const url = new URL(importer); + id = `${url.origin}${id}`; + } + // We still want to allow other plugins to participate in // resolution, with us being in front due to `enforce: "pre"`. // But we still want to ignore everything `vite:resolve` does // because we're kinda replacing that plugin here. const tmp = await this.resolve(id, importer, options); if (tmp && tmp.resolvedBy !== "vite:resolve") { - if (tmp.external) { + if (tmp.external && !/^https?:\/\//.test(tmp.id)) { return tmp; } @@ -66,7 +80,7 @@ export function deno(): Plugin { } // Plugins may return lower cased drive letters on windows - if (path.isAbsolute(id)) { + if (!isHttp && path.isAbsolute(id)) { id = path.toFileUrl(path.normalize(id)) .href; } @@ -83,7 +97,7 @@ export function deno(): Plugin { ResolutionMode.Import, ); - if (id === resolved) { + if (original === resolved) { return null; } @@ -124,7 +138,7 @@ export function deno(): Plugin { const code = new TextDecoder().decode(result.code); - const maybeJsx = maybeTransformJsxBrowser({ + const maybeJsx = babelTransform({ ssr: !!options?.ssr, code, id: specifier, @@ -150,6 +164,14 @@ export function deno(): Plugin { if (meta === null || meta === undefined) return; + // Skip for non-js files like `.css` + if ( + meta.type === RequestedModuleType.Default && + !/\.([tj]sx?|[mc]?[tj]s)$/.test(id) + ) { + return; + } + const url = path.toFileUrl(id); const result = await loader.load(url.href, meta.type); @@ -159,7 +181,7 @@ export function deno(): Plugin { const code = new TextDecoder().decode(result.code); - const maybeJsx = maybeTransformJsxBrowser({ + const maybeJsx = babelTransform({ ssr: !!options?.ssr, id, code, @@ -263,31 +285,44 @@ function getDenoType(id: string, type: string): RequestedModuleType { } } -function maybeTransformJsxBrowser( +function babelTransform( options: { ssr: boolean; code: string; id: string; isDev: boolean }, ) { + if ( + !/\.([tj]sx?|[mc[jt]s)$/.test(options.id) && + !/^https?:\/\//.test(options.id) + ) { + return null; + } + const { ssr, code, id, isDev } = options; + const presets: babel.PluginItem[] = []; if ( !ssr && id.endsWith(".tsx") || id.endsWith(".jsx") ) { - const babelResult = babel.transformSync(code, { - filename: id, - babelrc: false, - sourceMaps: "inline", - presets: [[babelReact, { - runtime: "automatic", - importSource: "preact", - development: isDev, - }]], - }); + presets.push([babelReact, { + runtime: "automatic", + importSource: "preact", + development: isDev, + }]); + } - if (babelResult !== null && babelResult.code) { - return { - code: babelResult.code, - map: babelResult.map, - }; - } + const url = URL.canParse(id) ? new URL(id) : null; + + const result = babel.transformSync(code, { + filename: id, + babelrc: false, + sourceMaps: "inline", + presets: presets, + plugins: [httpAbsolute(url)], + }); + + if (result !== null && result.code) { + return { + code: result.code, + map: result.map, + }; } return null; diff --git a/packages/plugin-vite/src/plugins/dev_server.ts b/packages/plugin-vite/src/plugins/dev_server.ts index 5e630209..b645fd4a 100644 --- a/packages/plugin-vite/src/plugins/dev_server.ts +++ b/packages/plugin-vite/src/plugins/dev_server.ts @@ -1,17 +1,12 @@ import type { Plugin } from "vite"; import { nodeToRequest, responseToNode } from "../request.ts"; import * as path from "@std/path"; -import { pathWithRoot } from "../utils.ts"; +import { ASSET_CACHE_BUST_KEY } from "fresh/internal"; export function devServer(): Plugin[] { - let publicDir = ""; - return [ { name: "fresh:dev_server", - configResolved(cfg) { - publicDir = pathWithRoot(cfg.publicDir, cfg.root); - }, configureServer(server) { const IGNORE_URLS = /^\/(@(vite|fs|id)|\.vite)\//; @@ -25,26 +20,25 @@ export function devServer(): Plugin[] { `${protocol}://${host}:${port}${nodeReq.url ?? "/"}`, ); + // Don't cache in dev + url.searchParams.delete(ASSET_CACHE_BUST_KEY); + // Check if it's a vite url if ( IGNORE_URLS.test(url.pathname) || server.environments.client.moduleGraph.urlToModuleMap.has( url.pathname, - ) + ) || + url.pathname === "/.well-known/appspecific/com.chrome.devtools.json" ) { return next(); } // Check if it's a static file first - // FIXME: Should this still go through fresh? if (url.pathname !== "/") { - try { - await Deno.stat(path.join(publicDir, url.pathname)); + const ext = path.extname(url.pathname); + if (ext !== "") { return next(); - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - return next(err); - } } } @@ -72,6 +66,17 @@ export function devServer(): Plugin[] { if (clientMod === undefined) { options.server.hot.send("fresh:reload"); + return; + } + + const ssrMod = options.server.environments.ssr.moduleGraph + .getModulesByFile(options.file); + if (ssrMod !== undefined) { + // SSR-only module. Might still be a route. + // deno-lint-ignore no-console + console.log("hmr", options.file); + + options.server.hot.send("fresh:reload"); } }, }, diff --git a/packages/plugin-vite/src/plugins/patches.ts b/packages/plugin-vite/src/plugins/patches.ts index d11b902e..841295df 100644 --- a/packages/plugin-vite/src/plugins/patches.ts +++ b/packages/plugin-vite/src/plugins/patches.ts @@ -17,6 +17,8 @@ export function patches(): Plugin { return true; }, transform(code, id, options) { + if (!/\.([tj]sx?|[mc][tj]s)$/.test(id)) return; + const presets = []; if (!options?.ssr && /\.(tsx?|m[jt]s)$/.test(id)) { presets.push([babelReact, { diff --git a/packages/plugin-vite/src/plugins/patches/commonjs.ts b/packages/plugin-vite/src/plugins/patches/commonjs.ts index d76e4b39..c6e49350 100644 --- a/packages/plugin-vite/src/plugins/patches/commonjs.ts +++ b/packages/plugin-vite/src/plugins/patches/commonjs.ts @@ -1,8 +1,8 @@ -import type { types } from "@babel/core"; +import type { PluginObj, types } from "@babel/core"; export function cjsPlugin( { types: t }: { types: typeof types }, -): babel.PluginObj { +): PluginObj { const HAS_ES_MODULE = "esModule"; const REQUIRE_CALLS = "requireCalls"; const ROOT_SCOPE = "rootScope"; diff --git a/packages/plugin-vite/src/plugins/patches/http_absolute.ts b/packages/plugin-vite/src/plugins/patches/http_absolute.ts new file mode 100644 index 00000000..33e96e82 --- /dev/null +++ b/packages/plugin-vite/src/plugins/patches/http_absolute.ts @@ -0,0 +1,66 @@ +import type { + NodePath, + PluginObj, + PluginPass, + types, + Visitor, +} from "@babel/core"; + +function maybeRewrite( + t: typeof types, + path: NodePath, + source: string, + url: URL, +) { + if (source.startsWith("/")) { + const s = `deno-http::${url.origin}${source}`; + path.replaceWith(t.stringLiteral(s)); + } else if (/^https?:\/\//.test(source)) { + const s = `deno-http::${source}`; + path.replaceWith(t.stringLiteral(s)); + } +} + +export function httpAbsolute(url: URL | null) { + return ({ types: t }: { types: typeof types }): PluginObj => { + const visitor: Visitor = url !== null + ? { + ImportDeclaration(path) { + const source = path.node.source.value; + maybeRewrite(t, path.get("source"), source, url); + }, + ExportAllDeclaration(path) { + const source = path.node.source.value; + maybeRewrite(t, path.get("source"), source, url); + }, + ExportNamedDeclaration(path) { + if (!path.node.source) return; + + const source = path.node.source.value; + // deno-lint-ignore no-explicit-any + maybeRewrite(t, path.get("source") as any, source, url); + }, + CallExpression(path) { + if ( + t.isImport(path.node.callee) && path.node.arguments.length > 0 && + t.isStringLiteral(path.node.arguments[0]) + ) { + const source = path.node.arguments[0].value; + maybeRewrite( + t, + path + .get("arguments")[0], + source, + url, + ); + } + }, + } + : {}; + + return { + name: "fresh-http-absolute", + visitor, + }; + }; +} diff --git a/packages/plugin-vite/src/plugins/patches/http_absolute_test.ts b/packages/plugin-vite/src/plugins/patches/http_absolute_test.ts new file mode 100644 index 00000000..7f55b9a2 --- /dev/null +++ b/packages/plugin-vite/src/plugins/patches/http_absolute_test.ts @@ -0,0 +1,46 @@ +import { expect } from "@std/expect/expect"; +import * as babel from "@babel/core"; +import { httpAbsolute } from "./http_absolute.ts"; + +function runTest(options: { input: string; expected: string; url?: URL }) { + const res = babel.transformSync(options.input, { + filename: "foo.js", + babelrc: false, + plugins: [httpAbsolute(options.url ?? null)], + }); + + const output = res?.code ?? ""; + expect(output).toEqual(options.expected); +} + +Deno.test("http absolute - change import sources", () => { + runTest({ + input: `import foo from "/foo.js"`, + expected: `import foo from "deno-http::http://localhost/foo.js";`, + url: new URL("http://localhost"), + }); +}); + +Deno.test("http absolute - change export all sources", () => { + runTest({ + input: `export * as foo from "/foo.js"`, + expected: `export * as foo from "deno-http::http://localhost/foo.js";`, + url: new URL("http://localhost"), + }); +}); + +Deno.test("http absolute - change export sources", () => { + runTest({ + input: `export { foo } from "/foo.js"`, + expected: `export { foo } from "deno-http::http://localhost/foo.js";`, + url: new URL("http://localhost"), + }); +}); + +Deno.test("http absolute - change import()", () => { + runTest({ + input: `import("/foo.js")`, + expected: `import("deno-http::http://localhost/foo.js");`, + url: new URL("http://localhost"), + }); +}); diff --git a/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts b/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts index 9f0f557c..df73d5f5 100644 --- a/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts +++ b/packages/plugin-vite/src/plugins/patches/inline_env_vars.ts @@ -1,4 +1,4 @@ -import type { NodePath, types } from "@babel/core"; +import type { NodePath, PluginObj, types } from "@babel/core"; export function inlineEnvVarsPlugin(mode: string) { const allowed = new Map(); @@ -12,7 +12,7 @@ export function inlineEnvVarsPlugin(mode: string) { return ( { types: t }: { types: typeof types }, - ): babel.PluginObj => { + ): PluginObj => { function replace(path: NodePath, name: string) { if (allowed.has(name)) { const value = allowed.get(name); diff --git a/packages/plugin-vite/src/plugins/patches/jsx_comment.ts b/packages/plugin-vite/src/plugins/patches/jsx_comment.ts index 5034246d..18b63be9 100644 --- a/packages/plugin-vite/src/plugins/patches/jsx_comment.ts +++ b/packages/plugin-vite/src/plugins/patches/jsx_comment.ts @@ -1,6 +1,6 @@ -import type { types } from "@babel/core"; +import type { PluginObj, types } from "@babel/core"; -export function jsxComments(): babel.PluginObj { +export function jsxComments(): PluginObj { return { name: "fresh-jsx-comment", visitor: { diff --git a/packages/plugin-vite/src/plugins/server_entry.ts b/packages/plugin-vite/src/plugins/server_entry.ts index ad8b6c97..6b3be675 100644 --- a/packages/plugin-vite/src/plugins/server_entry.ts +++ b/packages/plugin-vite/src/plugins/server_entry.ts @@ -1,5 +1,9 @@ -import type { Plugin } from "vite"; -import { generateServerEntry } from "fresh/internal-dev"; +import type { Manifest, Plugin } from "vite"; +import { + generateServerEntry, + type PendingStaticFile, + prepareStaticFile, +} from "fresh/internal-dev"; import { pathWithRoot, type ResolvedFreshViteConfig } from "../utils.ts"; import * as path from "@std/path"; @@ -10,6 +14,7 @@ export function serverEntryPlugin( let serverEntry = ""; let serverOutDir = ""; + let clientOutDir = ""; let root = ""; let isDev = false; @@ -29,6 +34,10 @@ export function serverEntryPlugin( config.environments.ssr.build.outDir, config.root, ); + clientOutDir = pathWithRoot( + config.environments.client.build.outDir, + config.root, + ); }, resolveId(id) { if (id === modName) { @@ -39,22 +48,71 @@ export function serverEntryPlugin( if (id !== `\0${modName}`) return; let code = generateServerEntry({ - root: path.relative(serverOutDir, root), + root: isDev ? path.relative(serverOutDir, root) : "..", serverEntry: path.toFileUrl(serverEntry).href, snapshotSpecifier: "fresh:server-snapshot", }); + code += ` + +export function registerStaticFile(prepared) { + snapshot.staticFiles.set(prepared.name, { + name: prepared.name, + contentType: prepared.contentType, + filePath: prepared.filePath + }); +} +`; + if (isDev) { code += `if (import.meta.hot) import.meta.hot.accept();\n`; } return code; }, - async writeBundle() { + async writeBundle(_options, bundle) { + const manifest = bundle[".vite/manifest.json"]; + + const staticFiles: PendingStaticFile[] = []; + if ( + manifest && manifest.type === "asset" && + typeof manifest.source === "string" + ) { + const json = JSON.parse(manifest.source) as Manifest; + + for (const item of Object.values(json)) { + if (item.assets) { + for (let i = 0; i < item.assets.length; i++) { + const id = item.assets[i]; + + staticFiles.push({ + filePath: path.join(serverOutDir, id), + hash: null, + pathname: `/${id}`, + }); + } + } + } + } + + const registered = await Promise.all(staticFiles.map(async (file) => { + const prepared = await prepareStaticFile(file, serverOutDir); + const rel = path.relative(serverOutDir, file.filePath); + const target = path.join(clientOutDir, rel); + await Deno.rename(file.filePath, target); + + prepared.filePath = path.join("client", prepared.filePath); + + return `registerStaticFile(${JSON.stringify(prepared)});`; + })); + const outDir = path.dirname(serverOutDir); await Deno.writeTextFile( path.join(outDir, "server.js"), - `import server from "./server/server-entry.mjs"; + `import server, { registerStaticFile } from "./server/server-entry.mjs"; + +${registered.join("\n")} + export default { fetch: server.fetch }; diff --git a/packages/plugin-vite/src/plugins/server_snapshot.ts b/packages/plugin-vite/src/plugins/server_snapshot.ts index 90c95db0..5c35513e 100644 --- a/packages/plugin-vite/src/plugins/server_snapshot.ts +++ b/packages/plugin-vite/src/plugins/server_snapshot.ts @@ -77,6 +77,7 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] { let islandMods: IslandModChunk[] = []; let clientEntry = "/@id/fresh:client-entry"; let buildId = ""; + const entryAssets: string[] = []; if (isDev && server !== undefined) { for (const id of islands.keys()) { @@ -104,8 +105,10 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] { ), ) as Manifest; + const clientEntryName = "client-entry"; + for (const chunk of Object.values(manifest)) { - if (chunk.name === "client-entry") { + if (chunk.name === clientEntryName) { clientEntry = pathToSpec(clientOutDir, chunk.file); } @@ -115,6 +118,24 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] { hash: null, }); + 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 ?? []) { @@ -165,10 +186,11 @@ export function serverSnapshot(options: ResolvedFreshViteConfig): Plugin[] { } const code = await generateSnapshotServer({ - outDir: root, + outDir: path.join(clientOutDir, ".."), staticFiles, buildId, clientEntry, + entryAssets, fsRoutesFiles: result.routes, islands: islandMods, writeSpecifier: (file) => { diff --git a/packages/plugin-vite/src/utils.ts b/packages/plugin-vite/src/utils.ts index 0b231760..48dbb56c 100644 --- a/packages/plugin-vite/src/utils.ts +++ b/packages/plugin-vite/src/utils.ts @@ -33,6 +33,7 @@ export interface ClientSnapshot { export interface FreshViteConfig { serverEntry?: string; + clientEntry?: string; islandsDir?: string; routeDir?: string; ignore?: RegExp[]; diff --git a/packages/plugin-vite/tests/build_test.ts b/packages/plugin-vite/tests/build_test.ts index ae50c098..f0e1ae8b 100644 --- a/packages/plugin-vite/tests/build_test.ts +++ b/packages/plugin-vite/tests/build_test.ts @@ -167,3 +167,102 @@ Deno.test({ sanitizeOps: false, sanitizeResources: false, }); + +Deno.test({ + name: "vite build - fetch static assets", + fn: async () => { + await using res = await buildVite(DEMO_DIR); + + await withChildProcessServer( + { + cwd: res.tmp, + args: ["serve", "-A", "--port", "0", "_fresh/server.js"], + }, + async (address) => { + await withBrowser(async (page) => { + await page.goto(`${address}/tests/assets`, { + waitUntil: "networkidle2", + }); + + const url = await page.locator("img").evaluate((el) => + // deno-lint-ignore no-explicit-any + (el as any).src + ); + + const res = await fetch(url); + await res.body?.cancel(); + expect(res.status).toEqual(200); + expect(res.headers.get("Content-Type")).toEqual("image/png"); + }); + }, + ); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "vite build - tailwind no _app", + fn: async () => { + const fixture = path.join(FIXTURE_DIR, "tailwind_no_app"); + await using res = await buildVite(fixture); + + await withChildProcessServer( + { + cwd: res.tmp, + args: ["serve", "-A", "--port", "0", "_fresh/server.js"], + }, + async (address) => { + await withBrowser(async (page) => { + await page.goto(`${address}`, { + waitUntil: "networkidle2", + }); + + const href = await page + .locator("link[rel='stylesheet']") + .evaluate((el) => { + // deno-lint-ignore no-explicit-any + return (el as any).href; + }); + + expect(href).toMatch(/\/assets\/client-entry-.*\.css$/); + }); + }, + ); + }, + sanitizeOps: false, + sanitizeResources: false, +}); + +Deno.test({ + name: "vite build - tailwind _app", + fn: async () => { + const fixture = path.join(FIXTURE_DIR, "tailwind_app"); + await using res = await buildVite(fixture); + + await withChildProcessServer( + { + cwd: res.tmp, + args: ["serve", "-A", "--port", "0", "_fresh/server.js"], + }, + async (address) => { + await withBrowser(async (page) => { + await page.goto(`${address}`, { + waitUntil: "networkidle2", + }); + + const href = await page + .locator("link[rel='stylesheet']") + .evaluate((el) => { + // deno-lint-ignore no-explicit-any + return (el as any).href; + }); + + expect(href).toMatch(/\/assets\/client-entry-.*\.css/); + }); + }, + ); + }, + sanitizeOps: false, + sanitizeResources: false, +}); diff --git a/packages/plugin-vite/tests/dev_server_test.ts b/packages/plugin-vite/tests/dev_server_test.ts index 0f18fe24..af0c02d1 100644 --- a/packages/plugin-vite/tests/dev_server_test.ts +++ b/packages/plugin-vite/tests/dev_server_test.ts @@ -167,3 +167,52 @@ Deno.test({ sanitizeResources: false, sanitizeOps: false, }); + +Deno.test({ + name: "vite dev - serves imported assets", + fn: async () => { + await withDevServer(DEMO_DIR, async (address) => { + const res = await fetch(`${address}/assets/deno-logo.png`); + expect(res.status).toEqual(200); + expect(res.headers.get("Content-Type")).toEqual("image/png"); + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "vite dev - tailwind no _app", + fn: async () => { + const fixture = path.join(FIXTURE_DIR, "tailwind_no_app"); + await withDevServer(fixture, async (address) => { + await withBrowser(async (page) => { + await page.goto(`${address}`, { + waitUntil: "networkidle2", + }); + + await page.locator("style[data-vite-dev-id$='style.css']").wait(); + }); + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); + +Deno.test({ + name: "vite dev - tailwind _app", + fn: async () => { + const fixture = path.join(FIXTURE_DIR, "tailwind_app"); + await withDevServer(fixture, async (address) => { + await withBrowser(async (page) => { + await page.goto(`${address}`, { + waitUntil: "networkidle2", + }); + + await page.locator("style[data-vite-dev-id$='style.css']").wait(); + }); + }); + }, + sanitizeResources: false, + sanitizeOps: false, +}); diff --git a/packages/plugin-vite/tests/fixtures/tailwind_app/assets/style.css b/packages/plugin-vite/tests/fixtures/tailwind_app/assets/style.css new file mode 100644 index 00000000..f1d8c73c --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_app/assets/style.css @@ -0,0 +1 @@ +@import "tailwindcss"; diff --git a/packages/plugin-vite/tests/fixtures/tailwind_app/client.ts b/packages/plugin-vite/tests/fixtures/tailwind_app/client.ts new file mode 100644 index 00000000..aac395dd --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_app/client.ts @@ -0,0 +1 @@ +import "./assets/style.css"; diff --git a/packages/plugin-vite/tests/fixtures/tailwind_app/main.ts b/packages/plugin-vite/tests/fixtures/tailwind_app/main.ts new file mode 100644 index 00000000..d98e91b1 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_app/main.ts @@ -0,0 +1,3 @@ +import { App } from "@fresh/core"; + +export const app = new App().fsRoutes(); diff --git a/packages/plugin-vite/tests/fixtures/tailwind_app/routes/_app.tsx b/packages/plugin-vite/tests/fixtures/tailwind_app/routes/_app.tsx new file mode 100644 index 00000000..426e4206 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_app/routes/_app.tsx @@ -0,0 +1,14 @@ +import type { PageProps } from "@fresh/core"; + +export default function App(props: PageProps) { + return ( + + + + + + + + + ); +} diff --git a/packages/plugin-vite/tests/fixtures/tailwind_app/routes/index.tsx b/packages/plugin-vite/tests/fixtures/tailwind_app/routes/index.tsx new file mode 100644 index 00000000..0ba44d30 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_app/routes/index.tsx @@ -0,0 +1,3 @@ +export default function Hello() { + return

ok

; +} diff --git a/packages/plugin-vite/tests/fixtures/tailwind_app/vite.config.ts b/packages/plugin-vite/tests/fixtures/tailwind_app/vite.config.ts new file mode 100644 index 00000000..67a37d03 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_app/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "vite"; +import { fresh } from "@fresh/plugin-vite"; +import tailwindcss from "@tailwindcss/vite"; + +export default defineConfig({ + plugins: [fresh(), tailwindcss()], +}); diff --git a/packages/plugin-vite/tests/fixtures/tailwind_no_app/assets/style.css b/packages/plugin-vite/tests/fixtures/tailwind_no_app/assets/style.css new file mode 100644 index 00000000..f1d8c73c --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_no_app/assets/style.css @@ -0,0 +1 @@ +@import "tailwindcss"; diff --git a/packages/plugin-vite/tests/fixtures/tailwind_no_app/client.ts b/packages/plugin-vite/tests/fixtures/tailwind_no_app/client.ts new file mode 100644 index 00000000..aac395dd --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_no_app/client.ts @@ -0,0 +1 @@ +import "./assets/style.css"; diff --git a/packages/plugin-vite/tests/fixtures/tailwind_no_app/main.ts b/packages/plugin-vite/tests/fixtures/tailwind_no_app/main.ts new file mode 100644 index 00000000..d98e91b1 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_no_app/main.ts @@ -0,0 +1,3 @@ +import { App } from "@fresh/core"; + +export const app = new App().fsRoutes(); diff --git a/packages/plugin-vite/tests/fixtures/tailwind_no_app/routes/index.tsx b/packages/plugin-vite/tests/fixtures/tailwind_no_app/routes/index.tsx new file mode 100644 index 00000000..0ba44d30 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_no_app/routes/index.tsx @@ -0,0 +1,3 @@ +export default function Hello() { + return

ok

; +} diff --git a/packages/plugin-vite/tests/fixtures/tailwind_no_app/vite.config.ts b/packages/plugin-vite/tests/fixtures/tailwind_no_app/vite.config.ts new file mode 100644 index 00000000..67a37d03 --- /dev/null +++ b/packages/plugin-vite/tests/fixtures/tailwind_no_app/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from "vite"; +import { fresh } from "@fresh/plugin-vite"; +import tailwindcss from "@tailwindcss/vite"; + +export default defineConfig({ + plugins: [fresh(), tailwindcss()], +});