webapp: add hashed minified asset pipeline

This commit is contained in:
3252a8
2026-04-26 20:04:30 +03:00
parent 250df445f0
commit 5ec179b6d6
10 changed files with 755 additions and 25 deletions
+45 -16
View File
@@ -52,6 +52,7 @@ _UNPATCHED_WIDGET_ORIGIN_SNIPPET = """ if (origin == 'https://telegram.org')
_PATCHED_WIDGET_ORIGIN_SNIPPET = """ if (origin == 'https://telegram.org') {\n origin = default_origin;\n } else if (origin == 'https://telegram-js.azureedge.net' || origin == 'https://tg.dev') {\n origin = dev_origin;\n } else {\n origin = default_origin;\n }\n""" _PATCHED_WIDGET_ORIGIN_SNIPPET = """ if (origin == 'https://telegram.org') {\n origin = default_origin;\n } else if (origin == 'https://telegram-js.azureedge.net' || origin == 'https://tg.dev') {\n origin = dev_origin;\n } else {\n origin = default_origin;\n }\n"""
WEBAPP_CONFIG_PLACEHOLDER = "<!-- WEBAPP_CONFIG_SCRIPT -->" WEBAPP_CONFIG_PLACEHOLDER = "<!-- WEBAPP_CONFIG_SCRIPT -->"
WEBAPP_I18N_PLACEHOLDER = "<!-- WEBAPP_I18N_SCRIPT -->" WEBAPP_I18N_PLACEHOLDER = "<!-- WEBAPP_I18N_SCRIPT -->"
WEBAPP_JS_PLACEHOLDER = "<!-- WEBAPP_JS_SCRIPT -->"
DEV_MOCK_START_MARKER = "<!-- WEBAPP_DEV_MOCK_START -->" DEV_MOCK_START_MARKER = "<!-- WEBAPP_DEV_MOCK_START -->"
DEV_MOCK_END_MARKER = "<!-- WEBAPP_DEV_MOCK_END -->" DEV_MOCK_END_MARKER = "<!-- WEBAPP_DEV_MOCK_END -->"
WEBAPP_RATE_LIMIT_WINDOW_SECONDS = 60 WEBAPP_RATE_LIMIT_WINDOW_SECONDS = 60
@@ -117,6 +118,7 @@ def setup_subscription_webapp_routes(app: web.Application) -> None:
app.router.add_get("/telegram-widget.js", telegram_widget_asset_route) app.router.add_get("/telegram-widget.js", telegram_widget_asset_route)
app.router.add_get(WEBAPP_LOGO_PROXY_PATH, webapp_logo_route) app.router.add_get(WEBAPP_LOGO_PROXY_PATH, webapp_logo_route)
app.router.add_get("/subscription_webapp.css", css_asset_route) app.router.add_get("/subscription_webapp.css", css_asset_route)
app.router.add_get("/subscription_webapp.min.{asset_hash}.js", js_asset_route)
app.router.add_get("/subscription_webapp.js", js_asset_route) app.router.add_get("/subscription_webapp.js", js_asset_route)
app.router.add_post("/api/auth/token", auth_token_route) app.router.add_post("/api/auth/token", auth_token_route)
app.router.add_post("/api/auth/email/request", email_auth_request_route) app.router.add_post("/api/auth/email/request", email_auth_request_route)
@@ -523,12 +525,22 @@ def _normalize_telegram_login_widget_sdk(data: bytes) -> bytes:
async def js_asset_route(request: web.Request) -> web.Response: async def js_asset_route(request: web.Request) -> web.Response:
return await _serve_template_asset( asset_hash = request.match_info.get("asset_hash")
request, filename = (
"subscription_webapp.js", f"subscription_webapp.min.{asset_hash}.js"
"application/javascript", if asset_hash
strip_dev_mock=True, else "subscription_webapp.js"
) )
response = await _serve_template_asset(
request,
filename,
"application/javascript",
strip_dev_mock=not asset_hash,
)
response.headers["Cache-Control"] = (
"public, max-age=31536000, immutable" if asset_hash else "no-cache"
)
return response
async def index_route(request: web.Request) -> web.Response: async def index_route(request: web.Request) -> web.Response:
@@ -571,6 +583,10 @@ async def index_route(request: web.Request) -> web.Response:
+ "</script>" + "</script>"
), ),
) )
html = html.replace(
WEBAPP_JS_PLACEHOLDER,
f'<script src="./{_resolve_webapp_js_asset_name()}" defer></script>',
)
return web.Response(text=html, content_type="text/html", charset="utf-8") return web.Response(text=html, content_type="text/html", charset="utf-8")
@@ -596,6 +612,19 @@ async def _serve_template_asset(
return web.Response(text=text, content_type=content_type, charset="utf-8") return web.Response(text=text, content_type=content_type, charset="utf-8")
def _resolve_webapp_js_asset_name() -> str:
minified_assets = []
for path in ASSET_DIR.glob("subscription_webapp.min.*.js"):
try:
minified_assets.append((path.stat().st_mtime, path.name))
except OSError:
continue
if minified_assets:
minified_assets.sort(reverse=True)
return minified_assets[0][1]
return "subscription_webapp.js"
def _strip_marked_block(html: str, start_marker: str, end_marker: str) -> str: def _strip_marked_block(html: str, start_marker: str, end_marker: str) -> str:
start = html.find(start_marker) start = html.find(start_marker)
if start == -1: if start == -1:
@@ -667,7 +696,7 @@ async def auth_token_route(request: web.Request) -> web.Response:
await session.commit() await session.commit()
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("WebApp auth failed: %s", exc, exc_info=True) logger.exception("WebApp auth failed")
return _json_error(500, "auth_failed", "Auth failed") return _json_error(500, "auth_failed", "Auth failed")
token = create_webapp_session_token(settings, int(authenticated_user_id)) token = create_webapp_session_token(settings, int(authenticated_user_id))
@@ -759,7 +788,7 @@ async def email_auth_verify_route(request: web.Request) -> web.Response:
await session.commit() await session.commit()
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("Email WebApp auth failed: %s", exc, exc_info=True) logger.exception("Email WebApp auth failed")
return _json_error(500, "auth_failed", "Auth failed") return _json_error(500, "auth_failed", "Auth failed")
token = create_webapp_session_token(settings, int(db_user.user_id)) token = create_webapp_session_token(settings, int(db_user.user_id))
@@ -919,7 +948,7 @@ async def account_email_verify_route(request: web.Request) -> web.Response:
return _json_error(409, "account_merge_conflict", str(exc)) return _json_error(409, "account_merge_conflict", str(exc))
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("Email account link failed: %s", exc, exc_info=True) logger.exception("Email account link failed")
return _json_error(500, "link_failed", "Link failed") return _json_error(500, "link_failed", "Link failed")
token = create_webapp_session_token(settings, int(final_user_id)) token = create_webapp_session_token(settings, int(final_user_id))
@@ -1043,7 +1072,7 @@ async def account_telegram_link_route(request: web.Request) -> web.Response:
return _json_error(409, "account_merge_conflict", str(exc)) return _json_error(409, "account_merge_conflict", str(exc))
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("Telegram account link failed: %s", exc, exc_info=True) logger.exception("Telegram account link failed")
return _json_error(500, "link_failed", "Link failed") return _json_error(500, "link_failed", "Link failed")
token = create_webapp_session_token(settings, int(final_user_id)) token = create_webapp_session_token(settings, int(final_user_id))
@@ -1106,7 +1135,7 @@ async def apply_promo_route(request: web.Request) -> web.Response:
) )
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("WebApp promo apply failed: %s", exc, exc_info=True) logger.exception("WebApp promo apply failed")
return _json_error(500, "promo_apply_failed", "Promo apply failed") return _json_error(500, "promo_apply_failed", "Promo apply failed")
@@ -1241,7 +1270,7 @@ async def _request_email_code(
return web.json_response({"ok": True}) return web.json_response({"ok": True})
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("Failed to send email verification code: %s", exc, exc_info=True) logger.exception("Failed to send email verification code")
return _json_error(502, "email_send_failed", "Failed to send email") return _json_error(502, "email_send_failed", "Failed to send email")
@@ -2015,7 +2044,7 @@ async def _create_yookassa_payment(
) )
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("YooKassa WebApp payment failed: %s", exc, exc_info=True) logger.exception("YooKassa WebApp payment failed")
return _json_error(502, "payment_failed", "Failed to create payment") return _json_error(502, "payment_failed", "Failed to create payment")
@@ -2076,7 +2105,7 @@ async def _create_freekassa_payment(
) )
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("FreeKassa WebApp payment failed: %s", exc, exc_info=True) logger.exception("FreeKassa WebApp payment failed")
return _json_error(502, "payment_failed", "Failed to create payment") return _json_error(502, "payment_failed", "Failed to create payment")
@@ -2152,7 +2181,7 @@ async def _create_platega_payment(
) )
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("Platega WebApp payment failed: %s", exc, exc_info=True) logger.exception("Platega WebApp payment failed")
return _json_error(502, "payment_failed", "Failed to create payment") return _json_error(502, "payment_failed", "Failed to create payment")
@@ -2215,7 +2244,7 @@ async def _create_severpay_payment(
) )
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("SeverPay WebApp payment failed: %s", exc, exc_info=True) logger.exception("SeverPay WebApp payment failed")
return _json_error(502, "payment_failed", "Failed to create payment") return _json_error(502, "payment_failed", "Failed to create payment")
@@ -2278,7 +2307,7 @@ async def _create_stars_payment(
) )
except Exception as exc: except Exception as exc:
await session.rollback() await session.rollback()
logger.error("Stars WebApp payment failed: %s", exc, exc_info=True) logger.exception("Stars WebApp payment failed")
return _json_error(502, "payment_failed", "Failed to create invoice") return _json_error(502, "payment_failed", "Failed to create invoice")
File diff suppressed because one or more lines are too long
@@ -291,6 +291,6 @@
<!-- WEBAPP_I18N_SCRIPT --> <!-- WEBAPP_I18N_SCRIPT -->
<!-- WEBAPP_CONFIG_SCRIPT --> <!-- WEBAPP_CONFIG_SCRIPT -->
<script src="./subscription_webapp.js" defer></script> <!-- WEBAPP_JS_SCRIPT -->
</body> </body>
</html> </html>
+5 -5
View File
@@ -435,7 +435,7 @@ const MOCK = (() => {
referral_bonus_explanation: 'Bonuses are awarded once for each invited user when they purchase a subscription.' referral_bonus_explanation: 'Bonuses are awarded once for each invited user when they purchase a subscription.'
} }
}; };
const I18N = readJsonScript('i18n') || (MOCK && MOCK.i18n) || FALLBACK_I18N; const I18N = readJsonScript('i18n') || (MOCK && MOCK.i18n) || {};
const accent = CFG.primaryColor || '#00fe7a'; const accent = CFG.primaryColor || '#00fe7a';
document.documentElement.style.setProperty('--accent', accent); document.documentElement.style.setProperty('--accent', accent);
@@ -2440,14 +2440,14 @@ const MOCK = (() => {
if (document.documentElement.lang) candidates.push(document.documentElement.lang); if (document.documentElement.lang) candidates.push(document.documentElement.lang);
for (const raw of candidates) { for (const raw of candidates) {
const short = String(raw).toLowerCase().split('-')[0]; const short = String(raw).toLowerCase().split('-')[0];
if (I18N[short]) return short; if (I18N && I18N[short]) return short;
} }
return 'ru'; return 'ru';
} }
function setLanguage(lang) { function setLanguage(lang) {
const short = String(lang || '').toLowerCase().split('-')[0]; const short = String(lang || '').toLowerCase().split('-')[0];
if (!I18N[short]) return; if (I18N && Object.keys(I18N).length && !I18N[short]) return;
state.langOverride = short; state.langOverride = short;
try { localStorage.setItem('rw_webapp_lang', short); } catch (e) { } try { localStorage.setItem('rw_webapp_lang', short); } catch (e) { }
applyI18n(); applyI18n();
@@ -2459,8 +2459,8 @@ const MOCK = (() => {
} }
function t(key, params = {}) { function t(key, params = {}) {
const table = I18N[getLanguage()] || I18N.ru; const table = (I18N && I18N[getLanguage()]) || (I18N && I18N.ru) || {};
const fallback = I18N.ru[key] || key; const fallback = (I18N && I18N.ru && I18N.ru[key]) || key;
const template = table[key] || fallback; const template = table[key] || fallback;
return template.replace(/\{(\w+)\}/g, (_, name) => ( return template.replace(/\{(\w+)\}/g, (_, name) => (
Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : '' Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : ''
File diff suppressed because one or more lines are too long
@@ -228,7 +228,7 @@
} }
.lang-dropdown-item.is-active { .lang-dropdown-item.is-active {
@apply text-[var(--accent)]; @apply bg-[var(--bg-card-hover)] text-[var(--text-primary)];
} }
.lang-dropdown-flag { .lang-dropdown-flag {
+485
View File
@@ -6,9 +6,452 @@
"": { "": {
"devDependencies": { "devDependencies": {
"@tailwindcss/cli": "4.2.4", "@tailwindcss/cli": "4.2.4",
"esbuild": "^0.28.0",
"tailwindcss": "4.2.4" "tailwindcss": "4.2.4"
} }
}, },
"node_modules/@esbuild/aix-ppc64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz",
"integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz",
"integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz",
"integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz",
"integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz",
"integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz",
"integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz",
"integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz",
"integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz",
"integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz",
"integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz",
"integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz",
"integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz",
"integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz",
"integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz",
"integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz",
"integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz",
"integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz",
"integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz",
"integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz",
"integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz",
"integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openharmony-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz",
"integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openharmony"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz",
"integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz",
"integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz",
"integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz",
"integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@jridgewell/gen-mapping": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
@@ -698,6 +1141,48 @@
"node": ">=10.13.0" "node": ">=10.13.0"
} }
}, },
"node_modules/esbuild": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz",
"integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.28.0",
"@esbuild/android-arm": "0.28.0",
"@esbuild/android-arm64": "0.28.0",
"@esbuild/android-x64": "0.28.0",
"@esbuild/darwin-arm64": "0.28.0",
"@esbuild/darwin-x64": "0.28.0",
"@esbuild/freebsd-arm64": "0.28.0",
"@esbuild/freebsd-x64": "0.28.0",
"@esbuild/linux-arm": "0.28.0",
"@esbuild/linux-arm64": "0.28.0",
"@esbuild/linux-ia32": "0.28.0",
"@esbuild/linux-loong64": "0.28.0",
"@esbuild/linux-mips64el": "0.28.0",
"@esbuild/linux-ppc64": "0.28.0",
"@esbuild/linux-riscv64": "0.28.0",
"@esbuild/linux-s390x": "0.28.0",
"@esbuild/linux-x64": "0.28.0",
"@esbuild/netbsd-arm64": "0.28.0",
"@esbuild/netbsd-x64": "0.28.0",
"@esbuild/openbsd-arm64": "0.28.0",
"@esbuild/openbsd-x64": "0.28.0",
"@esbuild/openharmony-arm64": "0.28.0",
"@esbuild/sunos-x64": "0.28.0",
"@esbuild/win32-arm64": "0.28.0",
"@esbuild/win32-ia32": "0.28.0",
"@esbuild/win32-x64": "0.28.0"
}
},
"node_modules/graceful-fs": { "node_modules/graceful-fs": {
"version": "4.2.11", "version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
+4 -1
View File
@@ -1,10 +1,13 @@
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"build:webapp:css": "tailwindcss -i ./bot/app/web/templates/subscription_webapp.tailwind.css -o ./bot/app/web/templates/subscription_webapp.css --minify" "build:webapp:css": "tailwindcss -i ./bot/app/web/templates/subscription_webapp.tailwind.css -o ./bot/app/web/templates/subscription_webapp.css --minify",
"build:webapp:js": "node ./scripts/build_subscription_webapp_js.mjs",
"build:webapp": "npm run build:webapp:css && npm run build:webapp:js"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/cli": "4.2.4", "@tailwindcss/cli": "4.2.4",
"esbuild": "^0.28.0",
"tailwindcss": "4.2.4" "tailwindcss": "4.2.4"
} }
} }
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { readFile, readdir, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { transform } from "esbuild";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, "..");
const sourcePath = path.join(
repoRoot,
"bot",
"app",
"web",
"templates",
"subscription_webapp.js",
);
function normalizeLineEndings(value) {
return value.replace(/\r\n/g, "\n");
}
function stripMarkedBlock(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
if (start === -1) {
return source;
}
const end = source.indexOf(endMarker, start);
if (end === -1) {
return source.slice(0, start);
}
return source.slice(0, start) + source.slice(end + endMarker.length);
}
function stripFallbackI18n(source) {
const fallbackStart = source.indexOf(" const FALLBACK_I18N = {");
const i18nLine = " const I18N = readJsonScript('i18n') || (MOCK && MOCK.i18n) || FALLBACK_I18N;";
const i18nLineIndex = source.indexOf(i18nLine);
if (fallbackStart === -1 || i18nLineIndex === -1 || i18nLineIndex < fallbackStart) {
return source;
}
return (
source.slice(0, fallbackStart)
+ " const I18N = readJsonScript('i18n') || (MOCK && MOCK.i18n) || {};\n"
+ source.slice(i18nLineIndex + i18nLine.length)
);
}
async function removeOldMinifiedAssets(assetDir, keepName) {
const entries = await readdir(assetDir, { withFileTypes: true });
await Promise.all(
entries
.filter(
(entry) => entry.isFile() && /^subscription_webapp\.min\.[0-9a-f]{8}\.js$/.test(entry.name) && entry.name !== keepName,
)
.map((entry) => unlink(path.join(assetDir, entry.name))),
);
}
async function main() {
const rawSource = await readFile(sourcePath, "utf8");
const withoutMocks = stripMarkedBlock(
normalizeLineEndings(rawSource),
"/* WEBAPP_DEV_MOCK_START */",
"/* WEBAPP_DEV_MOCK_END */",
);
const strippedSource = stripFallbackI18n(withoutMocks);
const result = await transform(strippedSource, {
charset: "utf8",
legalComments: "none",
loader: "js",
minify: true,
target: "es2018",
});
const code = `${result.code.replace(/[ \t]+$/gm, "").trimEnd()}\n`;
const hash = createHash("sha256").update(code, "utf8").digest("hex").slice(0, 8);
const outputPath = path.join(
path.dirname(sourcePath),
`subscription_webapp.min.${hash}.js`,
);
await removeOldMinifiedAssets(path.dirname(sourcePath), path.basename(outputPath));
await writeFile(outputPath, code, "utf8");
console.log(`Wrote ${path.relative(repoRoot, outputPath)} (${Buffer.byteLength(code, "utf8")} bytes)`);
}
await main();
+44
View File
@@ -0,0 +1,44 @@
import os
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from bot.app.web import subscription_webapp
class WebAppAssetTests(unittest.IsolatedAsyncioTestCase):
def test_resolve_webapp_js_asset_name_prefers_latest_minified_build(self):
with tempfile.TemporaryDirectory() as tmpdir:
asset_dir = Path(tmpdir)
(asset_dir / "subscription_webapp.js").write_text("console.log('fallback');", encoding="utf-8")
old_asset = asset_dir / "subscription_webapp.min.11111111.js"
new_asset = asset_dir / "subscription_webapp.min.22222222.js"
old_asset.write_text("console.log('old');", encoding="utf-8")
new_asset.write_text("console.log('new');", encoding="utf-8")
os.utime(old_asset, (1, 1))
os.utime(new_asset, (2, 2))
with patch.object(subscription_webapp, "ASSET_DIR", asset_dir):
self.assertEqual(
subscription_webapp._resolve_webapp_js_asset_name(),
"subscription_webapp.min.22222222.js",
)
async def test_js_asset_route_sets_immutable_cache_control_for_minified_asset(self):
with tempfile.TemporaryDirectory() as tmpdir:
asset_dir = Path(tmpdir)
minified_asset = asset_dir / "subscription_webapp.min.abcdef12.js"
minified_asset.write_text("console.log('minified');", encoding="utf-8")
request = SimpleNamespace(
app={"settings": SimpleNamespace(WEBAPP_ENABLED=True)},
match_info={"asset_hash": "abcdef12"},
)
with patch.object(subscription_webapp, "ASSET_DIR", asset_dir):
response = await subscription_webapp.js_asset_route(request)
self.assertEqual(response.headers["Cache-Control"], "public, max-age=31536000, immutable")
self.assertEqual(response.text, "console.log('minified');")