render.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. from __future__ import annotations
  2. import argparse
  3. import re
  4. import sys
  5. from html import escape
  6. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  7. from pathlib import Path
  8. from vendor import embed_vendor_scripts
  9. _SKILL_DIRECTORY = Path(__file__).resolve().parents[1]
  10. _FRAGMENT_PLACEHOLDER = "<!--__INLINE_VISUALIZATION_FRAGMENT__-->"
  11. _MAX_FRAGMENT_BYTES = 1_000_000
  12. _DOCUMENT_MARKUP = re.compile(r"<!doctype\s|<\s*(?:html|head|body)(?:\s|>)", re.IGNORECASE)
  13. _HOST_API_REFERENCE = re.compile(r"\b(?:window|globalThis)\.zcode\b")
  14. _RESOURCE_SOURCES = " ".join(
  15. (
  16. "blob:",
  17. "data:",
  18. "https://cdnjs.cloudflare.com",
  19. "https://cdn.jsdelivr.net",
  20. "https://esm.sh",
  21. "https://fonts.bunny.net",
  22. "https://fonts.googleapis.com",
  23. "https://fonts.gstatic.com",
  24. "https://unpkg.com",
  25. ),
  26. )
  27. _FRAME_CSP = "; ".join(
  28. (
  29. "default-src 'none'",
  30. f"script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' {_RESOURCE_SOURCES}",
  31. f"style-src 'unsafe-inline' {_RESOURCE_SOURCES}",
  32. f"img-src {_RESOURCE_SOURCES}",
  33. f"font-src {_RESOURCE_SOURCES}",
  34. f"media-src {_RESOURCE_SOURCES}",
  35. "worker-src blob:",
  36. "connect-src blob: data:",
  37. "frame-src 'none'",
  38. "object-src 'none'",
  39. "base-uri 'none'",
  40. "form-action 'none'",
  41. ),
  42. )
  43. # A srcdoc frame inherits the shell CSP, so the shell must permit resources
  44. # which the stricter inner frame policy may load.
  45. _SHELL_CSP = _FRAME_CSP.replace("frame-src 'none'", "frame-src 'self'")
  46. def _read_fragment(source: Path) -> str:
  47. if source.is_symlink() or not source.is_file():
  48. raise ValueError(f"source must be a regular file: {source}")
  49. if source.stat().st_size > _MAX_FRAGMENT_BYTES:
  50. raise ValueError("source fragment exceeds the 1 MB size limit")
  51. fragment = source.read_text(encoding="utf-8")
  52. if _DOCUMENT_MARKUP.search(fragment):
  53. raise ValueError("source must be an HTML fragment, not a complete document")
  54. return fragment
  55. def _default_title(source: Path) -> str:
  56. words = source.stem.replace("-", " ").replace("_", " ").split()
  57. return " ".join(word.capitalize() for word in words) or "Visualization"
  58. def calendar_script(fragment: str) -> str:
  59. """Register the bundled element before a fragment uses it in HTML or JavaScript."""
  60. if re.search(r"\bviz-calendar\b", fragment, re.IGNORECASE) is None:
  61. return ""
  62. source = (_SKILL_DIRECTORY / "assets" / "calendar.js").read_text(encoding="utf-8")
  63. return "<script>" + source.replace("</script", "<\\/script") + "</script>"
  64. def _render_document(fragment: str, title: str) -> str:
  65. stylesheet = (_SKILL_DIRECTORY / "assets" / "visualize.css").read_text(
  66. encoding="utf-8",
  67. )
  68. inner_kit = (_SKILL_DIRECTORY / "assets" / "visualize.html").read_text(
  69. encoding="utf-8",
  70. )
  71. host_bridge = (
  72. (_SKILL_DIRECTORY / "assets" / "standalone-host-bridge.js")
  73. .read_text(
  74. encoding="utf-8",
  75. )
  76. .replace("</script", r"<\/script")
  77. )
  78. shell = (
  79. (_SKILL_DIRECTORY / "assets" / "standalone-shell.js")
  80. .read_text(
  81. encoding="utf-8",
  82. )
  83. .replace("</script", r"<\/script")
  84. )
  85. inner_html = embed_vendor_scripts(inner_kit.replace(_FRAGMENT_PLACEHOLDER, calendar_script(fragment) + fragment))
  86. document_title = escape(title)
  87. frame_html = f"""<!doctype html>
  88. <html lang="en" data-visualize-standalone>
  89. <head>
  90. <meta charset="utf-8">
  91. <meta name="viewport" content="width=device-width, initial-scale=1">
  92. <meta name="referrer" content="no-referrer">
  93. <meta http-equiv="Content-Security-Policy" content="{_FRAME_CSP}">
  94. <title>{document_title}</title>
  95. <style>{stylesheet}
  96. html>body{{padding:0}}</style>
  97. </head>
  98. <body>
  99. <script type="application/json" id="zcode-visualization-widget-state">__ZCODE_VISUALIZATION_WIDGET_STATE__</script>
  100. <script>{host_bridge}</script>
  101. {inner_html}
  102. </body>
  103. </html>
  104. """
  105. return f"""<!doctype html>
  106. <html lang="en" data-visualize-standalone>
  107. <head>
  108. <meta charset="utf-8">
  109. <meta name="viewport" content="width=device-width, initial-scale=1">
  110. <meta name="referrer" content="no-referrer">
  111. <meta http-equiv="Content-Security-Policy" content="{_SHELL_CSP}">
  112. <title>{document_title}</title>
  113. <style>:root{{color-scheme:light dark;background:light-dark(rgb(255 255 255), rgb(24 24 24))}}html,body{{margin:0}}body{{box-sizing:border-box;padding:1rem;background:inherit}}iframe{{display:block;width:100%;height:calc(100vh - 2rem);margin:0 auto;border:0}}</style>
  114. </head>
  115. <body>
  116. <iframe id="zcode-visualization" sandbox="allow-scripts" referrerpolicy="no-referrer" title="{document_title}" data-srcdoc="{escape(frame_html)}"></iframe>
  117. <script>{shell}</script>
  118. </body>
  119. </html>
  120. """
  121. def render(fragment_path: Path, title: str | None = None) -> str:
  122. return _render_document(_read_fragment(fragment_path), title or _default_title(fragment_path))
  123. def export_html(
  124. source: Path,
  125. destination: Path,
  126. *,
  127. title: str | None = None,
  128. force: bool = False,
  129. ) -> bool:
  130. if destination.is_symlink():
  131. raise ValueError(f"destination cannot be a symbolic link: {destination}")
  132. if source.resolve() == destination.resolve() or (
  133. destination.exists() and source.samefile(destination)
  134. ):
  135. raise ValueError("source and destination must be different files")
  136. fragment = _read_fragment(source)
  137. document = _render_document(fragment, title or _default_title(source))
  138. destination.parent.mkdir(parents=True, exist_ok=True)
  139. with destination.open("w" if force else "x", encoding="utf-8", newline="\n") as output:
  140. output.write(document)
  141. return _HOST_API_REFERENCE.search(fragment) is not None
  142. def serve(document: str, port: int) -> None:
  143. encoded_document = document.encode("utf-8")
  144. class Handler(BaseHTTPRequestHandler):
  145. def do_GET(self) -> None:
  146. if self.path not in ("/", "/index.html"):
  147. self.send_error(404)
  148. return
  149. self.send_response(200)
  150. self.send_header("Content-Type", "text/html; charset=utf-8")
  151. self.send_header("Content-Length", str(len(encoded_document)))
  152. self.end_headers()
  153. self.wfile.write(encoded_document)
  154. def log_message(self, format: str, *args: object) -> None:
  155. pass
  156. server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
  157. print(f"http://127.0.0.1:{server.server_port}/", flush=True)
  158. try:
  159. server.serve_forever()
  160. except KeyboardInterrupt:
  161. pass
  162. def main(argv: list[str] | None = None) -> int:
  163. parser = argparse.ArgumentParser(
  164. description="Render an inline visualization fragment as standalone HTML.",
  165. )
  166. parser.add_argument("fragment", type=Path, help="absolute fragment HTML path")
  167. parser.add_argument(
  168. "destination",
  169. type=Path,
  170. nargs="?",
  171. help="optional output HTML path",
  172. )
  173. parser.add_argument(
  174. "--title",
  175. help="document title; defaults to the fragment file name",
  176. )
  177. parser.add_argument(
  178. "--force",
  179. action="store_true",
  180. help="replace the destination if it already exists",
  181. )
  182. parser.add_argument(
  183. "--serve",
  184. action="store_true",
  185. help="serve the rendered visualization locally",
  186. )
  187. parser.add_argument(
  188. "--port",
  189. type=int,
  190. default=0,
  191. help="local serve port; defaults to any free port",
  192. )
  193. args = parser.parse_args(argv)
  194. if args.serve and args.destination is not None:
  195. parser.error("destination cannot be used with --serve")
  196. if args.destination is not None and args.destination.exists() and not args.force:
  197. parser.error("destination already exists; pass --force to replace it")
  198. try:
  199. if args.destination is not None:
  200. references_host_api = export_html(
  201. args.fragment,
  202. args.destination,
  203. title=args.title,
  204. force=args.force,
  205. )
  206. if references_host_api:
  207. print(
  208. "warning: the source references window.zcode; verify APIs beyond "
  209. "widgetState/setWidgetState before hosting",
  210. file=sys.stderr,
  211. )
  212. print(args.destination)
  213. else:
  214. document = render(args.fragment, args.title)
  215. if args.serve:
  216. serve(document, args.port)
  217. else:
  218. sys.stdout.write(document)
  219. except (OSError, UnicodeError, ValueError) as exc:
  220. parser.error(str(exc))
  221. return 0
  222. if __name__ == "__main__":
  223. raise SystemExit(main())