chore: restructure repository into packages/ folder (#3197)

We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
This commit is contained in:
Marvin Hagemeister
2025-08-06 15:52:45 +02:00
committed by GitHub
parent 27e407a1e3
commit 815b1940e3
184 changed files with 94 additions and 82 deletions
+136
View File
@@ -0,0 +1,136 @@
import "preact/debug";
export * from "./mod.tsx";
import { IS_BROWSER } from "../shared.ts";
let ws: WebSocket;
let revision = 0;
let reconnectTimer: number;
const backoff = [
// Wait 100ms initially, because we could also be
// disconnected because of a form submit.
100,
150,
200,
250,
300,
350,
400,
450,
500,
500,
605,
750,
1000,
1250,
1500,
1750,
2000,
];
let backoffIdx = 0;
function reconnect() {
if (ws.readyState !== ws.CLOSED) return;
reconnectTimer = setTimeout(() => {
if (backoffIdx === 0) {
// deno-lint-ignore no-console
console.log(
`%c Fresh %c Connection closed. Trying to reconnect...`,
"background-color: #86efac; color: black",
"color: inherit",
);
}
backoffIdx++;
try {
connect();
clearTimeout(reconnectTimer);
} catch (_err) {
reconnect();
}
}, backoff[Math.min(backoffIdx, backoff.length - 1)]);
}
function onOpenWs() {
backoffIdx = 0;
}
function onCloseWs() {
disconnect();
reconnect();
}
function connect() {
const url = new URL("/_frsh/alive", location.origin.replace("http", "ws"));
ws = new WebSocket(
url,
);
ws.addEventListener("open", onOpenWs);
ws.addEventListener("close", onCloseWs);
ws.addEventListener("message", handleMessage);
ws.addEventListener("error", handleError);
}
function disconnect() {
ws.removeEventListener("open", onOpenWs);
ws.removeEventListener("close", onCloseWs);
ws.removeEventListener("message", handleMessage);
ws.removeEventListener("error", handleError);
ws.close();
}
function handleMessage(e: MessageEvent) {
const data = JSON.parse(e.data);
switch (data.type) {
case "initial-state": {
if (revision === 0) {
// deno-lint-ignore no-console
console.log(
`%c Fresh %c Connected to development server.`,
"background-color: #86efac; color: black",
"color: inherit",
);
}
if (revision === 0) {
revision = data.revision;
} else if (revision < data.revision) {
disconnect();
// Needs reload
location.reload();
}
}
}
}
function handleError(e: Event) {
// TODO
// deno-lint-ignore no-explicit-any
if (e && (e as any).code === "ECONNREFUSED") {
setTimeout(connect, 1000);
}
}
if (IS_BROWSER) {
connect();
addEventListener("message", (ev) => {
if (ev.origin !== location.origin) return;
if (typeof ev.data !== "string" || ev.data !== "close-error-overlay") {
return;
}
document.querySelector("#fresh-error-overlay")?.remove();
});
// Disconnect when the tab becomes inactive and re-connect when it
// becomes active again
addEventListener("visibilitychange", () => {
if (document.hidden) {
disconnect();
} else {
connect();
}
});
}
@@ -0,0 +1,5 @@
import "./polyfills.ts";
import "./preact_hooks_client.ts";
import "./partials.ts";
export { asset, IS_BROWSER, Partial, type PartialProps } from "../shared.ts";
export { boot, revive } from "./reviver.ts";
@@ -0,0 +1,520 @@
import { type ComponentChildren, h } from "preact";
import {
CLIENT_NAV_ATTR,
DATA_ANCESTOR,
DATA_CURRENT,
matchesUrl,
PartialMode,
UrlMatchKind,
} from "../shared_internal.tsx";
import {
ACTIVE_PARTIALS,
copyOldChildren,
CUSTOM_PARSER,
type DeserializedProps,
domToVNode,
ISLAND_REGISTRY,
Marker,
maybeHideMarker,
PartialComp,
} from "./reviver.ts";
import { createRootFragment, isCommentNode, isElementNode } from "./reviver.ts";
import type { PartialStateJson } from "../server/preact_hooks.tsx";
import { parse } from "../../jsonify/parse.ts";
import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts";
export const PARTIAL_ATTR = "f-partial";
class NoPartialsError extends Error {}
// Fresh partials history updates set the fClientNav flag
// and prevent reloads in the popstate handler when
// user-code triggers history navigation events.
export interface FreshHistoryState {
fClientNav: boolean;
index: number;
scrollX: number;
scrollY: number;
}
function checkClientNavEnabled(el: HTMLElement) {
const setting = el.closest(`[${CLIENT_NAV_ATTR}]`);
if (setting === null) return false;
return setting.getAttribute(CLIENT_NAV_ATTR) !== "false";
}
// Keep track of history state to apply forward or backward animations
let index = history.state?.index || 0;
if (!history.state) {
const state: FreshHistoryState = {
fClientNav: true,
index,
scrollX,
scrollY,
};
history.replaceState(state, document.title);
}
function maybeUpdateHistory(nextUrl: URL) {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (nextUrl.href !== globalThis.location.href) {
const state: FreshHistoryState = {
fClientNav: true,
index,
scrollX: globalThis.scrollX,
scrollY: globalThis.scrollY,
};
// Store current scroll position
history.replaceState({ ...state }, "", location.href);
// Now store the new position
index++;
state.scrollX = 0;
state.scrollY = 0;
history.pushState(state, "", nextUrl.href);
}
}
document.addEventListener("click", async (e) => {
let el = e.target;
if (el && (el instanceof HTMLElement || el instanceof SVGElement)) {
const originalEl = el;
// Check if we clicked inside an anchor link
if (el.nodeName !== "A") {
el = el.closest("a");
}
if (el === null) {
el = originalEl.closest("button");
}
if (
// Check that we're still dealing with an anchor tag
el && el instanceof HTMLAnchorElement &&
// Check if it's an internal link
el.href && (!el.target || el.target === "_self") &&
el.origin === location.origin &&
// Check if it was a left click and not a right click
e.button === 0 &&
// Check that the user doesn't press a key combo to open the
// link in a new tab or something
!(e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.button) &&
// Check that the event isn't aborted already
!e.defaultPrevented
) {
const partial = el.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation or if
// we're doing a fragment navigation.
if (
el.getAttribute("href")?.startsWith("#") ||
!checkClientNavEnabled(el)
) {
return;
}
// deno-lint-ignore no-explicit-any
const indicator = (el as any)._freshIndicator;
if (indicator !== undefined) {
indicator.value = true;
}
e.preventDefault();
const nextUrl = new URL(el.href);
try {
maybeUpdateHistory(nextUrl);
const partialUrl = new URL(
partial ? partial : nextUrl.href,
location.href,
);
await fetchPartials(nextUrl, partialUrl);
updateLinks(nextUrl);
scrollTo({ left: 0, top: 0, behavior: "instant" });
} finally {
if (indicator !== undefined) {
indicator.value = false;
}
}
} else if (
el && el instanceof HTMLButtonElement &&
(el.type !== "submit" || el.form === null)
) {
const partial = el.getAttribute(PARTIAL_ATTR);
// Check if the user opted out of client side navigation.
if (partial === null || !checkClientNavEnabled(el)) {
return;
}
const partialUrl = new URL(
partial,
location.href,
);
await fetchPartials(partialUrl, partialUrl);
}
}
});
addEventListener("popstate", async (e) => {
// When state is `null` then the browser navigated to a document
// fragment. In this case we do nothing.
if (e.state === null) {
// Reset to browser default
if (history.scrollRestoration) {
history.scrollRestoration = "auto";
}
return;
}
// Do nothing if Fresh navigation is not explicitly opted-in.
// Other applications might manage scrollRestoration individually.
if (!e.state.fClientNav) return;
const state: FreshHistoryState = history.state;
const nextIdx = state.index ?? index + 1;
index = nextIdx;
const setting = document.querySelector(`[${CLIENT_NAV_ATTR}]`);
if (setting === null || setting.getAttribute(CLIENT_NAV_ATTR) === "false") {
location.reload();
return;
}
// We need to keep track of that ourselves since we do client side
// navigation.
if (history.scrollRestoration) {
history.scrollRestoration = "manual";
}
const url = new URL(location.href, location.origin);
try {
await fetchPartials(url, url);
updateLinks(url);
scrollTo({
left: state.scrollX ?? 0,
top: state.scrollY ?? 0,
behavior: "instant",
});
} catch (err) {
// If the response didn't contain a partial, then we can only
// do a reload.
if (err instanceof NoPartialsError) {
location.reload();
return;
}
throw err;
}
});
// Form submit
document.addEventListener("submit", async (e) => {
const el = e.target;
if (el !== null && el instanceof HTMLFormElement && !e.defaultPrevented) {
if (
// Check if form has client nav enabled
!checkClientNavEnabled(el) ||
// Bail out if submitter is set and client nav is disabled
(e.submitter !== null && !checkClientNavEnabled(e.submitter))
) {
return;
}
const lowerMethod =
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
el.method.toLowerCase();
if (lowerMethod !== "get" && lowerMethod !== "post") {
return;
}
const rawPartialUrl = e.submitter?.getAttribute(PARTIAL_ATTR) ??
e.submitter?.getAttribute("formaction") ??
el.getAttribute(PARTIAL_ATTR) ?? el.action;
const rawActionUrl = e.submitter?.getAttribute("formaction") ?? el.action;
if (rawPartialUrl !== "") {
e.preventDefault();
const partialUrl = new URL(rawPartialUrl, location.href);
const actionUrl = new URL(rawActionUrl, location.href);
let init: RequestInit | undefined;
// GET method appends form data via url search params
if (lowerMethod === "get") {
// TODO: Looks like constructor type for URLSearchParam is wrong
// deno-lint-ignore no-explicit-any
const qs = new URLSearchParams(new FormData(el, e.submitter) as any);
qs.forEach((value, key) => partialUrl.searchParams.append(key, value));
} else {
init = { body: new FormData(el, e.submitter), method: lowerMethod };
}
await fetchPartials(actionUrl, partialUrl, init);
}
}
});
function updateLinks(url: URL) {
document.querySelectorAll("a").forEach((link) => {
const match = matchesUrl(url.pathname, link.href);
if (match === UrlMatchKind.Current) {
link.setAttribute(DATA_CURRENT, "true");
link.setAttribute("aria-current", "page");
link.removeAttribute(DATA_ANCESTOR);
} else if (match === UrlMatchKind.Ancestor) {
link.setAttribute(DATA_ANCESTOR, "true");
link.setAttribute("aria-current", "true");
link.removeAttribute(DATA_CURRENT);
} else {
link.removeAttribute(DATA_CURRENT);
link.removeAttribute(DATA_ANCESTOR);
link.removeAttribute("aria-current");
}
});
}
async function fetchPartials(
actualUrl: URL,
partialUrl: URL,
init: RequestInit = {},
) {
init.redirect = "follow";
partialUrl = new URL(partialUrl);
partialUrl.searchParams.set(PARTIAL_SEARCH_PARAM, "true");
const res = await fetch(partialUrl, init);
if (res.redirected) {
const nextUrl = new URL(res.url);
if (nextUrl.origin === actualUrl.origin) {
actualUrl = nextUrl;
}
}
maybeUpdateHistory(actualUrl);
await applyPartials(res);
}
interface PartialReviveCtx {
foundPartials: number;
}
/**
* Apply partials from a HTML response
*/
export async function applyPartials(res: Response): Promise<void> {
const contentType = res.headers.get("Content-Type");
if (contentType !== "text/html; charset=utf-8") {
throw new Error(`Unable to process partial response.`);
}
const id = res.headers.get("X-Fresh-Id");
const resText = await res.text();
const doc = new DOMParser().parseFromString(resText, "text/html") as Document;
const state = doc.querySelector(`#__FRSH_STATE_${id}`);
let allProps: DeserializedProps = [];
if (state !== null) {
const json = JSON.parse(state.textContent!) as PartialStateJson;
const promises: Promise<void>[] = [];
allProps = parse<DeserializedProps>(json.props, CUSTOM_PARSER);
for (let i = 0; i < json.islands.length; i++) {
const island = json.islands[i];
promises.push(
import(/* @vite-ignore */ island.chunk).then((mod) => {
ISLAND_REGISTRY.set(island.name, mod[island.exportName]);
}),
);
}
await Promise.all(promises);
}
const ctx: PartialReviveCtx = {
foundPartials: 0,
};
if (doc.title) {
document.title = doc.title;
}
// Needs to be converted to an array otherwise somehow <link>-tags
// are missing.
Array.from(doc.head.childNodes).forEach((childNode) => {
const child = childNode as HTMLElement;
if (child.nodeName === "TITLE") return;
if (child.nodeName === "META") {
const meta = child as HTMLMetaElement;
// Ignore charset which is usually set site wide anyway
if (meta.hasAttribute("charset")) return;
const name = meta.name;
if (name !== "") {
const existing = document.head.querySelector(`meta[name="${name}"]`) as
| HTMLMetaElement
| null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
} else {
const property = child.getAttribute("property");
const existing = document.head.querySelector(
`meta[property="${property}"]`,
) as HTMLMetaElement | null;
if (existing !== null) {
if (existing.content !== meta.content) {
existing.content = meta.content;
}
} else {
document.head.appendChild(meta);
}
}
} else if (child.nodeName === "LINK") {
const link = child as HTMLLinkElement;
if (link.rel === "modulepreload") return;
if (link.rel === "stylesheet") {
// The `href` attribute may be root relative. This ensures
// that they both have the same format
const existing = Array.from(document.head.querySelectorAll("link"))
.find((existingLink) => existingLink.href === link.href);
if (existing === undefined) {
document.head.appendChild(link);
}
}
} else if (child.nodeName === "SCRIPT") {
const script = child as HTMLScriptElement;
if (script.src === `${INTERNAL_PREFIX}/fresh-runtime.js`) return;
// TODO: What to do with script tags?
} else if (child.nodeName === "STYLE") {
const style = child as HTMLStyleElement;
// TODO: Do we need a smarter merging strategy?
// Don't overwrie existing style sheets that are flagged as unique
if (style.id === "") {
document.head.appendChild(style);
}
}
});
revivePartials(ctx, allProps, doc.body);
if (ctx.foundPartials === 0) {
throw new NoPartialsError(
`Found no partials in HTML response. Please make sure to render at least one partial. Requested url: ${res.url}`,
);
}
}
function revivePartials(
ctx: PartialReviveCtx,
allProps: DeserializedProps,
node: Element,
) {
let startNode = null;
let sib: ChildNode | null = node.firstChild;
let partialCount = 0;
let partialName = "";
let partialKey = "";
let partialMode = PartialMode.Replace;
while (sib !== null) {
if (isCommentNode(sib)) {
const comment = sib.data;
const parts = comment.split(":");
if (parts[0] === "frsh") {
sib = maybeHideMarker(sib);
}
if (parts[0] === "frsh" && parts[1] === "partial") {
if (++partialCount === 1) {
startNode = sib;
partialName = parts[2];
partialMode = +parts[3] as PartialMode;
partialKey = parts[4];
}
} else if (comment === "/frsh:partial") {
ctx.foundPartials++;
// Skip hydrating nested partials, only hydrate the outer one
if (--partialCount > 0) {
sib = sib.nextSibling;
continue;
}
// Create a fake DOM node that spans the partial we discovered.
// We need to include the partial markers itself for _walkInner
// to register them.
const container = createRootFragment(
node,
startNode as Comment,
sib as Comment,
);
const root = h(PartialComp, {
key: partialKey !== "" ? partialKey : undefined,
name: partialName,
mode: partialMode,
children: null,
});
domToVNode(
allProps,
[root],
[Marker.Partial],
container,
sib as Comment,
);
const instance = ACTIVE_PARTIALS.get(partialName);
if (instance === undefined) {
// deno-lint-ignore no-console
console.warn(`Partial "${partialName}" not found. Skipping...`);
// Partial doesn't exist on the current page
} else {
if (partialMode === PartialMode.Replace) {
instance.props.children = root.props.children;
} else if (partialMode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).push(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
} else if (partialMode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(partialName);
if (active !== undefined) {
copyOldChildren(instance.props, active.props.children);
(instance.props.children as ComponentChildren[]).unshift(
root.props.children,
);
} else {
instance.props.children = root.props.children;
}
}
instance.setState({});
}
}
} else if (partialCount === 0 && isElementNode(sib)) {
// Do not recurse if we know that we are inisde a partial
revivePartials(ctx, allProps, sib);
}
sib = sib.nextSibling;
}
}
@@ -0,0 +1,7 @@
// deno-lint-ignore-file ban-unknown-rule-code ban-unused-ignore
// Polyfill for old safari versions
if (typeof globalThis === "undefined") {
// @ts-ignore polyfill
// deno-lint-ignore no-window
window.globalThis = window;
}
@@ -0,0 +1,19 @@
import { options } from "preact";
import { assetHashingHook, CLIENT_NAV_ATTR } from "../shared_internal.tsx";
import { BUILD_ID } from "@fresh/build-id";
const oldVNodeHook = options.vnode;
options.vnode = (vnode) => {
assetHashingHook(vnode, BUILD_ID);
if (typeof vnode.type === "string") {
if (CLIENT_NAV_ATTR in vnode.props) {
const value = vnode.props[CLIENT_NAV_ATTR];
if (typeof value === "boolean") {
vnode.props[CLIENT_NAV_ATTR] = String(value);
}
}
}
oldVNodeHook?.(vnode);
};
@@ -0,0 +1,577 @@
import {
Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
render,
type VNode,
} from "preact";
import { type CustomParser, parse } from "../../jsonify/parse.ts";
import { computed, signal } from "@preact/signals";
import { DATA_FRESH_KEY, PartialMode } from "../shared_internal.tsx";
const enum RootKind {
Island,
Partial,
}
interface IslandReq {
kind: RootKind.Island;
name: string;
propsIdx: number;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface PartialReq {
kind: RootKind.Partial;
name: string;
key: string | null;
start: Comment | Text;
end: Comment | Text | null;
}
interface ReviveContext {
roots: Array<IslandReq | PartialReq>;
stack: Array<PartialReq | IslandReq>;
slots: Map<number, { name: string; start: Comment; end: Comment | null }>;
slotIdStack: number[];
}
interface SlotRef {
kind: typeof SLOT_SYMBOL;
name: string;
id: number;
}
const SLOT_SYMBOL = Symbol.for("_FRESH_SLOT");
function isSlotRef(x: unknown): x is SlotRef {
return x !== null && typeof x === "object" && "kind" in x &&
x.kind === SLOT_SYMBOL;
}
export type DeserializedProps = {
props: Record<string, unknown>;
slots: SlotRef[];
}[];
export const ACTIVE_PARTIALS = new Map<string, PartialComp>();
export class PartialComp extends Component<
{ children?: ComponentChildren; mode: PartialMode; name: string }
> {
override componentDidMount() {
ACTIVE_PARTIALS.set(this.props.name, this);
}
render() {
return this.props.children;
}
}
PartialComp.displayName = "Partial";
export function revive(
props: Record<string, unknown>,
component: ComponentType,
container: HTMLElement,
slots: ReviveContext["slots"],
allProps: DeserializedProps,
) {
const _render = () => {
for (const propName in props) {
const value = props[propName];
if (isSlotRef(value)) {
const marker = slots.get(value.id);
if (marker !== undefined) {
const root = h(Fragment, null);
const slotContainer = createRootFragment(
container,
marker.start,
marker.end!,
);
domToVNode(
allProps,
[root],
[Marker.Slot],
slotContainer,
marker.end!,
);
props[propName] = root;
} else {
const template = document.querySelector(
`#frsh-${value.id}-${value.name}`,
) as HTMLTemplateElement | null;
if (template !== null) {
const root = h(Fragment, null);
domToVNode(allProps, [root], [Marker.Slot], template.content, null);
props[propName] = root;
}
}
}
}
// TODO: explore hydrate?
render(h(component, props), container as unknown as HTMLElement);
};
// deno-lint-ignore no-window
"scheduler" in window
// `scheduler.postTask` is async but that can easily
// fire in the background. We don't want waiting for
// the hydration of an island block us.
// @ts-ignore scheduler API is not in types yet
? scheduler!.postTask(_render)
: setTimeout(_render, 0);
}
export const ISLAND_REGISTRY = new Map<string, ComponentType>();
export const CUSTOM_PARSER: CustomParser = {
Signal: (value: unknown) => signal(value),
Computed: (value: unknown) => computed(() => value),
Slot: (value: { name: string; id: number }): SlotRef => {
return { kind: SLOT_SYMBOL, name: value.name, id: value.id };
},
};
export function createReviveCtx(): ReviveContext {
return {
roots: [],
stack: [],
slots: new Map(),
slotIdStack: [],
};
}
export function boot(
initialIslands: Record<string, ComponentType>,
islandProps: string,
) {
const ctx = createReviveCtx();
_walkInner(ctx, document.body);
const keys = Object.keys(initialIslands);
for (let i = 0; i < keys.length; i++) {
const name = keys[i];
ISLAND_REGISTRY.set(name, initialIslands[name]);
}
const allProps = parse<DeserializedProps>(
islandProps,
CUSTOM_PARSER,
);
for (let i = 0; i < ctx.roots.length; i++) {
const root = ctx.roots[i];
const container = createRootFragment(
// deno-lint-ignore no-explicit-any
root.start.parentNode as any,
root.start,
root.end!,
);
if (root.kind === RootKind.Island) {
const props = allProps[root.propsIdx].props;
const component = ISLAND_REGISTRY.get(root.name)!;
revive(props, component, container, ctx.slots, allProps);
} else if (root.kind === RootKind.Partial) {
const props: Record<string, unknown> = {
name: root.name,
children: null,
};
const domRoot = h(Fragment, null);
domToVNode(allProps, [domRoot], [Marker.Partial], container, root.end!);
props.children = domRoot.props.children;
// deno-lint-ignore no-explicit-any
revive(props, PartialComp as any, container, ctx.slots, allProps);
}
}
}
const SHOW_MARKERS = false;
interface FreshMarker extends Text {
_frshMarker: string;
}
export function isFreshMarkerText(node: Node): node is FreshMarker {
return node.nodeType === Node.TEXT_NODE &&
// deno-lint-ignore no-explicit-any
typeof (node as any)._frshMarker === "string";
}
/**
* Replace comment markers with empty text nodes to hide them
* in DevTools. This is done to avoid user confusion.
*/
export function maybeHideMarker(marker: Comment): Comment | Text {
if (SHOW_MARKERS) return marker;
const text = new Text("") as FreshMarker;
text._frshMarker = marker.data;
marker.parentNode!.insertBefore(text, marker);
marker.remove();
return text;
}
function _walkInner(
ctx: ReviveContext,
node: Node | Comment,
) {
if (isElementNode(node)) {
// No need to traverse into <script> or <style> tags.
// No need to traverse deeper if we found a slotStart marker.
// We'll parse slots later when the island is revived.
if (
node.nodeName === "SCRIPT" || node.nodeName === "STYLE" ||
ctx.slotIdStack.length > 0
) {
return;
}
for (let i = 0; i < node.childNodes.length; i++) {
const child = node.childNodes[i];
_walkInner(ctx, child);
}
} else if (isCommentNode(node)) {
const comment = node.data;
if (comment.startsWith("frsh:")) {
node = maybeHideMarker(node);
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const found: IslandReq = {
kind: RootKind.Island,
name,
propsIdx: Number(propsIdx),
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
} else if (kind === "slot") {
const id = +parts[2];
const slotName = parts[3];
ctx.slotIdStack.push(id);
ctx.slots.set(id, {
name: slotName,
start: node as Comment,
end: null,
});
} else if (kind === "partial") {
const name = parts[2];
const key = parts[3];
const found: PartialReq = {
kind: RootKind.Partial,
name,
key: key === "" ? null : key,
start: node as Comment,
end: null,
};
if (ctx.stack.length === 0) {
ctx.roots.push(found);
}
ctx.stack.push(found);
}
} else if (comment === "/frsh:island" || comment === "/frsh:partial") {
node = maybeHideMarker(node);
const item = ctx.stack.pop();
if (item !== undefined) {
item.end = node as Comment;
}
} else if (comment === "/frsh:slot") {
node = maybeHideMarker(node);
const item = ctx.slotIdStack.pop();
if (item !== undefined) {
ctx.slots.get(item)!.end = node as Comment;
}
}
}
}
export const enum Marker {
Island,
Partial,
Slot,
}
interface ServerSlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
// deno-lint-ignore no-explicit-any
function ServerSlot(props: ServerSlotProps): any {
return props.children;
}
export function domToVNode(
allProps: DeserializedProps,
// deno-lint-ignore no-explicit-any
vnodeStack: VNode<any>[],
markerStack: Marker[],
node: Text | Comment | Node | DocumentFragment,
end: Text | Comment | null,
): void {
let sib: Node | ChildNode | null = node;
while (sib !== null) {
if (sib === end) return;
// deno-lint-ignore no-explicit-any
if ((sib as any)._frshRootFrag || sib instanceof DocumentFragment) {
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
} else if (isElementNode(sib)) {
const props: Record<string, unknown> = {};
for (let i = 0; i < sib.attributes.length; i++) {
const attr = sib.attributes[i];
if (attr.nodeName === DATA_FRESH_KEY) {
props.key = attr.nodeValue;
continue;
}
// Boolean attributes are always `true` when present.
// See: https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML
props[attr.nodeName] =
// deno-lint-ignore no-explicit-any
typeof (sib as any)[attr.nodeName] === "boolean"
? true
: attr.nodeValue;
}
const vnode = h(sib.localName, props);
const marker = markerStack.at(-1);
const appendVNode = marker === Marker.Slot || marker === Marker.Partial;
if (appendVNode) {
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
}
const firstChild = sib.firstChild;
if (firstChild !== null) {
domToVNode(allProps, vnodeStack, markerStack, firstChild, end);
}
if (appendVNode) {
vnodeStack.pop();
}
} else if (isCommentNode(sib) || isFreshMarkerText(sib)) {
const comment = isFreshMarkerText(sib) ? sib._frshMarker : sib.data;
if (comment.startsWith("frsh:")) {
const parts = comment.split(":");
const kind = parts[1];
if (kind === "island") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Island);
const name = parts[2];
const propsIdx = parts[3];
const key = parts[4];
const island = ISLAND_REGISTRY.get(name);
if (island === undefined) {
throw new Error(`Encountered unknown island: ${name}`);
}
const props = allProps[+propsIdx].props;
props.key = key === "" ? undefined : key;
// deno-lint-ignore no-explicit-any
const islandVNode = h<any>(island, props);
addVNodeChild(vnodeStack.at(-1)!, islandVNode);
vnodeStack.push(islandVNode);
} else if (kind === "slot") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Slot);
const id = +parts[2];
const slotName = parts[3];
const key = parts[4];
const vnode = h(ServerSlot, {
key: key === "" ? undefined : key,
id,
name: slotName,
children: [],
});
const parentVNode = vnodeStack.at(-1)!;
parentVNode.props[slotName] = vnode;
vnodeStack.push(vnode);
} else if (kind === "partial") {
sib = maybeHideMarker(sib);
markerStack.push(Marker.Partial);
const name = parts[2];
const mode = +parts[3] as PartialMode;
const key = parts[4];
// deno-lint-ignore no-explicit-any
let vnode: VNode<any> = h(PartialComp, {
name,
key: key === "" ? undefined : key,
mode,
});
const parentVNode = vnodeStack.at(-1);
if (parentVNode !== undefined) {
addVNodeChild(parentVNode, vnode);
}
if (mode === PartialMode.Append) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
addVNodeChild(vnode, wrapper);
vnode = wrapper;
}
} else if (mode === PartialMode.Prepend) {
const active = ACTIVE_PARTIALS.get(name);
if (active !== undefined) {
copyOldChildren(vnode.props, active.props.children);
const wrapper = h(Fragment, null);
if (!vnode.props.children) {
vnode.props.children = [];
}
// deno-lint-ignore no-explicit-any
(vnode.props.children as Array<VNode<any> | string>).unshift(
wrapper,
);
vnode = wrapper;
}
}
vnodeStack.push(vnode);
} else if (kind === "key") {
if (!SHOW_MARKERS) {
const current = sib;
sib = sib.nextSibling;
current.remove();
}
const vnode = h(Fragment, { key: parts[2] });
addVNodeChild(vnodeStack.at(-1)!, vnode);
vnodeStack.push(vnode);
continue;
}
} else if (
comment === "/frsh:island" || comment === "/frsh:slot" ||
comment === "/frsh:partial"
) {
vnodeStack.pop();
markerStack.pop();
sib = maybeHideMarker(sib);
} else if (comment === "/frsh:key") {
vnodeStack.pop();
sib = maybeHideMarker(sib);
}
} else if (isTextNode(sib)) {
const marker = markerStack.at(-1);
if (marker === Marker.Slot || marker === Marker.Partial) {
addVNodeChild(vnodeStack.at(-1)!, sib.data);
}
}
sib = sib.nextSibling;
}
}
// deno-lint-ignore no-explicit-any
function addVNodeChild(parent: VNode<any>, child: VNode<any> | string) {
if (!parent.props.children) {
parent.props.children = [];
}
// deno-lint-ignore no-explicit-any
(parent.props.children as Array<VNode<any> | string>).push(child);
}
export function copyOldChildren(
props: Record<string, unknown>,
oldChildren: ComponentChildren,
) {
props.children = oldChildren !== undefined && oldChildren !== null
? Array.isArray(oldChildren) ? oldChildren : [oldChildren]
: [];
}
export function isCommentNode(node: Node): node is Comment {
return node.nodeType === Node.COMMENT_NODE;
}
export function isTextNode(node: Node): node is Text {
return node.nodeType === Node.TEXT_NODE;
}
export function isElementNode(node: Node): node is HTMLElement {
return node.nodeType === Node.ELEMENT_NODE && !("_frshRootFrag" in node);
}
export function createRootFragment(
parent: Element,
startMarker: Text | Comment,
// We need an end marker for islands because multiple
// islands can share the same parent node. Since
// islands are root-level render calls any calls to
// `.appendChild` would lead to a wrong result.
endMarker: Text | Comment,
): HTMLElement & { _frshRootFrag: boolean } {
// @ts-ignore this is fine
const rootFrag = {
_frshRootFrag: true,
nodeType: 1,
parentNode: parent,
nextSibling: null,
get firstChild() {
const child = startMarker.nextSibling;
if (child === endMarker) return null;
return child;
},
get childNodes() {
const children: ChildNode[] = [];
let child = startMarker.nextSibling;
while (child !== null && child !== endMarker) {
children.push(child);
child = child.nextSibling;
}
return children;
},
insertBefore(node: Node, child: Node | null) {
parent.insertBefore(node, child ?? endMarker);
},
appendChild(child: Node) {
// We cannot blindly call `.append()` as that would add
// the new child to the very end of the parent node. This
// leads to ordering issues when the multiple islands
// share the same parent node.
parent.insertBefore(child, endMarker);
},
removeChild(child: Node) {
parent.removeChild(child);
},
contains(node: Node | null): boolean {
if (node === null) return false;
const children = rootFrag.childNodes;
for (let i = 0; i < children.length; i++) {
if (children[i].contains(node)) {
return true;
}
}
return false;
},
};
// deno-lint-ignore no-explicit-any
return rootFrag as any;
}
@@ -0,0 +1,553 @@
import {
type Component,
type ComponentChildren,
type ComponentType,
Fragment,
h,
isValidElement,
type Options as PreactOptions,
options as preactOptions,
type VNode,
} from "preact";
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 { stringify } from "../../jsonify/stringify.ts";
import type { Island } from "../../context.ts";
import {
assetHashingHook,
CLIENT_NAV_ATTR,
DATA_FRESH_KEY,
PartialMode,
setActiveUrl,
} from "../shared_internal.tsx";
import type { BuildCache } from "../../build_cache.ts";
import { BUILD_ID } from "@fresh/build-id";
import {
DEV_ERROR_OVERLAY_URL,
PARTIAL_SEARCH_PARAM,
} from "../../constants.ts";
import { escape as escapeHtml } from "@std/html";
import { HttpError } from "../../error.ts";
import { getCodeFrame } from "../../dev/middlewares/error_overlay/code_frame.tsx";
import { escapeScript } from "../../utils.ts";
const enum OptionsType {
ATTR = "attr",
VNODE = "vnode",
HOOK = "__h",
DIFF = "__b",
RENDER = "__r",
DIFFED = "diffed",
ERROR = "__e",
}
interface InternalPreactOptions extends PreactOptions {
[OptionsType.ATTR](name: string, value: unknown): string | void;
[OptionsType.VNODE](vnode: InternalVNode): void;
[OptionsType.HOOK](component: Component, index: number, type: number): void;
[OptionsType.DIFF](vnode: InternalVNode): void;
[OptionsType.RENDER](vnode: InternalVNode): void;
[OptionsType.DIFFED](vnode: InternalVNode): void;
[OptionsType.ERROR](
error: unknown,
vnode: InternalVNode,
oldVNode: InternalVNode,
): void;
}
interface InternalVNode extends VNode {
__c: Component | null;
__: InternalVNode | null;
}
// deno-lint-ignore no-explicit-any
const options: InternalPreactOptions = preactOptions as any;
export class RenderState {
nonce: string;
partialDepth = 0;
partialCount = 0;
error: Error | null = null;
// deno-lint-ignore no-explicit-any
slots: Array<{ id: number; name: string; vnode: VNode<any> } | null> = [];
// deno-lint-ignore no-explicit-any
islandProps: any[] = [];
islands = new Set<Island>();
// deno-lint-ignore no-explicit-any
encounteredPartials = new Set<any>();
owners = new Map<VNode, VNode>();
ownerStack: InternalVNode[] = [];
// TODO: merge into bitmask field
renderedHtmlTag = false;
renderedHtmlBody = false;
renderedHtmlHead = false;
hasRuntimeScript = false;
constructor(
// deno-lint-ignore no-explicit-any
public ctx: PageProps<any, any>,
public buildCache: BuildCache,
public partialId: string,
) {
this.nonce = crypto.randomUUID().replace(/-/g, "");
}
clear() {
this.islands.clear();
this.encounteredPartials.clear();
this.owners.clear();
this.slots = [];
this.islandProps = [];
this.ownerStack = [];
}
}
let RENDER_STATE: RenderState | null = null;
export function setRenderState(state: RenderState | null) {
RENDER_STATE = state;
}
const oldVNodeHook = options[OptionsType.VNODE];
options[OptionsType.VNODE] = (vnode) => {
if (RENDER_STATE !== null) {
RENDER_STATE.owners.set(vnode, RENDER_STATE!.ownerStack.at(-1)!);
if (vnode.type === "a") {
setActiveUrl(vnode, RENDER_STATE.ctx.url.pathname);
}
}
assetHashingHook(vnode, BUILD_ID);
if (typeof vnode.type === "function") {
if (vnode.type === Partial) {
const props = vnode.props as PartialProps;
const key = normalizeKey(vnode.key);
const mode = !props.mode || props.mode === "replace"
? PartialMode.Replace
: props.mode === "append"
? PartialMode.Append
: PartialMode.Prepend;
props.children = wrapWithMarker(
props.children,
"partial",
`${props.name}:${mode}:${key}`,
);
}
} else if (typeof vnode.type === "string") {
if (vnode.type === "body") {
const scripts = h(FreshScripts, null);
if (vnode.props.children == null) {
vnode.props.children = scripts;
} else if (Array.isArray(vnode.props.children)) {
vnode.props.children.push(scripts);
} else {
vnode.props.children = [vnode.props.children, scripts];
}
}
if (CLIENT_NAV_ATTR in vnode.props) {
vnode.props[CLIENT_NAV_ATTR] = String(vnode.props[CLIENT_NAV_ATTR]);
}
}
oldVNodeHook?.(vnode);
};
const oldAttrHook = options[OptionsType.ATTR];
options[OptionsType.ATTR] = (name, value) => {
if (name === CLIENT_NAV_ATTR) {
return `${CLIENT_NAV_ATTR}="${String(Boolean(value))}"`;
} else if (name === "key") {
return `${DATA_FRESH_KEY}="${escapeHtml(String(value))}"`;
}
return oldAttrHook?.(name, value);
};
const PATCHED = new WeakSet<VNode>();
function normalizeKey(key: unknown): string {
const value = key ?? "";
const s = (typeof value !== "string") ? String(value) : value;
return s.replaceAll(":", "_");
}
const oldDiff = options[OptionsType.DIFF];
options[OptionsType.DIFF] = (vnode) => {
if (RENDER_STATE !== null) {
patcher: if (
typeof vnode.type === "function" && vnode.type !== Fragment
) {
if (vnode.type === Partial) {
RENDER_STATE.partialDepth++;
const name = (vnode.props as PartialProps).name;
if (typeof name === "string") {
if (RENDER_STATE.encounteredPartials.has(name)) {
throw new Error(
`Rendered response contains duplicate partial name: "${name}"`,
);
}
RENDER_STATE.encounteredPartials.add(name);
}
if (hasIslandOwner(RENDER_STATE, vnode)) {
throw new Error(
`<Partial> components cannot be used inside islands.`,
);
}
} else if (
!PATCHED.has(vnode) && !hasIslandOwner(RENDER_STATE, vnode)
) {
const island = RENDER_STATE.buildCache.islandRegistry.get(vnode.type);
if (island === undefined) {
// Not an island, but we might need to preserve keys
if (vnode.key !== undefined) {
const key = normalizeKey(vnode.key);
const originalType = vnode.type;
vnode.type = (props) => {
const child = h(originalType, props);
PATCHED.add(child);
return wrapWithMarker(child, "key", key);
};
}
break patcher;
}
const { islands, islandProps } = RENDER_STATE;
islands.add(island);
const originalType = vnode.type;
vnode.type = (props) => {
for (const name in props) {
// deno-lint-ignore no-explicit-any
const value = (props as any)[name];
if (
name === "children" || (isValidElement(value) && !isSignal(value))
) {
const slotId = RENDER_STATE!.slots.length;
RENDER_STATE!.slots.push({ id: slotId, name, vnode: value });
// deno-lint-ignore no-explicit-any
(props as any)[name] = h(Slot, {
name,
id: slotId,
}, value);
}
}
const propsIdx = islandProps.push({ slots: [], props }) - 1;
const child = h(originalType, props);
PATCHED.add(child);
const key = normalizeKey(vnode.key);
return wrapWithMarker(
child,
"island",
`${island!.name}:${propsIdx}:${key}`,
);
};
}
} else if (typeof vnode.type === "string") {
switch (vnode.type) {
case "html":
RENDER_STATE!.renderedHtmlTag = true;
break;
case "head":
RENDER_STATE!.renderedHtmlHead = true;
break;
case "body":
RENDER_STATE!.renderedHtmlBody = true;
break;
}
if (
vnode.key !== undefined &&
(RENDER_STATE!.partialDepth > 0 || hasIslandOwner(RENDER_STATE!, vnode))
) {
(vnode.props as Record<string, unknown>)[DATA_FRESH_KEY] = String(
vnode.key,
);
}
}
}
oldDiff?.(vnode);
};
const oldRender = options[OptionsType.RENDER];
options[OptionsType.RENDER] = (vnode) => {
if (
typeof vnode.type === "function" && vnode.type !== Fragment &&
RENDER_STATE !== null
) {
RENDER_STATE.ownerStack.push(vnode);
}
oldRender?.(vnode);
};
const oldDiffed = options[OptionsType.DIFFED];
options[OptionsType.DIFFED] = (vnode) => {
if (
typeof vnode.type === "function" && vnode.type !== Fragment &&
RENDER_STATE !== null
) {
RENDER_STATE.ownerStack.pop();
if (vnode.type === Partial) {
RENDER_STATE.partialDepth--;
}
}
oldDiffed?.(vnode);
};
interface SlotProps {
name: string;
id: number;
children?: ComponentChildren;
}
function Slot(props: SlotProps) {
if (RENDER_STATE !== null) {
RENDER_STATE.slots[props.id] = null;
}
return wrapWithMarker(props.children, "slot", `${props.id}:${props.name}`);
}
/**
* Check if the current component was rendered in an island
*/
function hasIslandOwner(current: RenderState, vnode: VNode): boolean {
let tmpVNode = vnode;
let owner;
while ((owner = current.owners.get(tmpVNode)) !== undefined) {
if (current.buildCache.islandRegistry.has(owner.type as ComponentType)) {
return true;
}
tmpVNode = owner;
}
return false;
}
function wrapWithMarker(
vnode: ComponentChildren,
kind: string,
markerText: string,
) {
return h(
Fragment,
null,
h(Fragment, {
// @ts-ignore unstable property is not typed
UNSTABLE_comment: `frsh:${kind}:${markerText}`,
}),
vnode,
h(Fragment, {
// @ts-ignore unstable property is not typed
UNSTABLE_comment: "/frsh:" + kind,
}),
);
}
// deno-lint-ignore no-explicit-any
function isSignal(x: any): x is Signal {
return (
x !== null &&
typeof x === "object" &&
typeof x.peek === "function" &&
"value" in x
);
}
// deno-lint-ignore no-explicit-any
function isComputedSignal(x: any): x is ReadonlySignal {
return isSignal(x) &&
(("x" in x && typeof x.x === "function") ||
"_fn" in x && typeof x._fn === "function");
}
// deno-lint-ignore no-explicit-any
function isVNode(x: any): x is VNode {
return x !== null && typeof x === "object" && "type" in x && "ref" in x &&
"__k" in x &&
isValidElement(x);
}
const stringifiers: Stringifiers = {
Computed: (value: unknown) => {
return isComputedSignal(value) ? { value: value.peek() } : undefined;
},
Signal: (value: unknown) => {
return isSignal(value) ? { value: value.peek() } : undefined;
},
Slot: (value: unknown) => {
if (isVNode(value) && value.type === Slot) {
const props = value.props as SlotProps;
return {
value: {
name: props.name,
id: props.id,
},
};
}
},
};
export function FreshScripts() {
if (RENDER_STATE === null) return null;
if (RENDER_STATE.hasRuntimeScript) {
return null;
}
RENDER_STATE.hasRuntimeScript = true;
const { slots } = RENDER_STATE;
// Remaining slots must be rendered before creating the Fresh runtime
// script, so that we have the full list of islands rendered
return (
<>
{slots.map((slot) => {
if (slot === null) return null;
return (
<template
key={slot.id}
id={`frsh-${slot.id}-${slot.name}`}
>
{slot.vnode}
</template>
);
})}
<FreshRuntimeScript />
</>
);
}
export interface PartialStateJson {
islands: {
name: string;
chunk: string;
exportName: string;
}[];
props: string;
}
function FreshRuntimeScript() {
const { islands, nonce, ctx, islandProps, partialId, buildCache } =
RENDER_STATE!;
const basePath = ctx.config.basePath;
const islandArr = Array.from(islands);
if (ctx.url.searchParams.has(PARTIAL_SEARCH_PARAM)) {
const islands = islandArr.map((island) => {
return {
exportName: island.exportName,
chunk: island.file,
name: island.name,
};
});
const serializedProps = stringify(islandProps, stringifiers);
const json: PartialStateJson = {
islands,
props: serializedProps,
};
return (
<script
id={`__FRSH_STATE_${partialId}`}
type="application/json"
// deno-lint-ignore react-no-danger
dangerouslySetInnerHTML={{
__html: escapeScript(JSON.stringify(json), { json: true }),
}}
/>
);
} else {
const islandImports = islandArr.map((island) => {
const named = island.exportName === "default"
? island.name
: island.exportName === island.name
? `{ ${island.exportName} }`
: `{ ${island.exportName} as ${island.name} }`;
const islandSpec = island.file.startsWith(".")
? island.file.slice(1)
: island.file;
return `import ${named} from "${basePath}${islandSpec}";`;
}).join("");
const islandObj = "{" + islandArr.map((island) => island.name)
.join(",") +
"}";
const serializedProps = escapeScript(
JSON.stringify(stringify(islandProps, stringifiers)),
{ json: true },
);
// const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`;
const runtimeUrl = buildCache.clientEntry.startsWith(".")
? buildCache.clientEntry.slice(1)
: buildCache.clientEntry;
const scriptContent =
`import { boot } from "${basePath}${runtimeUrl}";${islandImports}boot(${islandObj},${serializedProps});`;
return (
<>
<script
type="module"
nonce={nonce}
// deno-lint-ignore react-no-danger
dangerouslySetInnerHTML={{
__html: scriptContent,
}}
/>
{buildCache.features.errorOverlay ? <ShowErrorOverlay /> : null}
</>
);
}
}
export function ShowErrorOverlay() {
if (RENDER_STATE === null) return null;
const { ctx } = RENDER_STATE;
const error = ctx.error;
if (error === null || error === undefined) return null;
// Ignore HTTP errors <500
if (error instanceof HttpError && error.status < 500) {
return null;
}
const basePath = ctx.config.basePath;
const searchParams = new URLSearchParams();
if (typeof error === "object") {
if ("message" in error) {
searchParams.append("message", String(error.message));
}
if ("stack" in error && typeof error.stack === "string") {
searchParams.append("stack", error.stack);
const codeFrame = getCodeFrame(error.stack, ctx.config.root);
if (codeFrame !== undefined) {
searchParams.append("code-frame", codeFrame);
}
}
} else {
searchParams.append("message", String(error));
}
return (
<iframe
id="fresh-error-overlay"
src={`${basePath}${DEV_ERROR_OVERLAY_URL}?${searchParams.toString()}`}
style="unset: all; position: fixed; top: 0; left: 0; z-index: 99999; width: 100%; height: 100%; border: none;"
/>
);
}
+54
View File
@@ -0,0 +1,54 @@
import type { ComponentChildren, VNode } from "preact";
import { BUILD_ID } from "@fresh/build-id";
import { assetInternal, assetSrcSetInternal } from "./shared_internal.tsx";
/**
* Returns true when the current runtime is the browser and false otherwise. This is used for guard runtime-dependent code.
* Shorthand for the following:
* `typeof document !== "undefined"`
*
* @example
* ```
* if (IS_BROWSER) {
* alert('This is running in the browser!');
* } else {
* console.log('This code is running on the server, no access to window or alert');
* }
* ```
*
* Without this guard, alert pauses the server until return is pressed in the console.
*/
export const IS_BROWSER = typeof document !== "undefined";
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function asset(path: string): string {
return assetInternal(path, BUILD_ID);
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSet(srcset: string): string {
return assetSrcSetInternal(srcset, BUILD_ID);
}
export interface PartialProps {
children?: ComponentChildren;
/**
* The name of the partial. This value must be unique across partials.
*/
name: string;
/**
* Define how the new HTML should be applied.
* @default {"replace"}
*/
mode?: "replace" | "prepend" | "append";
}
export function Partial(props: PartialProps): VNode {
// deno-lint-ignore no-explicit-any
return props.children as any;
}
Partial.displayName = "Partial";
@@ -0,0 +1,123 @@
import type { VNode } from "preact";
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,
Ancestor,
Current,
}
export function matchesUrl(current: string, needle: string): UrlMatchKind {
let href = new URL(needle, "http://localhost").pathname;
if (href !== "/" && href.endsWith("/")) {
href = href.slice(0, -1);
}
if (current !== "/" && current.endsWith("/")) {
current = current.slice(0, -1);
}
if (current === href) {
return UrlMatchKind.Current;
} else if (current.startsWith(href + "/") || href === "/") {
return UrlMatchKind.Ancestor;
}
return UrlMatchKind.None;
}
/**
* Mark active or ancestor link
* Note: This function is used both on the server and the client
*/
export function setActiveUrl(vnode: VNode, pathname: string): void {
const props = vnode.props as Record<string, unknown>;
const hrefProp = props.href;
if (typeof hrefProp === "string" && hrefProp.startsWith("/")) {
const match = matchesUrl(pathname, hrefProp);
if (match === UrlMatchKind.Current) {
props[DATA_CURRENT] = "true";
props["aria-current"] = "page";
} else if (match === UrlMatchKind.Ancestor) {
props[DATA_ANCESTOR] = "true";
props["aria-current"] = "true";
}
}
}
export const enum PartialMode {
Replace,
Append,
Prepend,
}
/**
* Create a "locked" asset path. This differs from a plain path in that it is
* specific to the current version of the application, and as such can be safely
* served with a very long cache lifetime (1 year).
*/
export function assetInternal(path: string, buildId: string): string {
if (!path.startsWith("/") || path.startsWith("//")) return path;
try {
const url = new URL(path, "https://freshassetcache.local");
if (
url.protocol !== "https:" || url.host !== "freshassetcache.local" ||
url.searchParams.has(ASSET_CACHE_BUST_KEY)
) {
return path;
}
url.searchParams.set(ASSET_CACHE_BUST_KEY, buildId);
return url.pathname + url.search + url.hash;
} catch (err) {
// deno-lint-ignore no-console
console.warn(
`Failed to create asset() URL, falling back to regular path ('${path}'):`,
err,
);
return path;
}
}
/** Apply the `asset` function to urls in a `srcset` attribute. */
export function assetSrcSetInternal(srcset: string, buildId: string): string {
if (srcset.includes("(")) return srcset; // Bail if the srcset contains complicated syntax.
const parts = srcset.split(",");
const constructed = [];
for (const part of parts) {
const trimmed = part.trimStart();
const leadingWhitespace = part.length - trimmed.length;
if (trimmed === "") return srcset; // Bail if the srcset is malformed.
let urlEnd = trimmed.indexOf(" ");
if (urlEnd === -1) urlEnd = trimmed.length;
const leading = part.substring(0, leadingWhitespace);
const url = trimmed.substring(0, urlEnd);
const trailing = trimmed.substring(urlEnd);
constructed.push(leading + assetInternal(url, buildId) + trailing);
}
return constructed.join(",");
}
export function assetHashingHook(
vnode: VNode<{
src?: string;
srcset?: string;
["data-fresh-disable-lock"]?: boolean;
}>,
buildId: string,
) {
if (vnode.type === "img" || vnode.type === "source") {
const { props } = vnode;
if (props["data-fresh-disable-lock"]) return;
if (typeof props.src === "string") {
props.src = assetInternal(props.src, buildId);
}
if (typeof props.srcset === "string") {
props.srcset = assetSrcSetInternal(props.srcset, buildId);
}
}
}