nomadro/scripts/prefix-vip-paths.py
eric 56b29205e7 Integrate four verticals into nomadro portal with shared packages and API gateway.
Mount /vip with nomadvip+payjsapi, add @nomadro/pay|pb|sdk, apps/api, /admin shell, and backup/rollback scripts under git.nomadro.cn workflow.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:16:44 -05:00

94 lines
2.9 KiB
Python

#!/usr/bin/env python3
"""Prefix VIP absolute paths with vipPath() for portal mount."""
from __future__ import annotations
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] / "apps" / "nomadvip"
SKIP = {"vipPath.ts", "vip.mock.ts"}
IMPORT = 'import { vipPath } from "@vip/app/lib/vipPath";\n'
def needs_patch(t: str) -> bool:
needles = (
'href="/ebook',
"href='/ebook",
'href="/cloudphone',
'href="/topic/',
'href="/paid',
"href={`/cloudphone",
"href={`/topic/",
'courseHomeHref="/cloudphone',
'courseHomeHref: "/cloudphone',
'window.location.href = "/cloudphone',
)
return any(n in t for n in needles)
def ensure_import(t: str) -> str:
if "@vip/app/lib/vipPath" in t or "from './vipPath'" in t:
return t
lines = t.splitlines(True)
insert_at = 0
for i, line in enumerate(lines):
if line.startswith("import ") or line.startswith('"use client"') or line.startswith("'use client'"):
insert_at = i + 1
elif (
insert_at > 0
and line.strip()
and not line.startswith("import ")
and not line.startswith("//")
and not line.startswith("/*")
and not line.startswith("*")
and not line.startswith(" ")
):
break
lines.insert(insert_at, IMPORT)
return "".join(lines)
def patch(t: str) -> str:
t = ensure_import(t)
t = re.sub(r"href=\{`/cloudphone([^`]*)`\}", r"href={vipPath(`/cloudphone\1`)}", t)
t = re.sub(r"href=\{`/topic([^`]*)`\}", r"href={vipPath(`/topic\1`)}", t)
t = re.sub(r'href="(/ebook[^"]*)"', r'href={vipPath("\1")}', t)
t = re.sub(r'href="(/cloudphone[^"]*)"', r'href={vipPath("\1")}', t)
t = re.sub(r'href="(/topic/[^"]*)"', r'href={vipPath("\1")}', t)
t = re.sub(r'href="(/paid[^"]*)"', r'href={vipPath("\1")}', t)
t = re.sub(r'courseHomeHref="(/cloudphone[^"]*)"', r'courseHomeHref={vipPath("\1")}', t)
t = re.sub(r'courseHomeHref:\s*"( /cloudphone[^"]*)"'.replace(" ", ""), r'courseHomeHref: vipPath("\1")', t)
t = re.sub(
r'courseHomeHref:\s*"(/cloudphone[^"]*)"',
r'courseHomeHref: vipPath("\1")',
t,
)
t = re.sub(
r'window\.location\.href\s*=\s*"(/cloudphone[^"]*)"',
r'window.location.href = vipPath("\1")',
t,
)
return t
def main() -> None:
n = 0
for f in list(ROOT.rglob("*.tsx")) + list(ROOT.rglob("*.ts")):
if f.name in SKIP:
continue
if "node_modules" in f.parts or ".next" in f.parts:
continue
text = f.read_text(encoding="utf-8")
if not needs_patch(text):
continue
new = patch(text)
if new != text:
f.write_text(new, encoding="utf-8")
print("patched", f.relative_to(ROOT))
n += 1
print("files", n)
if __name__ == "__main__":
main()