Merge some standalone Vite entries into index.js (#37085)

Keep `swagger` and `external-render-helper` as a standalone entries for
external render.

- Move `devtest.ts` to `modules/` as init functions
- Make external renders correctly load its helper JS and Gitea's current theme
- Make external render iframe inherit Gitea's iframe's background color to avoid flicker
- Add e2e tests for external render and OpenAPI iframe

---------

Co-authored-by: Claude (Opus 4.6) <noreply@anthropic.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
silverwind
2026-04-05 21:13:34 +02:00
committed by GitHub
parent 5f443184f3
commit a8938115d4
35 changed files with 419 additions and 247 deletions

View File

@@ -47,16 +47,22 @@ func (p *openAPIRenderer) SanitizerRules() []setting.MarkupSanitizerRule {
func (p *openAPIRenderer) GetExternalRendererOptions() (ret markup.ExternalRendererOptions) {
ret.SanitizerDisabled = true
ret.DisplayInIframe = true
ret.ContentSandbox = ""
ret.ContentSandbox = "allow-scripts allow-forms allow-modals allow-popups allow-downloads"
return ret
}
func (p *openAPIRenderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
if ctx.RenderOptions.StandalonePageOptions == nil {
opts := p.GetExternalRendererOptions()
return markup.RenderIFrame(ctx, &opts, output)
}
content, err := util.ReadWithLimit(input, int(setting.UI.MaxDisplayFileSize))
if err != nil {
return err
}
// TODO: can extract this to a tmpl file later
// HINT: SWAGGER-OPENAPI-VIEWER: another place "templates/swagger/openapi-viewer.tmpl"
_, err = io.WriteString(output, fmt.Sprintf(
`<!DOCTYPE html>
<html>

View File

@@ -38,6 +38,14 @@ var RenderBehaviorForTesting struct {
DisableAdditionalAttributes bool
}
type WebThemeInterface interface {
PublicAssetURI() string
}
type StandalonePageOptions struct {
CurrentWebTheme WebThemeInterface
}
type RenderOptions struct {
UseAbsoluteLink bool
@@ -55,7 +63,7 @@ type RenderOptions struct {
Metas map[string]string
// used by external render. the router "/org/repo/render/..." will output the rendered content in a standalone page
InStandalonePage bool
StandalonePageOptions *StandalonePageOptions
// EnableHeadingIDGeneration controls whether to auto-generate IDs for HTML headings without id attribute.
// This should be enabled for repository files and wiki pages, but disabled for comments to avoid duplicate IDs.
@@ -127,8 +135,8 @@ func (ctx *RenderContext) WithMetas(metas map[string]string) *RenderContext {
return ctx
}
func (ctx *RenderContext) WithInStandalonePage(v bool) *RenderContext {
ctx.RenderOptions.InStandalonePage = v
func (ctx *RenderContext) WithStandalonePage(opts StandalonePageOptions) *RenderContext {
ctx.RenderOptions.StandalonePageOptions = &opts
return ctx
}
@@ -197,20 +205,18 @@ func RenderString(ctx *RenderContext, content string) (string, error) {
return buf.String(), nil
}
func renderIFrame(ctx *RenderContext, sandbox string, output io.Writer) error {
func RenderIFrame(ctx *RenderContext, opts *ExternalRendererOptions, output io.Writer) error {
src := fmt.Sprintf("%s/%s/%s/render/%s/%s", setting.AppSubURL,
url.PathEscape(ctx.RenderOptions.Metas["user"]),
url.PathEscape(ctx.RenderOptions.Metas["repo"]),
util.PathEscapeSegments(ctx.RenderOptions.Metas["RefTypeNameSubURL"]),
util.PathEscapeSegments(ctx.RenderOptions.RelativePath),
)
var sandboxAttrValue template.HTML
if sandbox != "" {
sandboxAttrValue = htmlutil.HTMLFormat(`sandbox="%s"`, sandbox)
var extraAttrs template.HTML
if opts.ContentSandbox != "" {
extraAttrs = htmlutil.HTMLFormat(` sandbox="%s"`, opts.ContentSandbox)
}
iframe := htmlutil.HTMLFormat(`<iframe data-src="%s" class="external-render-iframe" %s></iframe>`, src, sandboxAttrValue)
_, err := io.WriteString(output, string(iframe))
_, err := htmlutil.HTMLPrintf(output, `<iframe data-src="%s" class="external-render-iframe"%s></iframe>`, src, extraAttrs)
return err
}
@@ -232,16 +238,17 @@ func getExternalRendererOptions(renderer Renderer) (ret ExternalRendererOptions,
func RenderWithRenderer(ctx *RenderContext, renderer Renderer, input io.Reader, output io.Writer) error {
var extraHeadHTML template.HTML
if extOpts, ok := getExternalRendererOptions(renderer); ok && extOpts.DisplayInIframe {
if !ctx.RenderOptions.InStandalonePage {
if ctx.RenderOptions.StandalonePageOptions == nil {
// for an external "DisplayInIFrame" render, it could only output its content in a standalone page
// otherwise, a <iframe> should be outputted to embed the external rendered page
return renderIFrame(ctx, extOpts.ContentSandbox, output)
return RenderIFrame(ctx, &extOpts, output)
}
// else: this is a standalone page, fallthrough to the real rendering, and add extra JS/CSS
extraStyleHref := public.AssetURI("css/external-render-iframe.css")
extraScriptSrc := public.AssetURI("js/external-render-iframe.js")
extraScriptSrc := public.AssetURI("js/external-render-helper.js")
extraLinkHref := ctx.RenderOptions.StandalonePageOptions.CurrentWebTheme.PublicAssetURI()
// "<script>" must go before "<link>", to make Golang's http.DetectContentType() can still recognize the content as "text/html"
extraHeadHTML = htmlutil.HTMLFormat(`<script type="module" src="%s"></script><link rel="stylesheet" href="%s">`, extraScriptSrc, extraStyleHref)
// DO NOT use "type=module", the script must run as early as possible, to set up the environment in the iframe
extraHeadHTML = htmlutil.HTMLFormat(`<script crossorigin src="%s"></script><link rel="stylesheet" href="%s">`, extraScriptSrc, extraLinkHref)
}
ctx.usedByRender = true

View File

@@ -0,0 +1,31 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package markup
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRenderIFrame(t *testing.T) {
render := func(ctx *RenderContext, opts ExternalRendererOptions) string {
sb := &strings.Builder{}
require.NoError(t, RenderIFrame(ctx, &opts, sb))
return sb.String()
}
ctx := NewRenderContext(t.Context()).
WithRelativePath("tree-path").
WithMetas(map[string]string{"user": "test-owner", "repo": "test-repo", "RefTypeNameSubURL": "src/branch/master"})
// the value is read from config RENDER_CONTENT_SANDBOX, empty means "disabled"
ret := render(ctx, ExternalRendererOptions{ContentSandbox: ""})
assert.Equal(t, `<iframe data-src="/test-owner/test-repo/render/src/branch/master/tree-path" class="external-render-iframe"></iframe>`, ret)
ret = render(ctx, ExternalRendererOptions{ContentSandbox: "allow"})
assert.Equal(t, `<iframe data-src="/test-owner/test-repo/render/src/branch/master/tree-path" class="external-render-iframe" sandbox="allow"></iframe>`, ret)
}

View File

@@ -125,27 +125,33 @@ func getManifestData() *manifestDataStruct {
return data
}
// getHashedPath resolves an unhashed asset path (origin path) to its content-hashed path from the frontend manifest.
// Example: getHashedPath("js/index.js") returns "js/index.C6Z2MRVQ.js"
// Falls back to returning the input path unchanged if the manifest is unavailable.
func getHashedPath(originPath string) string {
data := getManifestData()
if p, ok := data.paths[originPath]; ok {
return p
}
return originPath
}
// AssetURI returns the URI for a frontend asset.
// It may return a relative path or a full URL depending on the StaticURLPrefix setting.
// In Vite dev mode, known entry points are mapped to their source paths
// so the reverse proxy serves them from the Vite dev server.
// In production, it resolves the content-hashed path from the manifest.
func AssetURI(originPath string) string {
if src := viteDevSourceURL(originPath); src != "" {
return src
if IsViteDevMode() {
if src := viteDevSourceURL(originPath); src != "" {
return src
}
// it should be caused by incorrect vite config
setting.PanicInDevOrTesting("Failed to locate local path for managed asset URI: %s", originPath)
}
return setting.StaticURLPrefix + "/assets/" + getHashedPath(originPath)
// Try to resolve an unhashed asset path (origin path) to its content-hashed path from the frontend manifest.
// Example: "js/index.js" -> "js/index.C6Z2MRVQ.js"
data := getManifestData()
assetPath := data.paths[originPath]
if assetPath == "" {
// it should be caused by either: "incorrect vite config" or "user's custom theme"
assetPath = originPath
if !setting.IsProd {
log.Warn("Failed to find managed asset URI for origin path: %s", originPath)
}
}
return setting.StaticURLPrefix + "/assets/" + assetPath
}
// AssetNameFromHashedPath returns the asset entry name for a given hashed asset path.

View File

@@ -24,13 +24,6 @@ func TestViteManifest(t *testing.T) {
"isEntry": true,
"css": ["css/index.B3zrQPqD.css"]
},
"web_src/js/standalone/swagger.ts": {
"file": "js/swagger.SujiEmYM.js",
"name": "swagger",
"src": "web_src/js/standalone/swagger.ts",
"isEntry": true,
"css": ["css/swagger._-APWT_3.css"]
},
"web_src/css/themes/theme-gitea-dark.css": {
"file": "css/theme-gitea-dark.CyAaQnn5.css",
"name": "theme-gitea-dark",
@@ -62,12 +55,10 @@ func TestViteManifest(t *testing.T) {
// JS entries
assert.Equal(t, "js/index.C6Z2MRVQ.js", paths["js/index.js"])
assert.Equal(t, "js/swagger.SujiEmYM.js", paths["js/swagger.js"])
assert.Equal(t, "js/eventsource.sharedworker.Dug1twio.js", paths["js/eventsource.sharedworker.js"])
// Associated CSS from JS entries
assert.Equal(t, "css/index.B3zrQPqD.css", paths["css/index.css"])
assert.Equal(t, "css/swagger._-APWT_3.css", paths["css/swagger.css"])
// CSS-only entries
assert.Equal(t, "css/theme-gitea-dark.CyAaQnn5.css", paths["css/theme-gitea-dark.css"])
@@ -78,8 +69,6 @@ func TestViteManifest(t *testing.T) {
// Names: hashed path -> entry name
assert.Equal(t, "index", names["js/index.C6Z2MRVQ.js"])
assert.Equal(t, "index", names["css/index.B3zrQPqD.css"])
assert.Equal(t, "swagger", names["js/swagger.SujiEmYM.js"])
assert.Equal(t, "swagger", names["css/swagger._-APWT_3.css"])
assert.Equal(t, "theme-gitea-dark", names["css/theme-gitea-dark.CyAaQnn5.css"])
assert.Equal(t, "eventsource.sharedworker", names["js/eventsource.sharedworker.Dug1twio.js"])

View File

@@ -18,6 +18,8 @@ import (
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"github.com/go-chi/cors"
)
func CustomAssets() *assetfs.Layer {
@@ -28,6 +30,15 @@ func AssetFS() *assetfs.LayeredFS {
return assetfs.Layered(CustomAssets(), BuiltinAssets())
}
func AssetsCors() func(next http.Handler) http.Handler {
// static assets need to be served for external renders (sandboxed)
return cors.Handler(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"HEAD", "GET"},
MaxAge: 3600 * 24,
})
}
// FileHandlerFunc implements the static handler for serving files in "public" assets
func FileHandlerFunc() http.HandlerFunc {
assetFS := AssetFS()

View File

@@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web/routing"
)
@@ -70,6 +71,9 @@ func getViteDevProxy() *httputil.ReverseProxy {
return nil
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
if r.Context().Err() != nil {
return // request cancelled (e.g. client disconnected), silently ignore
}
log.Error("Error proxying to Vite dev server: %v", err)
http.Error(w, "Error proxying to Vite dev server: "+err.Error(), http.StatusBadGateway)
},
@@ -136,34 +140,33 @@ func IsViteDevMode() bool {
return isDev
}
func viteDevSourceURL(name string) string {
if !IsViteDevMode() {
return ""
}
if strings.HasPrefix(name, "css/theme-") {
// Only redirect built-in themes to Vite source; custom themes are served from custom/public/assets/css/
themeFile := strings.TrimPrefix(name, "css/")
srcPath := filepath.Join(setting.StaticRootPath, "web_src/css/themes", themeFile)
if _, err := os.Stat(srcPath); err == nil {
return setting.AppSubURL + "/web_src/css/themes/" + themeFile
}
return ""
}
if strings.HasPrefix(name, "css/") {
return setting.AppSubURL + "/web_src/" + name
}
if name == "js/eventsource.sharedworker.js" {
return setting.AppSubURL + "/web_src/js/features/eventsource.sharedworker.ts"
}
if name == "js/iife.js" {
return setting.AppSubURL + "/web_src/js/__vite_iife.js"
}
if name == "js/index.js" {
return setting.AppSubURL + "/web_src/js/index.ts"
func detectWebSrcPath(webSrcPath string) string {
localPath := util.FilePathJoinAbs(setting.StaticRootPath, "web_src", webSrcPath)
if _, err := os.Stat(localPath); err == nil {
return setting.AppSubURL + "/web_src/" + webSrcPath
}
return ""
}
func viteDevSourceURL(name string) string {
if strings.HasPrefix(name, "css/theme-") {
// Only redirect built-in themes to Vite source; custom themes are served from custom/public/assets/css/
themeFilePath := "css/themes/" + strings.TrimPrefix(name, "css/")
if srcPath := detectWebSrcPath(themeFilePath); srcPath != "" {
return srcPath
}
}
// try to map ".js" files to ".ts" files
pathPrefix, ok := strings.CutSuffix(name, ".js")
if ok {
if srcPath := detectWebSrcPath(pathPrefix + ".ts"); srcPath != "" {
return srcPath
}
}
// for all others that the names match
return detectWebSrcPath(name)
}
// isViteDevRequest returns true if the request should be proxied to the Vite dev server.
// Ref: Vite source packages/vite/src/node/constants.ts and packages/vite/src/shared/constants.ts
func isViteDevRequest(req *http.Request) bool {