Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit f824f1e

Browse files
committed
Check DENO_DEPLOYMENT_ID env for cache optimiztion
1 parent e07d7b0 commit f824f1e

File tree

6 files changed

+73
-49
lines changed

6 files changed

+73
-49
lines changed

framework/react/router.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,13 @@ export const Router: FC<RouterProps> = ({ ssrContext, suspense }) => {
109109
const routeModules = getRouteModules();
110110
const routes = loadRoutesFromTag();
111111
const importModule = async ({ filename }: RouteMeta) => {
112-
const { default: defaultExport, data: withData } = await import(filename.slice(1)); // todo: add version
112+
const deployId = document.body.getAttribute("data-deployment-id");
113+
let url = filename.slice(1);
114+
if (deployId) {
115+
url += `?v=${deployId}`;
116+
}
117+
console.log(url);
118+
const { default: defaultExport, data: withData } = await import(url);
113119
routeModules[filename] = { defaultExport, withData };
114120
return { defaultExport, withData };
115121
};
@@ -144,14 +150,19 @@ export const Router: FC<RouterProps> = ({ ssrContext, suspense }) => {
144150
dataCache.set(dataUrl, rd);
145151
};
146152
const onmoduleprefetch = (e: Record<string, unknown>) => {
153+
const deployId = document.body.getAttribute("data-deployment-id");
147154
const pageUrl = new URL(e.href as string, location.href);
148155
const matches = matchRoutes(pageUrl, routes);
149156
matches.map(([_, meta]) => {
150157
const { filename } = meta;
151158
if (!(filename in routeModules)) {
152159
const link = document.createElement("link");
160+
let href = meta.filename.slice(1);
161+
if (deployId) {
162+
href += `?v=${deployId}`;
163+
}
153164
link.setAttribute("rel", "modulepreload");
154-
link.setAttribute("href", meta.filename.slice(1));
165+
link.setAttribute("href", href);
155166
document.head.appendChild(link);
156167
}
157168
});

server/helpers.ts

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,35 @@ export type JSXConfig = {
1717
export const regFullVersion = /@\d+\.\d+\.\d+/;
1818
export const builtinModuleExts = ["tsx", "ts", "mts", "jsx", "js", "mjs"];
1919

20+
export function getAlephPkgUri() {
21+
return globalIt("__ALEPH_PKG_URI", () => {
22+
const uriFromEnv = Deno.env.get("ALEPH_PKG_URI");
23+
if (uriFromEnv) {
24+
return uriFromEnv;
25+
}
26+
const DEV_PORT = Deno.env.get("ALEPH_DEV_PORT");
27+
if (DEV_PORT) {
28+
return `http://localhost:${DEV_PORT}`;
29+
}
30+
const version = Deno.env.get("ALEPH_VERSION") || VERSION;
31+
return `https://deno.land/x/${isCanary ? "aleph_canary" : "aleph"}@${version}`;
32+
});
33+
}
34+
35+
export function getUnoGenerator() {
36+
return globalIt("__UNO_GENERATOR", () => {
37+
const config: AlephConfig | undefined = Reflect.get(globalThis, "__ALEPH_CONFIG");
38+
if (config?.unocss?.presets?.length) {
39+
return createGenerator(config.unocss);
40+
}
41+
return null;
42+
});
43+
}
44+
45+
export function getDeploymentId(): string | null {
46+
return Deno.env.get("DENO_DEPLOYMENT_ID") ?? null;
47+
}
48+
2049
/**
2150
* fix remote url to local path.
2251
* e.g. `https://esm.sh/[email protected]?dev` -> `/-/esm.sh/[email protected]?dev`
@@ -67,31 +96,6 @@ export function globalIt<T>(name: string, fn: () => T): T {
6796
return ret;
6897
}
6998

70-
export function getAlephPkgUri() {
71-
return globalIt("__ALEPH_PKG_URI", () => {
72-
const uriFromEnv = Deno.env.get("ALEPH_PKG_URI");
73-
if (uriFromEnv) {
74-
return uriFromEnv;
75-
}
76-
const DEV_PORT = Deno.env.get("ALEPH_DEV_PORT");
77-
if (DEV_PORT) {
78-
return `http://localhost:${DEV_PORT}`;
79-
}
80-
const version = Deno.env.get("ALEPH_VERSION") || VERSION;
81-
return `https://deno.land/x/${isCanary ? "aleph_canary" : "aleph"}@${version}`;
82-
});
83-
}
84-
85-
export function getUnoGenerator() {
86-
return globalIt("__UNO_GENERATOR", () => {
87-
const config: AlephConfig | undefined = Reflect.get(globalThis, "__ALEPH_CONFIG");
88-
if (config?.unocss?.presets?.length) {
89-
return createGenerator(config.unocss);
90-
}
91-
return null;
92-
});
93-
}
94-
9599
export async function loadJSXConfig(importMap: ImportMap): Promise<JSXConfig> {
96100
const jsxConfig: JSXConfig = {};
97101
const denoConfigFile = await findFile(["deno.jsonc", "deno.json", "tsconfig.json"]);

server/html.ts

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { Comment, DocumentEnd, Element } from "https://deno.land/x/lol_html
33
import initLolHtml, { HTMLRewriter } from "https://deno.land/x/[email protected]/mod.js";
44
import decodeLolHtmlWasm from "https://deno.land/x/[email protected]/wasm.js";
55
import util from "../lib/util.ts";
6-
import { getAlephPkgUri, toLocalPath } from "./helpers.ts";
6+
import { getAlephPkgUri, getDeploymentId, toLocalPath } from "./helpers.ts";
77

88
await initLolHtml(decodeLolHtmlWasm());
99

@@ -94,6 +94,7 @@ function fixIndexHtml(html: Uint8Array, hasSSRBody: boolean, options: LoadOption
9494
const alephPkgUri = getAlephPkgUri();
9595
const chunks: Uint8Array[] = [];
9696
const rewriter = new HTMLRewriter("utf8", (chunk: Uint8Array) => chunks.push(chunk));
97+
const deployId = getDeploymentId();
9798

9899
rewriter.on("link", {
99100
element: (el: Element) => {
@@ -102,6 +103,9 @@ function fixIndexHtml(html: Uint8Array, hasSSRBody: boolean, options: LoadOption
102103
const isHttpUrl = util.isLikelyHttpURL(href);
103104
if (!isHttpUrl) {
104105
href = util.cleanPath(href);
106+
if (deployId) {
107+
href += (href.includes("?") ? "&v=" : "?v=") + deployId;
108+
}
105109
el.setAttribute("href", href);
106110
}
107111
if (href.endsWith(".css") && !isHttpUrl && isDev) {
@@ -120,9 +124,13 @@ function fixIndexHtml(html: Uint8Array, hasSSRBody: boolean, options: LoadOption
120124
let nomoduleInserted = false;
121125
rewriter.on("script", {
122126
element: (el: Element) => {
123-
const src = el.getAttribute("src");
127+
let src = el.getAttribute("src");
124128
if (src && !util.isLikelyHttpURL(src)) {
125-
el.setAttribute("src", util.cleanPath(src));
129+
src = util.cleanPath(src);
130+
if (deployId) {
131+
src += (src.includes("?") ? "&v=" : "?v=") + deployId;
132+
}
133+
el.setAttribute("src", src);
126134
}
127135
if (!nomoduleInserted && el.getAttribute("type") === "module") {
128136
el.after(
@@ -145,20 +153,20 @@ function fixIndexHtml(html: Uint8Array, hasSSRBody: boolean, options: LoadOption
145153
}
146154
},
147155
});
148-
if (!hasSSRBody && ssr) {
149-
rewriter.on("body", {
150-
element: (el: Element) => {
151-
el.prepend("<ssr-body></ssr-body>", { html: true });
152-
},
153-
});
154-
}
155-
if (ssr?.suspense) {
156-
rewriter.on("body", {
157-
element: (el: Element) => {
156+
rewriter.on("body", {
157+
element: (el: Element) => {
158+
if (ssr?.suspense) {
158159
el.setAttribute("data-suspense", "true");
159-
},
160-
});
161-
}
160+
}
161+
if (deployId) {
162+
el.setAttribute("data-deployment-id", deployId);
163+
}
164+
if (ssr && !hasSSRBody) {
165+
el.prepend("<ssr-body></ssr-body>", { html: true });
166+
}
167+
},
168+
});
169+
162170
if (isDev && hmrWebSocketUrl) {
163171
rewriter.on("head", {
164172
element(el: Element) {

server/mod.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { getContentType } from "../lib/mime.ts";
55
import type { Routes } from "../lib/route.ts";
66
import util from "../lib/util.ts";
77
import { VERSION } from "../version.ts";
8-
import { initModuleLoaders, loadImportMap, loadJSXConfig } from "./helpers.ts";
8+
import { getDeploymentId, initModuleLoaders, loadImportMap, loadJSXConfig } from "./helpers.ts";
99
import { loadAndFixIndexHtml } from "./html.ts";
1010
import type { HTMLRewriterHandlers, SSR } from "./renderer.ts";
1111
import renderer from "./renderer.ts";
@@ -111,7 +111,7 @@ export const serve = (options: ServerOptions = {}) => {
111111
}
112112
if (stat.isFile) {
113113
const headers = new Headers({ "Content-Type": contentType });
114-
const deployId = Deno.env.get("DENO_DEPLOYMENT_ID");
114+
const deployId = getDeploymentId();
115115
let etag: string | null = null;
116116
if (deployId) {
117117
etag = `${btoa(pathname).replace(/[^a-z0-9]/g, "")}-${deployId}`;

server/renderer.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import util from "../lib/util.ts";
44
import type { RouteModule, Routes } from "../lib/route.ts";
55
import { matchRoutes } from "../lib/route.ts";
66
import type { DependencyGraph, Module } from "./graph.ts";
7-
import { builtinModuleExts, getUnoGenerator } from "./helpers.ts";
7+
import { builtinModuleExts, getDeploymentId, getUnoGenerator } from "./helpers.ts";
88
import type { Comment, Element } from "./html.ts";
99
import { HTMLRewriter } from "./html.ts";
1010
import { importRouteModule } from "./routing.ts";
@@ -231,8 +231,9 @@ export default {
231231
{ html: true },
232232
);
233233

234+
const deployId = getDeploymentId();
234235
const importStmts = routeModules.map(({ filename }, idx) =>
235-
`import $${idx} from ${JSON.stringify(filename.slice(1))};`
236+
`import $${idx} from ${JSON.stringify(filename.slice(1) + (deployId ? `?v=${deployId}` : ""))} ;`
236237
).join("");
237238
const kvs = routeModules.map(({ filename, data }, idx) =>
238239
`${JSON.stringify(filename)}:{defaultExport:$${idx}${data !== undefined ? ",withData:true" : ""}}`

server/serve_dist.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { readableStreamFromReader } from "https://deno.land/[email protected]/streams/conversion.ts";
22
import log from "../lib/log.ts";
3-
import { builtinModuleExts, regFullVersion } from "./helpers.ts";
3+
import { builtinModuleExts, getDeploymentId, regFullVersion } from "./helpers.ts";
44
import type { AlephConfig } from "./types.ts";
55

66
export default {
@@ -23,7 +23,7 @@ export default {
2323
ctype = "text/css; charset=utf-8";
2424
}
2525
const headers = new Headers({ "Content-Type": ctype });
26-
const deployId = Deno.env.get("DENO_DEPLOYMENT_ID");
26+
const deployId = getDeploymentId();
2727
let etag: string | null = null;
2828
if (deployId) {
2929
etag = `${btoa(pathname).replace(/[^a-z0-9]/g, "")}-${deployId}`;

0 commit comments

Comments
 (0)