gui: native WebView host as nested module yetano.dev/yetano/core/gui
Extracted from prototypes/yetano-webview (AP1): packages assets, document, bridge and window (macOS Cocoa/WKWebView via cgo, Windows Win32/WebView2 pure Go). No local HTTP listener or port: assets go through the WebView's resource handler, app routes through the native message binding. Own go.mod and gui/vX.Y.Z tags keep cgo and the WebView dependencies out of the main core module. Adds backend-free tests for the window's dispatch/destroy guards and a yet-gui migration guide. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
90132e2d76
commit
8c63d42a27
27 files changed
+4849
-3
No files matched your search
@@ -0,0 +1,267 @@
|
||||
package document
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"yetano.dev/yetano/core/gui/assets"
|
||||
)
|
||||
|
||||
// rewriteCSS replaces url(...) and @import references in css. base is the
|
||||
// virtual path of the stylesheet ("" for CSS embedded in the entry HTML);
|
||||
// relative references resolve against it. Comments and strings outside of
|
||||
// url()/@import are copied untouched.
|
||||
func (p *preparer) rewriteCSS(ctx context.Context, css, base string) (string, error) {
|
||||
var out strings.Builder
|
||||
i := 0
|
||||
n := len(css)
|
||||
for i < n {
|
||||
c := css[i]
|
||||
switch {
|
||||
case c == '/' && i+1 < n && css[i+1] == '*':
|
||||
end := strings.Index(css[i+2:], "*/")
|
||||
if end < 0 {
|
||||
out.WriteString(css[i:])
|
||||
return out.String(), nil
|
||||
}
|
||||
out.WriteString(css[i : i+2+end+2])
|
||||
i += 2 + end + 2
|
||||
case c == '"' || c == '\'':
|
||||
j := skipString(css, i)
|
||||
out.WriteString(css[i:j])
|
||||
i = j
|
||||
case c == '\\' && i+1 < n:
|
||||
out.WriteString(css[i : i+2])
|
||||
i += 2
|
||||
case hasFoldPrefix(css[i:], "url(") && isIdentBoundary(css, i):
|
||||
ref, end, ok := parseURLToken(css, i+4)
|
||||
if !ok {
|
||||
out.WriteByte(c)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
repl, err := p.cssRef(ctx, ref, base, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if repl == strings.TrimSpace(ref) {
|
||||
out.WriteString(css[i:end]) // not an asset: byte-identical
|
||||
} else {
|
||||
out.WriteString("url(" + quoteCSS(repl) + ")")
|
||||
}
|
||||
i = end
|
||||
case c == '@' && hasFoldPrefix(css[i:], "@import") && i+7 < n && !isIdentChar(css[i+7]):
|
||||
j := i + 7
|
||||
for j < n && isSpace(css[j]) {
|
||||
j++
|
||||
}
|
||||
var ref string
|
||||
var end int
|
||||
switch {
|
||||
case j < n && (css[j] == '"' || css[j] == '\''):
|
||||
end = skipString(css, j)
|
||||
ref = unquoteCSS(css[j:end])
|
||||
case hasFoldPrefix(css[j:], "url("):
|
||||
var ok bool
|
||||
ref, end, ok = parseURLToken(css, j+4)
|
||||
if !ok {
|
||||
out.WriteString(css[i:j])
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
default:
|
||||
out.WriteString(css[i:j])
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
repl, err := p.cssRef(ctx, ref, base, true)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if repl == strings.TrimSpace(ref) {
|
||||
out.WriteString(css[i:end])
|
||||
} else {
|
||||
out.WriteString("@import url(" + quoteCSS(repl) + ")")
|
||||
}
|
||||
i = end
|
||||
default:
|
||||
out.WriteByte(c)
|
||||
i++
|
||||
}
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
// cssRef resolves one reference found in CSS. Data URLs, fragments and
|
||||
// external URLs are left alone.
|
||||
func (p *preparer) cssRef(ctx context.Context, ref, base string, isImport bool) (string, error) {
|
||||
ref = strings.TrimSpace(ref)
|
||||
var name string
|
||||
var err error
|
||||
switch {
|
||||
case ref == "" || strings.HasPrefix(ref, "#") || strings.HasPrefix(ref, "data:"):
|
||||
return ref, nil
|
||||
case assets.IsAssetRef(ref):
|
||||
name, err = assets.FromRef(ref)
|
||||
case hasScheme(ref) || strings.HasPrefix(ref, "//") || strings.HasPrefix(ref, "/"):
|
||||
return ref, nil // external or not an asset: untouched
|
||||
case base != "":
|
||||
pth, _ := assets.SplitRef(ref)
|
||||
name, err = assets.Join(base, pth)
|
||||
if err == nil && p.link {
|
||||
// The WebView resolves relative URLs itself; only validate.
|
||||
if _, err := p.resolve(ctx, name, base); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
default:
|
||||
return ref, nil // relative ref in entry-level CSS: not an asset reference
|
||||
}
|
||||
if err != nil {
|
||||
return "", p.fail(base, ref, err)
|
||||
}
|
||||
if p.link {
|
||||
return p.assetDataURL(ctx, name, base)
|
||||
}
|
||||
if isImport {
|
||||
css, err := p.loadCSS(ctx, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dataURL("text/css;charset=utf-8", []byte(css)), nil
|
||||
}
|
||||
if assets.BaseMIME(mimeOf(name)) == "text/css" {
|
||||
css, err := p.loadCSS(ctx, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dataURL("text/css;charset=utf-8", []byte(css)), nil
|
||||
}
|
||||
return p.assetDataURL(ctx, name, base)
|
||||
}
|
||||
|
||||
// loadCSS loads and rewrites a stylesheet asset, detecting @import cycles.
|
||||
func (p *preparer) loadCSS(ctx context.Context, name string) (string, error) {
|
||||
for _, s := range p.cssStack {
|
||||
if s == name {
|
||||
return "", fmt.Errorf("css @import cycle: %s -> %s", strings.Join(p.cssStack, " -> "), name)
|
||||
}
|
||||
}
|
||||
res, err := p.resolve(ctx, name, p.current())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if assets.BaseMIME(res.MIME) != "text/css" {
|
||||
return "", fmt.Errorf("%s: expected text/css, got %s", name, res.MIME)
|
||||
}
|
||||
p.cssStack = append(p.cssStack, name)
|
||||
defer func() { p.cssStack = p.cssStack[:len(p.cssStack)-1] }()
|
||||
return p.rewriteCSS(ctx, string(res.Bytes), name)
|
||||
}
|
||||
|
||||
func (p *preparer) current() string {
|
||||
if len(p.cssStack) == 0 {
|
||||
return p.entry
|
||||
}
|
||||
return p.cssStack[len(p.cssStack)-1]
|
||||
}
|
||||
|
||||
// parseURLToken parses the inside of url( ... ) starting at i and returns the
|
||||
// reference and the index after ')'.
|
||||
func parseURLToken(s string, i int) (string, int, bool) {
|
||||
n := len(s)
|
||||
for i < n && isSpace(s[i]) {
|
||||
i++
|
||||
}
|
||||
if i < n && (s[i] == '"' || s[i] == '\'') {
|
||||
end := skipString(s, i)
|
||||
ref := unquoteCSS(s[i:end])
|
||||
j := end
|
||||
for j < n && isSpace(s[j]) {
|
||||
j++
|
||||
}
|
||||
if j >= n || s[j] != ')' {
|
||||
return "", 0, false
|
||||
}
|
||||
return ref, j + 1, true
|
||||
}
|
||||
start := i
|
||||
for i < n && s[i] != ')' {
|
||||
if s[i] == '\\' {
|
||||
i++
|
||||
}
|
||||
i++
|
||||
}
|
||||
if i >= n {
|
||||
return "", 0, false
|
||||
}
|
||||
return strings.TrimSpace(s[start:i]), i + 1, true
|
||||
}
|
||||
|
||||
func skipString(s string, i int) int {
|
||||
q := s[i]
|
||||
j := i + 1
|
||||
for j < len(s) {
|
||||
switch s[j] {
|
||||
case '\\':
|
||||
j += 2
|
||||
continue
|
||||
case q:
|
||||
return j + 1
|
||||
case '\n':
|
||||
return j
|
||||
}
|
||||
j++
|
||||
}
|
||||
return len(s)
|
||||
}
|
||||
|
||||
func unquoteCSS(s string) string {
|
||||
if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') && s[len(s)-1] == s[0] {
|
||||
s = s[1 : len(s)-1]
|
||||
}
|
||||
// Minimal unescape: "\x" -> "x" (hex escapes are not used in asset paths).
|
||||
if strings.IndexByte(s, '\\') < 0 {
|
||||
return s
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
i++
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func quoteCSS(s string) string {
|
||||
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\a `).Replace(s) + `"`
|
||||
}
|
||||
|
||||
func hasFoldPrefix(s, prefix string) bool {
|
||||
return len(s) >= len(prefix) && strings.EqualFold(s[:len(prefix)], prefix)
|
||||
}
|
||||
|
||||
func isIdentChar(c byte) bool {
|
||||
return c == '-' || c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c >= 0x80
|
||||
}
|
||||
|
||||
func isIdentBoundary(s string, i int) bool { return i == 0 || !isIdentChar(s[i-1]) }
|
||||
|
||||
func isSpace(c byte) bool { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' }
|
||||
|
||||
func hasScheme(ref string) bool {
|
||||
for i := 0; i < len(ref); i++ {
|
||||
c := ref[i]
|
||||
switch {
|
||||
case c == ':':
|
||||
return i > 0
|
||||
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', i > 0 && (c >= '0' && c <= '9' || c == '+' || c == '-' || c == '.'):
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
// Package document prepares HTML for display: every "/assets/..." and
|
||||
// "assets:..." reference in HTML attributes, <style> blocks, style="" and
|
||||
// referenced CSS (url(), @import) is resolved through the asset resolver and
|
||||
// replaced by a typed data: URL.
|
||||
//
|
||||
// HTML is processed with the golang.org/x/net/html tokenizer. Tokens that are
|
||||
// not changed are copied byte for byte (comments, entities, scripts, void
|
||||
// tags and formatting stay as written); only a changed start tag is
|
||||
// re-serialized.
|
||||
package document
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
|
||||
"yetano.dev/yetano/core/gui/assets"
|
||||
)
|
||||
|
||||
// DefaultMaxOutput bounds the prepared document. Data-URL navigation and
|
||||
// NavigateToString have backend limits (WebView2: 2 MB); large binaries such
|
||||
// as Go-WASM are meant to be fetched separately, not inlined.
|
||||
const DefaultMaxOutput = 1536 << 10
|
||||
|
||||
// Replacement records one rewritten reference (diagnostics).
|
||||
type Replacement struct {
|
||||
Ref string `json:"ref"`
|
||||
Asset string `json:"asset"`
|
||||
Source string `json:"source"`
|
||||
MIME string `json:"mime"`
|
||||
Size int `json:"size"`
|
||||
In string `json:"in"`
|
||||
}
|
||||
|
||||
// Result is a prepared HTML document or fragment.
|
||||
type Result struct {
|
||||
HTML []byte
|
||||
Replacements []Replacement
|
||||
}
|
||||
|
||||
// Options for Prepare.
|
||||
type Options struct {
|
||||
MaxOutput int // 0 = DefaultMaxOutput (inline mode only)
|
||||
// Link keeps resources as URLs instead of inlining them: "assets:x"
|
||||
// becomes "/assets/x", "/assets/x" stays, relative CSS references stay.
|
||||
// Every reference is still validated against the resolver. This is the
|
||||
// mode for the native resource handler, where the WebView loads each
|
||||
// resource itself.
|
||||
Link bool
|
||||
}
|
||||
|
||||
type preparer struct {
|
||||
link bool
|
||||
res *assets.Resolver
|
||||
entry string // virtual name of the HTML being prepared (diagnostics)
|
||||
cssStack []string
|
||||
repl []Replacement
|
||||
}
|
||||
|
||||
// Prepare rewrites an HTML document or fragment. entry names the source for
|
||||
// error messages (an asset path or e.g. "fragment:/fragment/card").
|
||||
func Prepare(ctx context.Context, res *assets.Resolver, entry string, src []byte, opt Options) (*Result, error) {
|
||||
r, err := prepare(ctx, res, entry, src, opt)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare %s: %w", entry, err)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func prepare(ctx context.Context, res *assets.Resolver, entry string, src []byte, opt Options) (*Result, error) {
|
||||
if opt.MaxOutput == 0 {
|
||||
opt.MaxOutput = DefaultMaxOutput
|
||||
}
|
||||
if opt.Link {
|
||||
opt.MaxOutput = 1 << 30
|
||||
}
|
||||
p := &preparer{res: res, entry: entry, link: opt.Link}
|
||||
var out bytes.Buffer
|
||||
z := html.NewTokenizer(bytes.NewReader(src))
|
||||
inStyle := false
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == html.ErrorToken {
|
||||
if z.Err() == io.EOF {
|
||||
break
|
||||
}
|
||||
return nil, fmt.Errorf("html: %w", z.Err())
|
||||
}
|
||||
raw := z.Raw()
|
||||
switch tt {
|
||||
case html.StartTagToken, html.SelfClosingTagToken:
|
||||
tok := z.Token()
|
||||
changed, err := p.rewriteTag(ctx, &tok)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if changed {
|
||||
out.WriteString(tok.String())
|
||||
} else {
|
||||
out.Write(raw)
|
||||
}
|
||||
inStyle = tt == html.StartTagToken && tok.Data == "style"
|
||||
case html.TextToken:
|
||||
if inStyle {
|
||||
css, err := p.rewriteCSS(ctx, string(raw), "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.Contains(strings.ToLower(css), "</style") {
|
||||
return nil, fmt.Errorf("rewritten <style> would contain </style")
|
||||
}
|
||||
out.WriteString(css)
|
||||
} else {
|
||||
out.Write(raw)
|
||||
}
|
||||
case html.EndTagToken:
|
||||
inStyle = false
|
||||
out.Write(raw)
|
||||
default:
|
||||
out.Write(raw)
|
||||
}
|
||||
if out.Len() > opt.MaxOutput {
|
||||
return nil, fmt.Errorf("prepared document exceeds %d bytes; load large assets via fetch instead of inlining", opt.MaxOutput)
|
||||
}
|
||||
}
|
||||
return &Result{HTML: out.Bytes(), Replacements: p.repl}, nil
|
||||
}
|
||||
|
||||
func (p *preparer) rewriteTag(ctx context.Context, tok *html.Token) (bool, error) {
|
||||
changed := false
|
||||
rel := ""
|
||||
for _, a := range tok.Attr {
|
||||
if a.Namespace == "" && a.Key == "rel" {
|
||||
rel = " " + strings.ToLower(a.Val) + " "
|
||||
}
|
||||
}
|
||||
for i := range tok.Attr {
|
||||
a := &tok.Attr[i]
|
||||
if a.Namespace != "" {
|
||||
continue
|
||||
}
|
||||
var nv string
|
||||
var err error
|
||||
did := false
|
||||
switch {
|
||||
case a.Key == "style":
|
||||
nv, err = p.rewriteCSS(ctx, a.Val, "")
|
||||
did = nv != a.Val
|
||||
case a.Key == "srcset" && (tok.Data == "img" || tok.Data == "source"):
|
||||
nv, did, err = p.rewriteSrcset(ctx, a.Val)
|
||||
case assets.IsAssetRef(strings.TrimSpace(a.Val)) && urlAttr(tok.Data, a.Key):
|
||||
ref := strings.TrimSpace(a.Val)
|
||||
if tok.Data == "link" && a.Key == "href" && strings.Contains(rel, " stylesheet ") {
|
||||
nv, err = p.stylesheetURL(ctx, ref)
|
||||
} else {
|
||||
nv, err = p.refDataURL(ctx, ref)
|
||||
}
|
||||
did = true
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if did {
|
||||
a.Val = nv
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed, nil
|
||||
}
|
||||
|
||||
// urlAttr lists the element/attribute pairs whose asset references load a
|
||||
// resource. Navigation targets (<a href>) are deliberately not inlined.
|
||||
func urlAttr(tag, key string) bool {
|
||||
switch key {
|
||||
case "src":
|
||||
switch tag {
|
||||
case "img", "script", "source", "audio", "video", "track", "input", "iframe", "embed":
|
||||
return true
|
||||
}
|
||||
case "href":
|
||||
return tag == "link" || tag == "image" || tag == "use"
|
||||
case "poster":
|
||||
return tag == "video"
|
||||
case "data":
|
||||
return tag == "object"
|
||||
case "xlink:href":
|
||||
return tag == "image" || tag == "use"
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *preparer) rewriteSrcset(ctx context.Context, v string) (string, bool, error) {
|
||||
parts := strings.Split(v, ",")
|
||||
changed := false
|
||||
for i, part := range parts {
|
||||
f := strings.Fields(part)
|
||||
if len(f) == 0 || !assets.IsAssetRef(f[0]) {
|
||||
continue
|
||||
}
|
||||
d, err := p.refDataURL(ctx, f[0])
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
f[0] = d
|
||||
parts[i] = strings.Join(f, " ")
|
||||
changed = true
|
||||
}
|
||||
return strings.Join(parts, ", "), changed, nil
|
||||
}
|
||||
|
||||
func (p *preparer) stylesheetURL(ctx context.Context, ref string) (string, error) {
|
||||
name, err := assets.FromRef(ref)
|
||||
if err != nil {
|
||||
return "", p.fail(p.entry, ref, err)
|
||||
}
|
||||
if p.link {
|
||||
return p.assetDataURL(ctx, name, p.entry)
|
||||
}
|
||||
css, err := p.loadCSS(ctx, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p.repl = append(p.repl, Replacement{Ref: ref, Asset: name, MIME: "text/css", Size: len(css), In: p.entry})
|
||||
return dataURL("text/css;charset=utf-8", []byte(css)), nil
|
||||
}
|
||||
|
||||
func (p *preparer) refDataURL(ctx context.Context, ref string) (string, error) {
|
||||
name, err := assets.FromRef(ref)
|
||||
if err != nil {
|
||||
return "", p.fail(p.entry, ref, err)
|
||||
}
|
||||
if assets.BaseMIME(mimeOf(name)) == "text/css" {
|
||||
return p.stylesheetURL(ctx, ref)
|
||||
}
|
||||
return p.assetDataURL(ctx, name, p.entry)
|
||||
}
|
||||
|
||||
func (p *preparer) assetDataURL(ctx context.Context, name, in string) (string, error) {
|
||||
if in == "" {
|
||||
in = p.entry
|
||||
}
|
||||
r, err := p.resolve(ctx, name, in)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p.repl = append(p.repl, Replacement{Ref: name, Asset: name, Source: r.Source, MIME: r.MIME, Size: len(r.Bytes), In: in})
|
||||
if p.link {
|
||||
return assets.PrefixSlash + name, nil
|
||||
}
|
||||
m := strings.ReplaceAll(r.MIME, " ", "")
|
||||
return dataURL(m, r.Bytes), nil
|
||||
}
|
||||
|
||||
func (p *preparer) resolve(ctx context.Context, name, in string) (*assets.Resource, error) {
|
||||
r, err := p.res.Resolve(ctx, name)
|
||||
if err != nil {
|
||||
if in != p.entry {
|
||||
return nil, fmt.Errorf("%s: %w", in, err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (p *preparer) fail(in, ref string, err error) error {
|
||||
if in == "" || in == p.entry {
|
||||
return fmt.Errorf("reference %q: %w", ref, err)
|
||||
}
|
||||
return fmt.Errorf("%s: reference %q: %w", in, ref, err)
|
||||
}
|
||||
|
||||
// PrepareCSS rewrites a stylesheet asset served on its own (link mode for
|
||||
// the native resource handler, inline mode otherwise).
|
||||
func PrepareCSS(ctx context.Context, res *assets.Resolver, name string, css []byte, opt Options) ([]byte, error) {
|
||||
p := &preparer{res: res, entry: name, link: opt.Link}
|
||||
out, err := p.rewriteCSS(ctx, string(css), name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("prepare %s: %w", name, err)
|
||||
}
|
||||
return []byte(out), nil
|
||||
}
|
||||
|
||||
func dataURL(mime string, data []byte) string {
|
||||
return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
func mimeOf(name string) string {
|
||||
m, _ := assets.DetectMIME(name, nil)
|
||||
return m
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package document
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"yetano.dev/yetano/core/gui/assets"
|
||||
)
|
||||
|
||||
func resolver(files map[string]string) *assets.Resolver {
|
||||
m := fstest.MapFS{}
|
||||
for k, v := range files {
|
||||
m[k] = &fstest.MapFile{Data: []byte(v)}
|
||||
}
|
||||
r, _ := assets.NewResolver(assets.NewFSSource("test", m))
|
||||
return r
|
||||
}
|
||||
|
||||
var testFiles = map[string]string{
|
||||
"images/a.svg": `<svg xmlns="http://www.w3.org/2000/svg"/>`,
|
||||
"images/b.png": "\x89PNG\r\n\x1a\nxx",
|
||||
"fonts/f.ttf": "ttf",
|
||||
"js/app.js": "console.log(1)",
|
||||
"css/app.css": `@import "base.css"; body{background:url('../images/b.png')} /* url(/assets/missing) */ .x{content:"url(x)"} .e{background:url(https://example.com/x.png)} .d{background:url(data:image/png;base64,AAAA)}`,
|
||||
"css/base.css": `@font-face{font-family:F;src:url("../fonts/f.ttf") format("truetype")}`,
|
||||
"css/cycle1.css": `@import url(cycle2.css);`,
|
||||
"css/cycle2.css": `@import "cycle1.css";`,
|
||||
"css/escape.css": `x{background:url(../../outside.png)}`,
|
||||
}
|
||||
|
||||
func prep(t *testing.T, html string) string {
|
||||
t.Helper()
|
||||
res, err := Prepare(context.Background(), resolver(testFiles), "index.html", []byte(html), Options{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(res.HTML)
|
||||
}
|
||||
|
||||
func decodeDataURL(t *testing.T, u string) string {
|
||||
t.Helper()
|
||||
i := strings.Index(u, ";base64,")
|
||||
b, err := base64.StdEncoding.DecodeString(u[i+8:])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestReplaceBothForms(t *testing.T) {
|
||||
out := prep(t, `<img src="/assets/images/a.svg"><img src='assets:images/b.png'>`)
|
||||
if !strings.Contains(out, `src="data:image/svg+xml;base64,`) || !strings.Contains(out, `src="data:image/png;base64,`) {
|
||||
t.Fatal(out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUntouchedParts(t *testing.T) {
|
||||
in := "<!doctype html>\n<!-- /assets/images/a.svg stays --><p title=\"a & b\">x < y …</p><br/><a href=\"/assets/images/a.svg\">nav</a>" +
|
||||
"<script>var s = \"<img src='/assets/images/a.svg'>\";</script><img src=\"https://example.com/x.png\"><img src=\"data:image/png;base64,AA\">"
|
||||
out := prep(t, in)
|
||||
if out != in {
|
||||
t.Fatalf("unchanged document was modified:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStylesheetCSSDependencies(t *testing.T) {
|
||||
out := prep(t, `<link rel="stylesheet" href="/assets/css/app.css">`)
|
||||
href := regexp.MustCompile(`href="([^"]+)"`).FindStringSubmatch(out)[1]
|
||||
if !strings.HasPrefix(href, "data:text/css;charset=utf-8;base64,") {
|
||||
t.Fatal(href)
|
||||
}
|
||||
css := decodeDataURL(t, href)
|
||||
for _, want := range []string{`url("data:image/png;base64,`, `@import url("data:text/css`, `/* url(/assets/missing) */`, `content:"url(x)"`, `url(https://example.com/x.png)`, `url(data:image/png;base64,AAAA)`} {
|
||||
if !strings.Contains(css, want) {
|
||||
t.Errorf("css lacks %q:\n%s", want, css)
|
||||
}
|
||||
}
|
||||
imp := regexp.MustCompile(`@import url\("([^"]+)"\)`).FindStringSubmatch(css)[1]
|
||||
if base := decodeDataURL(t, imp); !strings.Contains(base, `url("data:font/ttf;base64,`) {
|
||||
t.Errorf("font in imported css (relative to css/): %s", base)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStyleBlockSrcsetAndStyleAttr(t *testing.T) {
|
||||
out := prep(t, `<style>.h{background:url("assets:images/b.png")}</style><img srcset="/assets/images/b.png 1x, assets:images/a.svg 2x"><div style="background:url(/assets/images/b.png)"></div>`)
|
||||
if strings.Count(out, "data:image/png;base64,") != 3 || strings.Count(out, "data:image/svg+xml;base64,") != 1 {
|
||||
t.Fatal(out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrors(t *testing.T) {
|
||||
r := resolver(testFiles)
|
||||
for name, in := range map[string]string{
|
||||
"missing": `<img src="/assets/nope.png">`,
|
||||
"traversal": `<img src="/assets/../go.mod">`,
|
||||
"cycle": `<link rel="stylesheet" href="/assets/css/cycle1.css">`,
|
||||
"escape": `<link rel="stylesheet" href="/assets/css/escape.css">`,
|
||||
} {
|
||||
if _, err := Prepare(context.Background(), r, "index.html", []byte(in), Options{}); err == nil {
|
||||
t.Errorf("%s: no error", name)
|
||||
} else if !strings.Contains(err.Error(), "index.html") {
|
||||
t.Errorf("%s: error does not name the document: %v", name, err)
|
||||
}
|
||||
}
|
||||
big := `<img src="/assets/images/b.png">`
|
||||
if _, err := Prepare(context.Background(), r, "index.html", []byte(strings.Repeat(big, 100)), Options{MaxOutput: 1000}); err == nil {
|
||||
t.Error("size limit not enforced")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFragmentKeepsSemantics(t *testing.T) {
|
||||
in := `<tr><td><img src="assets:images/a.svg"></td></tr>`
|
||||
out := prep(t, in)
|
||||
if !strings.HasPrefix(out, "<tr><td><img src=\"data:") || !strings.HasSuffix(out, "></td></tr>") {
|
||||
t.Fatal(out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkMode(t *testing.T) {
|
||||
r := resolver(testFiles)
|
||||
res, err := Prepare(context.Background(), r, "index.html", []byte(`<img src="assets:images/a.svg"><link rel="stylesheet" href="/assets/css/app.css"><div style="background:url(assets:images/b.png)">`), Options{Link: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := `<img src="/assets/images/a.svg"><link rel="stylesheet" href="/assets/css/app.css"><div style="background:url("/assets/images/b.png")">`
|
||||
if string(res.HTML) != want {
|
||||
t.Fatalf("got %s\nwant %s", res.HTML, want)
|
||||
}
|
||||
css, err := PrepareCSS(context.Background(), r, "css/app.css", []byte(testFiles["css/app.css"]), Options{Link: true})
|
||||
if err != nil || string(css) != testFiles["css/app.css"] {
|
||||
t.Fatalf("relative CSS must stay byte-identical: %s %v", css, err)
|
||||
}
|
||||
if _, err := Prepare(context.Background(), r, "index.html", []byte(`<img src="assets:images/missing.png">`), Options{Link: true}); err == nil {
|
||||
t.Error("missing asset not reported in link mode")
|
||||
}
|
||||
if _, err := PrepareCSS(context.Background(), r, "css/escape.css", []byte(testFiles["css/escape.css"]), Options{Link: true}); err == nil {
|
||||
t.Error("root escape not reported in link mode")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user