1 Commits
Author SHA1 Message Date
schreifuchs 0255ae6165 chore: use better scaling kernel
/ publish (push) Successful in 3m45s
2026-03-09 08:40:05 +01:00
43 changed files with 2089 additions and 817 deletions
+20 -38
View File
@@ -2,40 +2,35 @@
Personal portfolio website for Schreifuchs, featuring photography, informatics, music, and video. Personal portfolio website for Schreifuchs, featuring photography, informatics, music, and video.
The site is built with **Go**, **templ**, and **HTMX**, and it is powered by a dynamic **Nextcloud** backend via WebDAV. The site is built with **Svelte 5** and **SvelteKit**, and it is powered by a dynamic **Nextcloud** backend via WebDAV.
## Features ## Features
- **Dynamic Content:** Pages are automatically discovered based on the folder structure in Nextcloud. - **Dynamic Content:** Pages are automatically discovered based on the folder structure in Nextcloud.
- **Hidden Sites:** Folders starting with `_` are excluded from the navigation menu but remain accessible via direct links. - **Hidden Sites:** Folders starting with `_` are excluded from the navigation menu but remain accessible via direct links.
- **Markdown Driven:** Content for each page is fetched from a corresponding Markdown file and rendered via `gomarkdown`. - **Markdown Driven:** Content for each page is fetched from a corresponding Markdown file.
- **Image Optimization:** Automatic image resizing via Nextcloud's Preview API for optimized delivery and `srcset` support. - **Image Optimization:** Automatic image resizing via Nextcloud's Preview API for optimized delivery and `srcset` support.
- **Asset Proxying:** Images and attachments are securely streamed from Nextcloud through a server-side proxy. - **Asset Proxying:** Images and attachments are securely streamed from Nextcloud through a server-side proxy.
- **Performance:** Multi-layer caching using **Valkey** (Redis-compatible) for WebDAV requests and image scaling. - **Performance:** In-memory caching for Nextcloud requests (15-minute TTL).
- **Responsive Design:** Styled with **Tailwind CSS**, optimized for all screen sizes. - **Responsive Design:** Styled with Tailwind CSS, optimized for all screen sizes.
## Tech Stack ## Tech Stack
- **Backend:** Go (Golang) - **Framework:** Svelte 5 (Runes) & SvelteKit
- **UI Components:** [templ](https://templ.guide/)
- **Frontend Interactivity:** [HTMX](https://htmx.org/)
- **Styling:** Tailwind CSS - **Styling:** Tailwind CSS
- **Caching:** Valkey - **Backend:** Node.js (via `@sveltejs/adapter-node`)
- **Integration:** `gowebdav` for Nextcloud communication - **Integration:** `webdav` library for Nextcloud communication
- **Content:** `github.com/gomarkdown/markdown` for rendering - **Content:** `@ts-stack/markdown` for rendering
## Configuration ## Configuration
The application requires the following environment variables in a `.env` file: The application requires the following environment variables in a `.env` file:
```env ```env
FILESYSTEM_URL=https://your-nextcloud-instance.com/remote.php/dav/files/user/ NEXTCLOUD_URL=https://your-nextcloud-instance.com
FILESYSTEM_USERNAME=your_username NEXTCLOUD_USER=your_username
FILESYSTEM_PASSWORD=your_app_password NEXTCLOUD_PASSWORD=your_app_password
CACHE_ADDRESS=localhost:6379 NEXTCLOUD_BASE_DIR=WebsiteContent # Optional: Root folder for site content
CACHE_PASSWORD=your_valkey_password
PORT=8080
LOG_LEVEL=DEBUG
``` ```
## Content Management ## Content Management
@@ -50,45 +45,32 @@ To add or update content, manage files in your configured Nextcloud directory:
## Development ## Development
Install dependencies (Go, pnpm, and the `templ` binary): Install dependencies:
```bash ```bash
# Install Go dependencies
go mod tidy
# Install JS/CSS dependencies
pnpm install pnpm install
``` ```
Start the development server with hot reloading: Start the development server:
```bash ```bash
air pnpm run dev
```
For CSS changes, run in a separate terminal:
```bash
pnpm run watch:css
``` ```
## Building ## Building
Build the project for production: Build for production (Node.js):
```bash ```bash
# Generate Go code from Templ files pnpm run build
go generate ./...
# Build CSS
pnpm run build:css
# Build Go binary
go build -o ./tmp/main ./cmd/schreifuchs-ch/main.go
``` ```
The output will be in the `build/` directory, ready to be served by Node.
## Image Processing ## Image Processing
To optimize images before uploading to Nextcloud: To optimize images before uploading to Nextcloud:
```bash ```bash
convert input.png -resize 3000 -quality 80 output.webp convert input.png -resize 3000 -quality 80 output.webp
``` ```
+1 -7
View File
@@ -23,19 +23,13 @@ func main() {
cancle() cancle()
}() }()
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))) slog.SetLogLoggerLevel(slog.LevelDebug)
cfg, err := config.Read(ctx) cfg, err := config.Read(ctx)
if err != nil { if err != nil {
slog.Error("could not read configuaration", "err", err) slog.Error("could not read configuaration", "err", err)
} }
slog.SetDefault(
slog.New(
slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: cfg.LogLevel}),
),
)
err = server.Start(ctx, cfg) err = server.Start(ctx, cfg)
if err != nil { if err != nil {
slog.Error("error while serving", "err", err) slog.Error("error while serving", "err", err)
+3 -5
View File
@@ -11,10 +11,7 @@ require (
github.com/sethvargo/go-envconfig v1.3.0 github.com/sethvargo/go-envconfig v1.3.0
github.com/studio-b12/gowebdav v0.12.0 github.com/studio-b12/gowebdav v0.12.0
github.com/valkey-io/valkey-go v1.0.72 github.com/valkey-io/valkey-go v1.0.72
github.com/valkey-io/valkey-go/mock v1.0.72
go.uber.org/mock v0.6.0
golang.org/x/image v0.36.0 golang.org/x/image v0.36.0
golang.org/x/sync v0.16.0
) )
require ( require (
@@ -28,8 +25,9 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/natefinch/atomic v1.0.1 // indirect github.com/natefinch/atomic v1.0.1 // indirect
github.com/yuin/gopher-lua v1.1.1 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect
golang.org/x/mod v0.27.0 // indirect golang.org/x/mod v0.26.0 // indirect
golang.org/x/net v0.48.0 // indirect golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.16.0 // indirect
golang.org/x/sys v0.39.0 // indirect golang.org/x/sys v0.39.0 // indirect
golang.org/x/tools v0.36.0 // indirect golang.org/x/tools v0.35.0 // indirect
) )
+4 -8
View File
@@ -39,18 +39,14 @@ github.com/studio-b12/gowebdav v0.12.0 h1:kFRtQECt8jmVAvA6RHBz3geXUGJHUZA6/IKpOV
github.com/studio-b12/gowebdav v0.12.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE= github.com/studio-b12/gowebdav v0.12.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE=
github.com/valkey-io/valkey-go v1.0.72 h1:iRWt1hJyOchcEgbHSkRY3aKkcBudxvMaVMsmxuYxuxE= github.com/valkey-io/valkey-go v1.0.72 h1:iRWt1hJyOchcEgbHSkRY3aKkcBudxvMaVMsmxuYxuxE=
github.com/valkey-io/valkey-go v1.0.72/go.mod h1:VGhZ6fs68Qrn2+OhH+6waZH27bjpgQOiLyUQyXuYK5k= github.com/valkey-io/valkey-go v1.0.72/go.mod h1:VGhZ6fs68Qrn2+OhH+6waZH27bjpgQOiLyUQyXuYK5k=
github.com/valkey-io/valkey-go/mock v1.0.72 h1:rE8K/sjlX0SRldI70Rt4/MCrYl224XD4A4vkYegP1Iw=
github.com/valkey-io/valkey-go/mock v1.0.72/go.mod h1:A4B8L3Wg85yAOl/GwNgkO/6aeGNXydwBl+86e20NQQY=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M= github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw= github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/image v0.36.0 h1:Iknbfm1afbgtwPTmHnS2gTM/6PPZfH+z2EFuOkSbqwc= golang.org/x/image v0.36.0 h1:Iknbfm1afbgtwPTmHnS2gTM/6PPZfH+z2EFuOkSbqwc=
golang.org/x/image v0.36.0/go.mod h1:YsWD2TyyGKiIX1kZlu9QfKIsQ4nAAK9bdgdrIsE7xy4= golang.org/x/image v0.36.0/go.mod h1:YsWD2TyyGKiIX1kZlu9QfKIsQ4nAAK9bdgdrIsE7xy4=
golang.org/x/mod v0.27.0 h1:kb+q2PyFnEADO2IEF935ehFUXlWiNjJWtRNgBLSfbxQ= golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg=
golang.org/x/mod v0.27.0/go.mod h1:rWI627Fq0DEoudcK+MBkNkCe0EetEaDSwJJkCcjpazc= golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
@@ -61,7 +57,7 @@ golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
golang.org/x/tools v0.36.0 h1:kWS0uv/zsvHEle1LbV5LE8QujrxB3wfQyxHfhOk0Qkg= golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0=
golang.org/x/tools v0.36.0/go.mod h1:WBDiHKJK8YgLHlcQPYQzNCkUxUypCaa5ZegCVutKm+s= golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+2 -2
View File
@@ -13,6 +13,7 @@ import (
_ "image/png" _ "image/png"
"io" "io"
"strings" "strings"
"time"
_ "golang.org/x/image/webp" _ "golang.org/x/image/webp"
@@ -29,7 +30,6 @@ func (s *Service) getMime(path string) (mimeType string, err error) {
if mimer, ok := info.(interface{ ContentType() string }); ok { if mimer, ok := info.(interface{ ContentType() string }); ok {
mimeType = mimer.ContentType() mimeType = mimer.ContentType()
return
} }
return return
@@ -97,7 +97,7 @@ func (s *Service) GetImage(ctx context.Context, uid string, options Options) (im
if err != nil { if err != nil {
return return
} }
if err = s.cache.Do(ctx, s.cache.B().Set().Key("img:"+hash).Value(valkey.BinaryString(outBuff.Bytes())).Ex(s.cfg.CacheLifetime).Build()).Error(); err == nil { if err = s.cache.Do(ctx, s.cache.B().Set().Key("img:"+hash).Value(valkey.BinaryString(outBuff.Bytes())).Ex(time.Hour*48).Build()).Error(); err == nil {
return outBuff, "image/jpeg", err return outBuff, "image/jpeg", err
} }
@@ -1,37 +0,0 @@
package images_test
import (
"context"
"errors"
"testing"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/test/testdata"
"github.com/valkey-io/valkey-go"
"github.com/valkey-io/valkey-go/mock"
"go.uber.org/mock/gomock"
)
func Setup(ctx context.Context, ctrl *gomock.Controller) (*images.Service, *mock.Client) {
valkey := mock.NewClient(ctrl)
return images.New(testdata.FS(), &config.ImageConfig{Concurency: 1, Quality: 80}, valkey), valkey
}
func BenchmarkService_GetImage(b *testing.B) {
srv, valkeyClient := Setup(b.Context(), gomock.NewController(b))
uid, err := images.UIDFromPath("cover.jpg")
if err != nil {
b.Error("could not get uid", err)
}
b.ReportAllocs()
for b.Loop() {
valkeyClient.EXPECT().Do(gomock.Any(), gomock.Any()).Return(mock.ErrorResult(errors.New("adf")))
valkeyClient.EXPECT().Do(gomock.Any(), gomock.Any()).Return(mock.Result(valkey.ValkeyMessage{}))
_, _, err = srv.GetImage(b.Context(), uid, images.Options{Width: 500, Quality: 80})
if err != nil {
b.Error(err)
}
}
}
+7 -14
View File
@@ -9,11 +9,6 @@ import (
"strings" "strings"
) )
const (
sourceSetSteps = 300
sourceSetMax = 1500
)
func UIDFromPath(path string) (uid string, err error) { func UIDFromPath(path string) (uid string, err error) {
var b bytes.Buffer var b bytes.Buffer
// NewWriter with NoDict (nil) creates a raw DEFLATE compressor // NewWriter with NoDict (nil) creates a raw DEFLATE compressor
@@ -62,14 +57,12 @@ func PathFromUID(uid string) (string, error) {
func SourceSet(src string) string { func SourceSet(src string) string {
sb := strings.Builder{} sb := strings.Builder{}
i := 1 for i := range 19 {
for { sb.WriteString(fmt.Sprintf("%s?w=%d %dw, ", src, 100*(i+1), 100*(i+1)))
width := i * sourceSetSteps
sb.WriteString(fmt.Sprintf("%s?w=%d %dw, ", src, width, width))
if width >= sourceSetMax {
return sb.String()
}
sb.WriteRune(',')
i++
} }
i := 20
sb.WriteString(fmt.Sprintf("%s?w=%d %dw", src, 100*(i+1), 100*(i+1)))
return sb.String()
} }
+1 -3
View File
@@ -16,7 +16,6 @@ type PageHeader struct {
type Page struct { type Page struct {
PageHeader PageHeader
Content string Content string
Images []Image
} }
func (s *Service) GetPages(ctx context.Context) (pages []PageHeader, err error) { func (s *Service) GetPages(ctx context.Context) (pages []PageHeader, err error) {
@@ -47,7 +46,7 @@ func (s *Service) GetPage(ctx context.Context, uid string) (page Page, err error
return return
} }
html, imgs, err := s.getHTML(ctx, p) html, err := s.getHTML(ctx, p)
if err != nil { if err != nil {
return return
} }
@@ -55,7 +54,6 @@ func (s *Service) GetPage(ctx context.Context, uid string) (page Page, err error
page = Page{ page = Page{
PageHeader: p, PageHeader: p,
Content: string(html), Content: string(html),
Images: imgs,
} }
return return
} }
+5 -17
View File
@@ -14,13 +14,7 @@ import (
"github.com/gomarkdown/markdown/parser" "github.com/gomarkdown/markdown/parser"
) )
// image can be used to preload func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, err error) {
type Image struct {
SrcSet string
Src string
}
func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, imgs []Image, err error) {
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
p := parser.NewWithExtensions(extensions) p := parser.NewWithExtensions(extensions)
@@ -30,7 +24,7 @@ func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, img
htmlFlags := html.CommonFlags | html.HrefTargetBlank htmlFlags := html.CommonFlags | html.HrefTargetBlank
opts := html.RendererOptions{ opts := html.RendererOptions{
Flags: htmlFlags, Flags: htmlFlags,
RenderNodeHook: imageMiddleware(page, &imgs), RenderNodeHook: imageMiddleware(page),
} }
renderer := html.NewRenderer(opts) renderer := html.NewRenderer(opts)
@@ -38,7 +32,7 @@ func (s *Service) getHTML(ctx context.Context, page PageHeader) (out []byte, img
return return
} }
func imageMiddleware(page PageHeader, imgs *[]Image) func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) { func imageMiddleware(page PageHeader) func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
return func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) { return func(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
if !entering { if !entering {
return ast.GoToNext, false return ast.GoToNext, false
@@ -59,20 +53,14 @@ func imageMiddleware(page PageHeader, imgs *[]Image) func(w io.Writer, node ast.
slog.Error("could not get image url", "err", err) slog.Error("could not get image url", "err", err)
return ast.GoToNext, false return ast.GoToNext, false
} }
image := Image{
SrcSet: images.SourceSet(src),
Src: src + "?w=1024",
}
img.Attribute = &ast.Attribute{Attrs: map[string][]byte{ img.Attribute = &ast.Attribute{Attrs: map[string][]byte{
// "srcset": []byte(image.SrcSet), "srcset": []byte(images.SourceSet(src)),
"fetchpriority": []byte("low"), "fetchpriority": []byte("low"),
"loading": []byte("lazy"), "loading": []byte("lazy"),
"class": []byte("min-h-48"), "class": []byte("min-h-48"),
"src": []byte(image.Src), "src": []byte(src),
}} }}
*imgs = append(*imgs, image)
// // img.Attrs["srcset"] = // // img.Attrs["srcset"] =
} }
+1
View File
@@ -52,6 +52,7 @@ func Path(ctx context.Context, pp ...string) string {
} }
func PathForLang(ctx context.Context, lang string, pp ...string) string { func PathForLang(ctx context.Context, lang string, pp ...string) string {
slog.Info("path for lang", "path", pp)
s, ok := ctx.Value(serviceKey).(*Service) s, ok := ctx.Value(serviceKey).(*Service)
if !ok { if !ok {
slog.Error("could not extract translation service from context for translating path", "ctx", ctx, "path", pp) slog.Error("could not extract translation service from context for translating path", "ctx", ctx, "path", pp)
-13
View File
@@ -1,13 +0,0 @@
package rest
import "net/http"
type Middeware = func(next http.Handler) http.Handler
func Use(handler http.Handler, middlewares ...Middeware) http.Handler {
for _, middleware := range middlewares {
handler = middleware(handler)
}
return handler
}
+1 -13
View File
@@ -1,10 +1,8 @@
package resthome package resthome
import ( import (
"fmt"
"net/http" "net/http"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/pages"
) )
@@ -19,7 +17,6 @@ func (h *Handler) home(w http.ResponseWriter, r *http.Request) {
} }
func (h *Handler) page(w http.ResponseWriter, r *http.Request) { func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
uid := r.PathValue("uid") uid := r.PathValue("uid")
page, err := h.src.GetPage(r.Context(), uid) page, err := h.src.GetPage(r.Context(), uid)
@@ -28,14 +25,5 @@ func (h *Handler) page(w http.ResponseWriter, r *http.Request) {
return return
} }
for i, image := range page.Images { h.r.Render(r.Context(), w, r, pages.ContentPage(page))
if i > 3 {
break
}
ctx = templer.AppendHeader(ctx, fmt.Sprintf(`<link rel="preload" href="%s" as="image" />`, image.Src))
}
ctx = templer.PageTitle(ctx, page.Title)
h.r.Render(ctx, w, r, pages.ContentPage(page))
} }
+3 -6
View File
@@ -10,17 +10,14 @@ import (
) )
type Handler struct { type Handler struct {
http.Handler
src pageService src pageService
r renderer r renderer
} }
func New(renderer renderer, srv pageService) *Handler { func New(mux *http.ServeMux, renderer renderer, srv pageService) *Handler {
mux := http.NewServeMux()
h := &Handler{ h := &Handler{
Handler: mux, src: srv,
src: srv, r: renderer,
r: renderer,
} }
mux.HandleFunc("GET /{$}", h.home) mux.HandleFunc("GET /{$}", h.home)
+7 -7
View File
@@ -6,7 +6,7 @@ import (
"net/http" "net/http"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restutil"
) )
func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) { func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) {
@@ -14,20 +14,20 @@ func (h *Handler) getImage(w http.ResponseWriter, r *http.Request) {
var err error var err error
options := images.Options{} options := images.Options{}
options.Height, err = rest.IntParam(r, "h") options.Height, err = restutil.IntParam(r, "h")
if err != nil { if err != nil {
rest.SendErr(w, err) restutil.SendErr(w, err)
return return
} }
options.Width, err = rest.IntParam(r, "w") options.Width, err = restutil.IntParam(r, "w")
if err != nil { if err != nil {
rest.SendErr(w, err) restutil.SendErr(w, err)
return return
} }
options.Quality, err = rest.IntParam(r, "q") options.Quality, err = restutil.IntParam(r, "q")
if err != nil { if err != nil {
rest.SendErr(w, err) restutil.SendErr(w, err)
return return
} }
+2 -5
View File
@@ -9,15 +9,12 @@ import (
) )
type Handler struct { type Handler struct {
http.Handler
img imageService img imageService
} }
func New(srv imageService) *Handler { func New(mux *http.ServeMux, srv imageService) *Handler {
mux := http.NewServeMux()
h := &Handler{ h := &Handler{
Handler: mux, img: srv,
img: srv,
} }
mux.HandleFunc("GET /images/{uid}", h.getImage) mux.HandleFunc("GET /images/{uid}", h.getImage)
@@ -1,4 +1,4 @@
package rest package restutil
import ( import (
"encoding/json" "encoding/json"
@@ -1,4 +1,4 @@
package rest package restutil
import ( import (
"fmt" "fmt"
+2 -5
View File
@@ -1,13 +1,10 @@
package config package config
import "time"
func Default() Cfg { func Default() Cfg {
return Cfg{ return Cfg{
Image: &ImageConfig{ Image: &ImageConfig{
Concurency: 10, Concurency: 10,
Quality: 80, Quality: 80,
CacheLifetime: time.Hour * 24 * 31,
}, },
Tracking: &UmamiConfig{ Tracking: &UmamiConfig{
ScriptSrc: "https://umami.schreifuchs.ch/script.js", ScriptSrc: "https://umami.schreifuchs.ch/script.js",
+2 -8
View File
@@ -2,8 +2,6 @@ package config
import ( import (
"context" "context"
"log/slog"
"time"
"github.com/sethvargo/go-envconfig" "github.com/sethvargo/go-envconfig"
) )
@@ -13,8 +11,6 @@ type Cfg struct {
Cache *ValkeyConfig `env:", prefix=CACHE_"` Cache *ValkeyConfig `env:", prefix=CACHE_"`
Image *ImageConfig `env:", prefix=IMAGE_"` Image *ImageConfig `env:", prefix=IMAGE_"`
Tracking *UmamiConfig `env:", prefix=TRACKING_"` Tracking *UmamiConfig `env:", prefix=TRACKING_"`
LogLevel slog.Level `env:"LOG_LEVEL, default=DEBUG"`
} }
type WebdavConfig struct { type WebdavConfig struct {
@@ -37,9 +33,8 @@ type ValkeyConfig struct {
} }
type ImageConfig struct { type ImageConfig struct {
Concurency int64 `env:"CONCURENCY"` Concurency int64 `env:"CONCURENCY"`
Quality int `env:"QUALITY"` Quality int `env:"QUALITY"`
CacheLifetime time.Duration `env:"CACHE_LIFETIME"`
} }
type UmamiConfig struct { type UmamiConfig struct {
@@ -56,7 +51,6 @@ func Read(ctx context.Context) (cfg Cfg, err error) {
// overridden. // overridden.
DefaultDelimiter: ";", DefaultDelimiter: ";",
DefaultSeparator: "@", DefaultSeparator: "@",
DefaultOverwrite: true,
Lookuper: envconfig.MultiLookuper(secretLookuper(), envconfig.OsLookuper()), Lookuper: envconfig.MultiLookuper(secretLookuper(), envconfig.OsLookuper()),
}) })
-48
View File
@@ -1,48 +0,0 @@
package templer
import (
"context"
)
// GetHeader returns a slice of strings that should be added to the html head.
// Because strings are immutable a slice of strings is used.
func GetHeader(ctx context.Context) []string {
v := ctx.Value(headerKey)
if v == nil {
return []string{}
}
header, ok := v.([]string)
if !ok {
return []string{}
}
return header
}
// AppendHeader lets you add lines to the header.
func AppendHeader(ctx context.Context, v ...string) context.Context {
header := GetHeader(ctx)
header = append(header, v...)
return context.WithValue(ctx, headerKey, header)
}
// AppendHeader lets you add lines to the header.
func PageTitle(ctx context.Context, title string) context.Context {
return context.WithValue(ctx, titleKey, title)
}
// AppendHeader lets you add lines to the header.
func GetTitle(ctx context.Context, main string) string {
v := ctx.Value(titleKey)
if v == nil {
return main
}
title, ok := v.(string)
if !ok {
return main
}
return title + " | " + main
}
-2
View File
@@ -11,8 +11,6 @@ type ctxKey int
const ( const (
pathKey ctxKey = iota pathKey ctxKey = iota
headerKey
titleKey
) )
func Middleware(next http.Handler) http.HandlerFunc { func Middleware(next http.Handler) http.HandlerFunc {
@@ -1,4 +1,4 @@
package middleware package server
import ( import (
"fmt" "fmt"
@@ -17,7 +17,7 @@ func (c *captureWriter) WriteHeader(statusCode int) {
c.ResponseWriter.WriteHeader(statusCode) c.ResponseWriter.WriteHeader(statusCode)
} }
func Logging(next http.Handler) http.Handler { func (s *Server) loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now() start := time.Now()
cw := &captureWriter{ cw := &captureWriter{
@@ -35,7 +35,7 @@ func Logging(next http.Handler) http.Handler {
} }
// cacheMiddleware adds Cache-Control headers to the response. // cacheMiddleware adds Cache-Control headers to the response.
func Cache(maxAge time.Duration) func(next http.Handler) http.Handler { func cacheMiddleware(maxAge time.Duration) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds())) w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%.0f", maxAge.Seconds()))
@@ -1,50 +1,40 @@
package server package server
import ( import (
"fmt" "log/slog"
"net/http" "net/http"
"time" "time"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/images"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/page"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/rest"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/resthome" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/resthome"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restimage" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/handlers/restimage"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/filesystem" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/filesystem"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/middleware"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/layouts" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web/layouts"
"github.com/studio-b12/gowebdav" "github.com/studio-b12/gowebdav"
"github.com/valkey-io/valkey-go" "github.com/valkey-io/valkey-go"
) )
func (s *Server) allRoutes() (h http.Handler, err error) { func (s *Server) RegisterRoutes() (h http.Handler) {
mux := http.NewServeMux() mux := http.NewServeMux()
registerStatic(mux) registerStatic(mux)
mux.Handle("/", s.registerOther())
other, err := s.dynamicRoutes()
if err != nil {
return
}
mux.Handle("/", other)
h = mux h = mux
h = templer.Middleware(h) h = templer.Middleware(h)
h = middleware.Logging(h) h = s.loggingMiddleware(h)
return h, nil return h
} }
func (s *Server) dynamicRoutes() (h http.Handler, err error) { func (s *Server) registerOther() (h http.Handler) {
mux := http.NewServeMux() mux := http.NewServeMux()
webdavClient := gowebdav.NewClient(s.cfg.FileSystem.URL, s.cfg.FileSystem.User, s.cfg.FileSystem.Password) webdavClient := gowebdav.NewClient(s.cfg.FileSystem.URL, s.cfg.FileSystem.User, s.cfg.FileSystem.Password)
err = webdavClient.Connect() if err := webdavClient.Connect(); err != nil {
if err != nil { slog.Error("could not connect webdavClient", "err", err)
err = fmt.Errorf("could not connect webdavClient: %w", err)
return
} }
var fs filesystem.FS = webdavClient var fs filesystem.FS = webdavClient
@@ -54,27 +44,22 @@ func (s *Server) dynamicRoutes() (h http.Handler, err error) {
Password: s.cfg.Cache.Password, Password: s.cfg.Cache.Password,
}) })
if err != nil { if err != nil {
err = fmt.Errorf("failed to create valkey client: %w", err) slog.Error("failed to create valkey client", "err", err)
return
}
if err != nil {
} else { } else {
fs = filesystem.NewCachedClient(webdavClient, valkeyClient, 5*time.Hour) fs = filesystem.NewCachedClient(webdavClient, valkeyClient, 5*time.Hour)
} }
mux.Handle("/images/", rest.Use(
restimage.New(images.New(fs, s.cfg.Image, valkeyClient)),
middleware.Cache(time.Hour*24*5),
))
translator := translate.New()
renderer := layouts.New(s.cfg) renderer := layouts.New(s.cfg)
mux.Handle("/", rest.Use( _ = resthome.New(mux, renderer, page.New(fs))
resthome.New(renderer, page.New(fs)), _ = restimage.New(mux, images.New(fs, s.cfg.Image, valkeyClient))
translator.Middleware,
middleware.Cache(time.Minute),
))
return mux, nil mux.Handle("/", http.FileServer(http.FS(web.GetStaticFS())))
translator := translate.New()
h = mux
h = translator.Middleware(h)
h = cacheMiddleware(time.Minute * 5)(h)
return h
} }
+3 -11
View File
@@ -1,4 +1,3 @@
// Package server provides the http server for schreifuchs.ch.
package server package server
import ( import (
@@ -18,7 +17,6 @@ type Server struct {
cfg config.Cfg cfg config.Cfg
} }
// Start starts a new http server. When the context gets canceled, the server stops gracefully.
func Start(ctx context.Context, cfg config.Cfg) (err error) { func Start(ctx context.Context, cfg config.Cfg) (err error) {
port, _ := strconv.Atoi(os.Getenv("PORT")) port, _ := strconv.Atoi(os.Getenv("PORT"))
if port == 0 { if port == 0 {
@@ -29,16 +27,10 @@ func Start(ctx context.Context, cfg config.Cfg) (err error) {
cfg: cfg, cfg: cfg,
} }
hander, err := s.allRoutes()
if err != nil {
err = fmt.Errorf("could not setup routes: %w", err)
return
}
// Declare Server config // Declare Server config
srv := &http.Server{ srv := &http.Server{
Addr: fmt.Sprintf(":%d", s.port), Addr: fmt.Sprintf(":%d", s.port),
Handler: hander, Handler: s.RegisterRoutes(),
IdleTimeout: time.Minute, IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second, ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second, WriteTimeout: 30 * time.Second,
@@ -53,7 +45,7 @@ func Start(ctx context.Context, cfg config.Cfg) (err error) {
// Shutdown server when ctx done // Shutdown server when ctx done
if err = srv.Shutdown(context.Background()); err != nil { if err = srv.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout: // Error from closing listeners, or context timeout:
err = fmt.Errorf("error while shutting down server: %w", err) err = fmt.Errorf("error whilse shutting down server: %w", err)
} }
close(idleConnsClosed) close(idleConnsClosed)
@@ -61,7 +53,7 @@ func Start(ctx context.Context, cfg config.Cfg) (err error) {
slog.Info("starting server", "address", srv.Addr) slog.Info("starting server", "address", srv.Addr)
if err := srv.ListenAndServe(); err != http.ErrServerClosed { if err := srv.ListenAndServe(); err != http.ErrServerClosed {
return fmt.Errorf("error while serving: %w", err) return fmt.Errorf("error while server ListenAndServe: %w", err)
} }
<-idleConnsClosed <-idleConnsClosed
+2 -3
View File
@@ -6,7 +6,6 @@ import (
"net/http" "net/http"
"time" "time"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/middleware"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/web"
) )
@@ -15,7 +14,7 @@ func registerStatic(mux *http.ServeMux) {
fileSystem := web.GetStaticFS() fileSystem := web.GetStaticFS()
// we still use go's fileServer to avoid unnecessary implementation // we still use go's fileServer to avoid unnecessary implementation
fileServer := middleware.Cache(time.Hour * 24)(http.FileServer(http.FS(fileSystem))) fileServer := cacheMiddleware(time.Hour * 24)(http.FileServer(http.FS(fileSystem)))
err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error { err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil { if err != nil {
@@ -27,7 +26,7 @@ func registerStatic(mux *http.ServeMux) {
path = "/" + path path = "/" + path
slog.Debug("registered static file", "path", path) slog.Debug("registering file", "path", path)
mux.Handle(path, fileServer) mux.Handle(path, fileServer)
+3 -5
View File
@@ -4,9 +4,9 @@
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"build:css": "tailwindcss -i ./web/src/css/input.css -o ./web/static/css/output.css --minify", "build:css": "tailwindcss -i ./web/static/css/input.css -o ./web/static/css/output.css --minify",
"watch:css": "tailwindcss -i ./web/src/css/input.css -o ./web/static/css/output.css --watch", "watch:css": "tailwindcss -i ./web/static/css/input.css -o ./web/static/css/output.css --watch",
"build:js": "node scripts/build.mjs" "build:js": "cp node_modules/htmx.org/dist/htmx.min.js web/static/js/htmx.min.js && cp ./node_modules/htmx-ext-preload/dist/preload.min.js ./web/static/js/preload.min.js"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@@ -16,12 +16,10 @@
"@tailwindcss/cli": "^4.1.18", "@tailwindcss/cli": "^4.1.18",
"@tailwindcss/typography": "^0.5.19", "@tailwindcss/typography": "^0.5.19",
"autoprefixer": "^10.4.24", "autoprefixer": "^10.4.24",
"esbuild": "^0.27.4",
"postcss": "^8.5.6", "postcss": "^8.5.6",
"tailwindcss": "^4.1.18" "tailwindcss": "^4.1.18"
}, },
"dependencies": { "dependencies": {
"htmx-ext-head-support": "^2.0.5",
"htmx-ext-preload": "^2.1.2", "htmx-ext-preload": "^2.1.2",
"htmx.org": "^2.0.8" "htmx.org": "^2.0.8"
} }
-281
View File
@@ -8,9 +8,6 @@ importers:
.: .:
dependencies: dependencies:
htmx-ext-head-support:
specifier: ^2.0.5
version: 2.0.5
htmx-ext-preload: htmx-ext-preload:
specifier: ^2.1.2 specifier: ^2.1.2
version: 2.1.2 version: 2.1.2
@@ -27,9 +24,6 @@ importers:
autoprefixer: autoprefixer:
specifier: ^10.4.24 specifier: ^10.4.24
version: 10.4.24(postcss@8.5.6) version: 10.4.24(postcss@8.5.6)
esbuild:
specifier: ^0.27.4
version: 0.27.4
postcss: postcss:
specifier: ^8.5.6 specifier: ^8.5.6
version: 8.5.6 version: 8.5.6
@@ -39,162 +33,6 @@ importers:
packages: packages:
'@esbuild/aix-ppc64@0.27.4':
resolution: {integrity: sha512-cQPwL2mp2nSmHHJlCyoXgHGhbEPMrEEU5xhkcy3Hs/O7nGZqEpZ2sUtLaL9MORLtDfRvVl2/3PAuEkYZH0Ty8Q==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [aix]
'@esbuild/android-arm64@0.27.4':
resolution: {integrity: sha512-gdLscB7v75wRfu7QSm/zg6Rx29VLdy9eTr2t44sfTW7CxwAtQghZ4ZnqHk3/ogz7xao0QAgrkradbBzcqFPasw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
'@esbuild/android-arm@0.27.4':
resolution: {integrity: sha512-X9bUgvxiC8CHAGKYufLIHGXPJWnr0OCdR0anD2e21vdvgCI8lIfqFbnoeOz7lBjdrAGUhqLZLcQo6MLhTO2DKQ==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
'@esbuild/android-x64@0.27.4':
resolution: {integrity: sha512-PzPFnBNVF292sfpfhiyiXCGSn9HZg5BcAz+ivBuSsl6Rk4ga1oEXAamhOXRFyMcjwr2DVtm40G65N3GLeH1Lvw==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
'@esbuild/darwin-arm64@0.27.4':
resolution: {integrity: sha512-b7xaGIwdJlht8ZFCvMkpDN6uiSmnxxK56N2GDTMYPr2/gzvfdQN8rTfBsvVKmIVY/X7EM+/hJKEIbbHs9oA4tQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
'@esbuild/darwin-x64@0.27.4':
resolution: {integrity: sha512-sR+OiKLwd15nmCdqpXMnuJ9W2kpy0KigzqScqHI3Hqwr7IXxBp3Yva+yJwoqh7rE8V77tdoheRYataNKL4QrPw==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
'@esbuild/freebsd-arm64@0.27.4':
resolution: {integrity: sha512-jnfpKe+p79tCnm4GVav68A7tUFeKQwQyLgESwEAUzyxk/TJr4QdGog9sqWNcUbr/bZt/O/HXouspuQDd9JxFSw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
'@esbuild/freebsd-x64@0.27.4':
resolution: {integrity: sha512-2kb4ceA/CpfUrIcTUl1wrP/9ad9Atrp5J94Lq69w7UwOMolPIGrfLSvAKJp0RTvkPPyn6CIWrNy13kyLikZRZQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
'@esbuild/linux-arm64@0.27.4':
resolution: {integrity: sha512-7nQOttdzVGth1iz57kxg9uCz57dxQLHWxopL6mYuYthohPKEK0vU0C3O21CcBK6KDlkYVcnDXY099HcCDXd9dA==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
'@esbuild/linux-arm@0.27.4':
resolution: {integrity: sha512-aBYgcIxX/wd5n2ys0yESGeYMGF+pv6g0DhZr3G1ZG4jMfruU9Tl1i2Z+Wnj9/KjGz1lTLCcorqE2viePZqj4Eg==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
'@esbuild/linux-ia32@0.27.4':
resolution: {integrity: sha512-oPtixtAIzgvzYcKBQM/qZ3R+9TEUd1aNJQu0HhGyqtx6oS7qTpvjheIWBbes4+qu1bNlo2V4cbkISr8q6gRBFA==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
'@esbuild/linux-loong64@0.27.4':
resolution: {integrity: sha512-8mL/vh8qeCoRcFH2nM8wm5uJP+ZcVYGGayMavi8GmRJjuI3g1v6Z7Ni0JJKAJW+m0EtUuARb6Lmp4hMjzCBWzA==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
'@esbuild/linux-mips64el@0.27.4':
resolution: {integrity: sha512-1RdrWFFiiLIW7LQq9Q2NES+HiD4NyT8Itj9AUeCl0IVCA459WnPhREKgwrpaIfTOe+/2rdntisegiPWn/r/aAw==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
'@esbuild/linux-ppc64@0.27.4':
resolution: {integrity: sha512-tLCwNG47l3sd9lpfyx9LAGEGItCUeRCWeAx6x2Jmbav65nAwoPXfewtAdtbtit/pJFLUWOhpv0FpS6GQAmPrHA==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
'@esbuild/linux-riscv64@0.27.4':
resolution: {integrity: sha512-BnASypppbUWyqjd1KIpU4AUBiIhVr6YlHx/cnPgqEkNoVOhHg+YiSVxM1RLfiy4t9cAulbRGTNCKOcqHrEQLIw==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
'@esbuild/linux-s390x@0.27.4':
resolution: {integrity: sha512-+eUqgb/Z7vxVLezG8bVB9SfBie89gMueS+I0xYh2tJdw3vqA/0ImZJ2ROeWwVJN59ihBeZ7Tu92dF/5dy5FttA==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
'@esbuild/linux-x64@0.27.4':
resolution: {integrity: sha512-S5qOXrKV8BQEzJPVxAwnryi2+Iq5pB40gTEIT69BQONqR7JH1EPIcQ/Uiv9mCnn05jff9umq/5nqzxlqTOg9NA==}
engines: {node: '>=18'}
cpu: [x64]
os: [linux]
'@esbuild/netbsd-arm64@0.27.4':
resolution: {integrity: sha512-xHT8X4sb0GS8qTqiwzHqpY00C95DPAq7nAwX35Ie/s+LO9830hrMd3oX0ZMKLvy7vsonee73x0lmcdOVXFzd6Q==}
engines: {node: '>=18'}
cpu: [arm64]
os: [netbsd]
'@esbuild/netbsd-x64@0.27.4':
resolution: {integrity: sha512-RugOvOdXfdyi5Tyv40kgQnI0byv66BFgAqjdgtAKqHoZTbTF2QqfQrFwa7cHEORJf6X2ht+l9ABLMP0dnKYsgg==}
engines: {node: '>=18'}
cpu: [x64]
os: [netbsd]
'@esbuild/openbsd-arm64@0.27.4':
resolution: {integrity: sha512-2MyL3IAaTX+1/qP0O1SwskwcwCoOI4kV2IBX1xYnDDqthmq5ArrW94qSIKCAuRraMgPOmG0RDTA74mzYNQA9ow==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openbsd]
'@esbuild/openbsd-x64@0.27.4':
resolution: {integrity: sha512-u8fg/jQ5aQDfsnIV6+KwLOf1CmJnfu1ShpwqdwC0uA7ZPwFws55Ngc12vBdeUdnuWoQYx/SOQLGDcdlfXhYmXQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [openbsd]
'@esbuild/openharmony-arm64@0.27.4':
resolution: {integrity: sha512-JkTZrl6VbyO8lDQO3yv26nNr2RM2yZzNrNHEsj9bm6dOwwu9OYN28CjzZkH57bh4w0I2F7IodpQvUAEd1mbWXg==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openharmony]
'@esbuild/sunos-x64@0.27.4':
resolution: {integrity: sha512-/gOzgaewZJfeJTlsWhvUEmUG4tWEY2Spp5M20INYRg2ZKl9QPO3QEEgPeRtLjEWSW8FilRNacPOg8R1uaYkA6g==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
'@esbuild/win32-arm64@0.27.4':
resolution: {integrity: sha512-Z9SExBg2y32smoDQdf1HRwHRt6vAHLXcxD2uGgO/v2jK7Y718Ix4ndsbNMU/+1Qiem9OiOdaqitioZwxivhXYg==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
'@esbuild/win32-ia32@0.27.4':
resolution: {integrity: sha512-DAyGLS0Jz5G5iixEbMHi5KdiApqHBWMGzTtMiJ72ZOLhbu/bzxgAe8Ue8CTS3n3HbIUHQz/L51yMdGMeoxXNJw==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
'@esbuild/win32-x64@0.27.4':
resolution: {integrity: sha512-+knoa0BDoeXgkNvvV1vvbZX4+hizelrkwmGJBdT17t8FNPwG2lKemmuMZlmaNQ3ws3DKKCxpb4zRZEIp3UxFCg==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
'@jridgewell/gen-mapping@0.3.13': '@jridgewell/gen-mapping@0.3.13':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -432,11 +270,6 @@ packages:
resolution: {integrity: sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg==} resolution: {integrity: sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg==}
engines: {node: '>=10.13.0'} engines: {node: '>=10.13.0'}
esbuild@0.27.4:
resolution: {integrity: sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ==}
engines: {node: '>=18'}
hasBin: true
escalade@3.2.0: escalade@3.2.0:
resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}
engines: {node: '>=6'} engines: {node: '>=6'}
@@ -447,9 +280,6 @@ packages:
graceful-fs@4.2.11: graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
htmx-ext-head-support@2.0.5:
resolution: {integrity: sha512-fTzqnCw7OnMijiS48CCBFBHTuOMvycbX0nEFRL0lkRxyu5DFWX90IV1SwXpQ92fJf02IzkXcRNyjXn3j0QtYxA==}
htmx-ext-preload@2.1.2: htmx-ext-preload@2.1.2:
resolution: {integrity: sha512-foD06XAITUUQApCUQnPexyJ6B7+4vFGMQ+t42unTVTGRu/CYHdAAt6oHg7eekPHT7NRnbM5hjnGVKtClryPabg==} resolution: {integrity: sha512-foD06XAITUUQApCUQnPexyJ6B7+4vFGMQ+t42unTVTGRu/CYHdAAt6oHg7eekPHT7NRnbM5hjnGVKtClryPabg==}
@@ -600,84 +430,6 @@ packages:
snapshots: snapshots:
'@esbuild/aix-ppc64@0.27.4':
optional: true
'@esbuild/android-arm64@0.27.4':
optional: true
'@esbuild/android-arm@0.27.4':
optional: true
'@esbuild/android-x64@0.27.4':
optional: true
'@esbuild/darwin-arm64@0.27.4':
optional: true
'@esbuild/darwin-x64@0.27.4':
optional: true
'@esbuild/freebsd-arm64@0.27.4':
optional: true
'@esbuild/freebsd-x64@0.27.4':
optional: true
'@esbuild/linux-arm64@0.27.4':
optional: true
'@esbuild/linux-arm@0.27.4':
optional: true
'@esbuild/linux-ia32@0.27.4':
optional: true
'@esbuild/linux-loong64@0.27.4':
optional: true
'@esbuild/linux-mips64el@0.27.4':
optional: true
'@esbuild/linux-ppc64@0.27.4':
optional: true
'@esbuild/linux-riscv64@0.27.4':
optional: true
'@esbuild/linux-s390x@0.27.4':
optional: true
'@esbuild/linux-x64@0.27.4':
optional: true
'@esbuild/netbsd-arm64@0.27.4':
optional: true
'@esbuild/netbsd-x64@0.27.4':
optional: true
'@esbuild/openbsd-arm64@0.27.4':
optional: true
'@esbuild/openbsd-x64@0.27.4':
optional: true
'@esbuild/openharmony-arm64@0.27.4':
optional: true
'@esbuild/sunos-x64@0.27.4':
optional: true
'@esbuild/win32-arm64@0.27.4':
optional: true
'@esbuild/win32-ia32@0.27.4':
optional: true
'@esbuild/win32-x64@0.27.4':
optional: true
'@jridgewell/gen-mapping@0.3.13': '@jridgewell/gen-mapping@0.3.13':
dependencies: dependencies:
'@jridgewell/sourcemap-codec': 1.5.5 '@jridgewell/sourcemap-codec': 1.5.5
@@ -865,45 +617,12 @@ snapshots:
graceful-fs: 4.2.11 graceful-fs: 4.2.11
tapable: 2.3.0 tapable: 2.3.0
esbuild@0.27.4:
optionalDependencies:
'@esbuild/aix-ppc64': 0.27.4
'@esbuild/android-arm': 0.27.4
'@esbuild/android-arm64': 0.27.4
'@esbuild/android-x64': 0.27.4
'@esbuild/darwin-arm64': 0.27.4
'@esbuild/darwin-x64': 0.27.4
'@esbuild/freebsd-arm64': 0.27.4
'@esbuild/freebsd-x64': 0.27.4
'@esbuild/linux-arm': 0.27.4
'@esbuild/linux-arm64': 0.27.4
'@esbuild/linux-ia32': 0.27.4
'@esbuild/linux-loong64': 0.27.4
'@esbuild/linux-mips64el': 0.27.4
'@esbuild/linux-ppc64': 0.27.4
'@esbuild/linux-riscv64': 0.27.4
'@esbuild/linux-s390x': 0.27.4
'@esbuild/linux-x64': 0.27.4
'@esbuild/netbsd-arm64': 0.27.4
'@esbuild/netbsd-x64': 0.27.4
'@esbuild/openbsd-arm64': 0.27.4
'@esbuild/openbsd-x64': 0.27.4
'@esbuild/openharmony-arm64': 0.27.4
'@esbuild/sunos-x64': 0.27.4
'@esbuild/win32-arm64': 0.27.4
'@esbuild/win32-ia32': 0.27.4
'@esbuild/win32-x64': 0.27.4
escalade@3.2.0: {} escalade@3.2.0: {}
fraction.js@5.3.4: {} fraction.js@5.3.4: {}
graceful-fs@4.2.11: {} graceful-fs@4.2.11: {}
htmx-ext-head-support@2.0.5:
dependencies:
htmx.org: 2.0.8
htmx-ext-preload@2.1.2: htmx-ext-preload@2.1.2:
dependencies: dependencies:
htmx.org: 2.0.8 htmx.org: 2.0.8
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 439 KiB

+1976
View File
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 112 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 439 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 439 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 439 KiB

-69
View File
@@ -1,69 +0,0 @@
import * as esbuild from "esbuild";
import fs from "node:fs/promises";
import path from "node:path";
const filesToCopy = [
"node_modules/htmx.org/dist/htmx.min.js",
"node_modules/htmx-ext-preload/dist/preload.min.js",
"node_modules/htmx-ext-head-support/dist/head-support.min.js",
];
const filesToMinifyRoot = "web/src/js";
const outputRoot = "web/static/js";
async function minifyFiles() {
try {
const files = (await fs.readdir(filesToMinifyRoot))
.filter((p) => p.endsWith(".js"))
.map((p) => {
return {
src: path.join(filesToMinifyRoot, p),
dest: path.join(outputRoot, p.substring(0, p.length - 3) + ".min.js"),
};
});
for (const file of files) {
await esbuild.build({
entryPoints: [file.src],
bundle: false,
minify: true,
outfile: file.dest,
});
console.log(`Minified ${file.src} to ${file.dest}`);
}
} catch (err) {
console.error("could not minify files", err);
}
}
async function coppyFromNodemodules() {
try {
const fileMap = filesToCopy.map((file) => {
return {
src: file,
dest: path.join(outputRoot, path.basename(file)),
};
});
for (const file of fileMap) {
await fs.copyFile(file.src, file.dest);
console.log(`Copied ${path.basename(file.dest)}`);
}
} catch (err) {
console.error("JS build failed:", err);
process.exit(2);
}
}
async function build() {
console.log("Starting JS build...");
await minifyFiles();
await coppyFromNodemodules();
console.log("JS build complete!");
}
build();
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 MiB

-62
View File
@@ -1,62 +0,0 @@
package testdata
import (
"bytes"
"embed"
"io"
"os"
"strings"
)
//go:embed *
var fs embed.FS
func FS() mockFS {
return mockFS{
FS: fs,
}
}
type mockFS struct {
embed.FS
}
type mockMimer struct{ os.FileInfo }
func (m *mockMimer) ContentType() string {
parts := strings.Split(m.Name(), ".")
suffix := parts[len(parts)-1]
switch suffix {
case "jpg":
return "image/jpeg"
default:
return ""
}
}
func (m mockFS) Read(path string) (b []byte, err error) {
file, err := m.Open(path)
if err != nil {
return
}
defer file.Close()
buff := bytes.NewBuffer(make([]byte, 0, 1024))
_, err = io.Copy(buff, file)
return buff.Bytes(), err
}
func (m mockFS) Stat(path string) (info os.FileInfo, err error) {
file, err := m.Open(path)
if err != nil {
return
}
info, err = file.Stat()
info = &mockMimer{info}
return
}
+16 -29
View File
@@ -1,47 +1,34 @@
package layouts package layouts
import ( import "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/components/translate" import "strings"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config" import "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer" import "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
"strings"
)
templ Head(cfg config.Cfg, title string) {
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>{ title }</title>
<link rel="icon" type="image/png" href="/favicon.png"/>
<link fetchpriority="high" href="/css/output.css" rel="stylesheet"/>
<script src="/js/htmx.min.js"></script>
<script src="/js/head-support.min.js"></script>
<script src="/js/preload.min.js"></script>
<script src="/js/preload-links.min.js"></script>
<script src={ cfg.Tracking.ScriptSrc } data-website-id={ cfg.Tracking.WebsiteID }></script>
for _, h := range templer.GetHeader(ctx) {
@templ.Raw(h)
}
</head>
{ children... }
}
templ Base(cfg config.Cfg, title string) { templ Base(cfg config.Cfg, title string) {
<!DOCTYPE html> <!DOCTYPE html>
<html lang={ translate.Language(ctx) }> <html lang={ translate.Language(ctx) }>
@Head(cfg, title) <head>
<body class="bg-black dark" hx-boost="true" hx-target="main" hx-ext="head-support,preload,preload-links"> <meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>{ title }</title>
<link rel="icon" type="image/png" href="/favicon.png"/>
<link fetchpriority="high" href="/css/output.css" rel="stylesheet"/>
<script fetchpriority="low" src="/js/htmx.min.js"></script>
<script src="/js/preload.min.js"></script>
<script src={ cfg.Tracking.ScriptSrc } data-website-id={ cfg.Tracking.WebsiteID }></script>
</head>
<body class="bg-black dark" hx-boost="true" hx-target="main" hx-ext="preload">
<header <header
class="fixed z-50 mix-blend-difference p-1 w-full flex justify-between items-start" class="fixed z-50 mix-blend-difference p-1 w-full flex justify-between items-start"
> >
<a class="text-white text-2xl" href={ translate.Path(ctx, "") } preload="mouseover" preload-images="true">schreifuchs.ch</a> <a class="text-white text-2xl" href={ translate.Path(ctx, "") }>schreifuchs.ch</a>
<nav class="flex gap-2 p-2"> <nav class="flex gap-2 p-2">
for _, lang := range translate.SupportedLanguages(ctx) { for _, lang := range translate.SupportedLanguages(ctx) {
<a <a
href={ translate.PathForLang(ctx, lang, strings.Split(templer.Path(ctx), "/")...) } href={ translate.PathForLang(ctx, lang, strings.Split(templer.Path(ctx), "/")...) }
hreflang={ lang } hreflang={ lang }
data-no-translate data-no-translate
preload="mouseover"
class="text-white hover:underline uppercase" class="text-white hover:underline uppercase"
> >
{ lang } { lang }
+1 -7
View File
@@ -8,7 +8,6 @@ import (
"net/http" "net/http"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config" "git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/config"
"git.schreifuchs.ch/schreifuchs/schreifuchs.ch/internal/pkg/templer"
"github.com/a-h/templ" "github.com/a-h/templ"
) )
@@ -28,15 +27,10 @@ func (l *Layouts) Render(ctx context.Context, w io.Writer, r *http.Request, comp
withLayout := !r.URL.Query().Has("c") withLayout := !r.URL.Query().Has("c")
fmt.Println("layout: ", withLayout) fmt.Println("layout: ", withLayout)
title := templer.GetTitle(ctx, "Schreifuchs")
slog.Debug("HX-Request", "value", r.Header.Get("HX-Request")) slog.Debug("HX-Request", "value", r.Header.Get("HX-Request"))
if r.Header.Get("HX-Request") != "true" { if r.Header.Get("HX-Request") != "true" {
ctx = templ.WithChildren(ctx, component) ctx = templ.WithChildren(ctx, component)
component = Base(l.cfg, title) component = Base(l.cfg, "Schreifuchs")
} else {
ctx = templ.WithChildren(ctx, component)
component = Head(l.cfg, title)
} }
if err := component.Render(ctx, w); err != nil { if err := component.Render(ctx, w); err != nil {
+1 -6
View File
@@ -9,12 +9,7 @@ import (
templ Home(pages []page.PageHeader) { templ Home(pages []page.PageHeader) {
for _, page := range pages { for _, page := range pages {
@components.ImageTile("/images/" + page.CoverImageUID) { @components.ImageTile("/images/" + page.CoverImageUID) {
<a <a class="flex items-center justify-center h-full " href={ translate.Path(ctx, "/"+page.UID) } preload="mouseover">
class="flex items-center justify-center h-full "
href={ translate.Path(ctx, "/"+page.UID) }
preload="mouseover"
hx-load-links="true"
>
<h2 <h2
class="text-3xl font-bold text-white hover:underline text-shadow-lg" class="text-3xl font-bold text-white hover:underline text-shadow-lg"
> >
-63
View File
@@ -1,63 +0,0 @@
/**
* @file preload-links.js
* @description HTMX extension to extract <link rel="preload"> from preloaded HTML responses.
* @generated By opencode (AI Agent)
* @model gemini-3-flash-preview
* @date Thu Mar 19 2026
*/
(function () {
// Save the original XHR methods
const originalOpen = XMLHttpRequest.prototype.open;
const originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
const originalSend = XMLHttpRequest.prototype.send;
// We need to track which XHRs are preloads
XMLHttpRequest.prototype.open = function () {
this._isHtmxPreload = false;
return originalOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
if (header.toLowerCase() === "hx-preloaded" && value === "true") {
this._isHtmxPreload = true;
}
return originalSetRequestHeader.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function () {
if (this._isHtmxPreload) {
this.addEventListener("load", function () {
// Parse the response text as HTML
const parser = new DOMParser();
const doc = parser.parseFromString(this.responseText, "text/html");
// Find all preload links
const links = doc.querySelectorAll('link[rel="preload"]');
links.forEach((link) => {
const href = link.getAttribute("href");
// Only inject if the current document doesn't already have it
if (
href &&
!document.querySelector(`link[rel="preload"][href="${href}"]`)
) {
const newLink = document.createElement("link");
newLink.rel = "preload";
newLink.href = href;
// Copy relevant attributes
["as", "type", "media", "fetchpriority", "crossorigin"].forEach(
(attr) => {
const val = link.getAttribute(attr);
if (val) newLink.setAttribute(attr, val);
},
);
document.head.appendChild(newLink);
}
});
});
}
return originalSend.apply(this, arguments);
};
})();
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
(function(){var H=null;function M(){}function a(e,t){if(e&&e.indexOf("<head")>-1){const g=document.createElement("html");var r=e.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");var a=r.match(/(<head(\s[^>]*>|>)([\s\S]*?)<\/head>)/im);if(a){var n=[];var d=[];var o=[];var i=[];g.innerHTML=a;var h=g.querySelector("head");var m=document.head;if(h==null){return}else{var s=new Map;for(const p of h.children){s.set(p.outerHTML,p)}}var u=H.getAttributeValue(h,"hx-head")||t;for(const x of m.children){var l=s.has(x.outerHTML);var f=x.getAttribute("hx-head")==="re-eval";var v=H.getAttributeValue(x,"hx-preserve")==="true";if(l||v){if(f){d.push(x)}else{s.delete(x.outerHTML);o.push(x)}}else{if(u==="append"){if(f){d.push(x);i.push(x)}}else{if(H.triggerEvent(document.body,"htmx:removingHeadElement",{headElement:x})!==false){d.push(x)}}}}i.push(...s.values());M("to append: ",i);for(const E of i){M("adding: ",E);var c=document.createRange().createContextualFragment(E.outerHTML);M(c);if(H.triggerEvent(document.body,"htmx:addingHeadElement",{headElement:c})!==false){m.appendChild(c);n.push(c)}}for(const b of d){if(H.triggerEvent(document.body,"htmx:removingHeadElement",{headElement:b})!==false){m.removeChild(b)}}H.triggerEvent(document.body,"htmx:afterHeadMerge",{added:n,kept:o,removed:d})}}}htmx.defineExtension("head-support",{init:function(e){H=e;htmx.on("htmx:afterSwap",function(e){let t=e.detail.xhr;if(t){var r=t.response;if(H.triggerEvent(document.body,"htmx:beforeHeadMerge",e.detail)){a(r,e.detail.boosted?"merge":"append")}}});htmx.on("htmx:historyRestore",function(e){if(H.triggerEvent(document.body,"htmx:beforeHeadMerge",e.detail)){if(e.detail.cacheMiss){a(e.detail.serverResponse,"merge")}else{a(e.detail.item.head,"merge")}}});htmx.on("htmx:historyItemCreated",function(e){var t=e.detail.item;t.head=document.head.outerHTML})}})})();
-1
View File
@@ -1 +0,0 @@
(function(){const p=XMLHttpRequest.prototype.open,a=XMLHttpRequest.prototype.setRequestHeader,l=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(){return this._isHtmxPreload=!1,p.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(r,o){return r.toLowerCase()==="hx-preloaded"&&o==="true"&&(this._isHtmxPreload=!0),a.apply(this,arguments)},XMLHttpRequest.prototype.send=function(){return this._isHtmxPreload&&this.addEventListener("load",function(){new DOMParser().parseFromString(this.responseText,"text/html").querySelectorAll('link[rel="preload"]').forEach(n=>{const t=n.getAttribute("href");if(t&&!document.querySelector(`link[rel="preload"][href="${t}"]`)){const e=document.createElement("link");e.rel="preload",e.href=t,["as","type","media","fetchpriority","crossorigin"].forEach(s=>{const i=n.getAttribute(s);i&&e.setAttribute(s,i)}),document.head.appendChild(e)}})}),l.apply(this,arguments)}})();