transcript.md 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. transcript/__init__.py +35 -0
  2. transcript/_rule/__init__.py +0 -0
  3. transcript/_rule/archive.py +128 -0
  4. transcript/_rule/conda.py +52 -0
  5. transcript/_rule/container.py +290 -0
  6. transcript/_rule/core.py +524 -0
  7. transcript/_rule/lambdas.py +120 -0
  8. transcript/_rule/registry.py +54 -0
  9. transcript/_rule/serialize.py +26 -0
  10. transcript/_rule/snakefile.py +81 -0
  11. transcript/_rule/wildcards.py +110 -0
  12. transcript/cli.py +363 -0
  13. transcript/document.py +56 -0
  14. transcript/execute.py +240 -0
  15. transcript/html/__init__.py +17 -0
  16. transcript/html/_assets/.frontend.sha256 +1 -0
  17. transcript/html/_assets/__init__.py +21 -0
  18. transcript/html/_assets/style.min.css +1 -0
  19. transcript/html/_assets/transcript.min.js +21 -0
  20. transcript/html/_island.py +72 -0
  21. transcript/html/_navigate.py +198 -0
  22. transcript/html/_output.py +100 -0
  23. transcript/html/_resources.py +171 -0
  24. transcript/html/_review.py +34 -0
  25. transcript/html/markup.py +26 -0
  26. transcript/html/page.py +107 -0
  27. transcript/output.py +308 -0
  28. transcript/parse.py +256 -0
  29. transcript/renderers/__init__.py +126 -0
  30. transcript/renderers/bitmap.py +166 -0
  31. transcript/renderers/compose.py +174 -0
  32. transcript/renderers/compose_runtime.js +233 -0
  33. transcript/renderers/datavzrd.py +321 -0
  34. transcript/renderers/datavzrd_runtime.js +362 -0
  35. transcript/renderers/label.py +211 -0
  36. transcript/renderers/markdown.py +45 -0
  37. transcript/renderers/table.py +32 -0
  38. transcript/renderers/vegalite.py +250 -0
  39. transcript/review/__init__.py +13 -0
  40. transcript/review/_block.py +167 -0
  41. transcript/review/_migrate.py +212 -0
  42. transcript/review/_records.py +238 -0
  43. transcript/review/_span.py +287 -0
  44. transcript/review/load.py +64 -0
  45. transcript/tmd.py +159 -0
  46. transcript_md-0.1.0.dist-info/METADATA +17 -0
  47. transcript_md-0.1.0.dist-info/RECORD +49 -0
  48. transcript_md-0.1.0.dist-info/WHEEL +4 -0
  49. transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,321 @@
1
+ """Datavzrd renderer: snapshot DataFrames and build offline table reports."""
2
+
3
+ import json
4
+ import mimetypes
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+ from typing import Any, cast
11
+
12
+ from ..output import Renderer, dataframe_csv
13
+ from . import jsonify, load_spec, register
14
+
15
+ _NAMED_MAPPINGS = {"views", "datasets", "columns", "links", "link-to-url", "headers"}
16
+ _UNSUPPORTED_OPTIONS = {
17
+ "add-columns",
18
+ "aux-libraries",
19
+ "custom",
20
+ "custom-content",
21
+ "custom-path",
22
+ "custom-plot",
23
+ "render-html",
24
+ "render-img",
25
+ "render-plot",
26
+ "script-path",
27
+ "spec-path",
28
+ "spell",
29
+ "__use_yte__",
30
+ }
31
+
32
+
33
+ def _check_options(value, location: str = "config", *, properties=True) -> None:
34
+ if isinstance(value, dict):
35
+ for key, item in value.items():
36
+ # View, column and link names are user data, not option names.
37
+ is_option = properties or (
38
+ location.endswith(".link-to-url") and key == "custom-content"
39
+ )
40
+ if is_option and (key in _UNSUPPORTED_OPTIONS or key.startswith("?")):
41
+ raise ValueError(
42
+ f"Datavzrd {location}.{key} is not supported by offline table "
43
+ "outputs; use built-in render-table options without external "
44
+ "assets, custom JavaScript, plots, or spells"
45
+ )
46
+ _check_options(
47
+ item,
48
+ f"{location}.{key}",
49
+ properties=not (properties and key in _NAMED_MAPPINGS),
50
+ )
51
+ elif isinstance(value, list):
52
+ for item in value:
53
+ _check_options(item, location)
54
+
55
+
56
+ def _validate_config(config: dict):
57
+ _check_options(config)
58
+ if config.get("webview-controls", False):
59
+ raise ValueError("Datavzrd webview-controls requires an online service")
60
+ datasets = config.get("datasets", {})
61
+ if not isinstance(datasets, dict) or set(datasets) - {"data"}:
62
+ raise ValueError(
63
+ "Datavzrd config can only configure the archived dataset 'data'"
64
+ )
65
+ options = datasets.get("data", {})
66
+ if not isinstance(options, dict):
67
+ raise ValueError("Datavzrd datasets.data must be a mapping")
68
+ if "path" in options:
69
+ raise ValueError("Datavzrd datasets.data.path is managed by transcript")
70
+ if options.get("separator", ",") != "," or options.get("headers", 1) != 1:
71
+ raise ValueError("Datavzrd dataset 'data' uses CSV with one header row")
72
+ views = config.get("views")
73
+ if not isinstance(views, dict) or not views:
74
+ raise ValueError("Datavzrd config.views must contain at least one table view")
75
+ for name, view in views.items():
76
+ if not name or not isinstance(view, dict):
77
+ raise ValueError("Datavzrd views must map nonempty names to mappings")
78
+ if (
79
+ name in {".", ".."}
80
+ or name.startswith(" ")
81
+ or any(
82
+ char in "/\\:?#%" or ord(char) < 32 or 127 <= ord(char) <= 159
83
+ for char in name
84
+ )
85
+ ):
86
+ raise ValueError(
87
+ "Datavzrd view names must be plain directory names without "
88
+ "URL delimiters, control characters, or leading spaces"
89
+ )
90
+ if view.get("dataset") != "data" or "datasets" in view:
91
+ raise ValueError(f"Datavzrd view {name!r} must use dataset 'data'")
92
+ if "default-view" in config:
93
+ selected = config["default-view"]
94
+ if not isinstance(selected, str) or selected not in views:
95
+ raise ValueError("Datavzrd default-view must name an archived view")
96
+
97
+
98
+ _NUMERIC_KINDS = "iuf"
99
+ _TEXT_LIMIT = 30
100
+
101
+
102
+ def _dtype_is_numeric(dtype):
103
+ """Whether a pandas or polars column dtype is numeric, without imports."""
104
+ is_numeric = getattr(dtype, "is_numeric", None)
105
+ if callable(is_numeric):
106
+ return bool(is_numeric())
107
+ return getattr(dtype, "kind", "") in _NUMERIC_KINDS
108
+
109
+
110
+ def _columns(frame):
111
+ """Yield ``(label, dtype)`` per column, or nothing without dtype info."""
112
+ labels = getattr(frame, "columns", None)
113
+ if labels is None:
114
+ return
115
+ labels = list(labels)
116
+ dtypes = getattr(frame, "dtypes", None)
117
+ if dtypes is not None and len(dtypes) == len(labels):
118
+ pairs = zip(labels, dtypes)
119
+ else: # polars use schema
120
+ schema = getattr(frame, "schema", None)
121
+ if not isinstance(schema, Mapping):
122
+ return
123
+ pairs = ((label, schema.get(label)) for label in labels)
124
+ yield from pairs
125
+
126
+
127
+ def _text_kind(frame, label):
128
+ """Classify a column as short ``categorical`` text, ``long`` text, or None.
129
+
130
+ Only a column whose every non-missing value is a string (or a boolean)
131
+ counts; dates, numbers stored as objects, and anything else return None so
132
+ Datavzrd keeps its own default.
133
+ """
134
+ try:
135
+ series = frame[label]
136
+ except KeyError, TypeError, ValueError:
137
+ return None
138
+ to_list = getattr(series, "to_list", None)
139
+ if not callable(to_list):
140
+ return None
141
+ values = cast("list", to_list())
142
+ longest = 0
143
+ seen = False
144
+ for value in values:
145
+ if value is None:
146
+ continue
147
+ if isinstance(value, bool):
148
+ length = 1
149
+ elif isinstance(value, str):
150
+ length = len(value)
151
+ else:
152
+ return None
153
+ longest = max(longest, length)
154
+ seen = True
155
+ if not seen:
156
+ return None
157
+ return "categorical" if longest <= _TEXT_LIMIT else "long"
158
+
159
+
160
+ def _column_spec(frame, label, dtype):
161
+ """Infer one Datavzrd column spec; ``None`` leaves the column to Datavzrd."""
162
+ if _dtype_is_numeric(dtype):
163
+ return {"plot": {"bars": {}}}
164
+ kind = _text_kind(frame, label)
165
+ if kind == "categorical":
166
+ return {"plot": {"pills": {"color-scheme": "category20"}}}
167
+ if kind == "long":
168
+ return {"ellipsis": _TEXT_LIMIT}
169
+ return None
170
+
171
+
172
+ def _check_input(frame, config: Mapping | str | Path):
173
+ """Load *config* and return ``(csv, snapshot)`` for the archived report.
174
+
175
+ ``config`` is a native Datavzrd configuration mapping or YAML filename;
176
+ relative YAML filenames are resolved against the current working directory,
177
+ like any Python file read. Every view must use the managed dataset ``data``,
178
+ and the snapshot holds the CSV and configuration, not their original paths.
179
+ A single view without ``default-view`` opens that view directly instead of
180
+ Datavzrd's landing page; multiple views keep the landing page unless
181
+ ``default-view`` selects one.
182
+ """
183
+ try:
184
+ config = load_spec(config)
185
+ except Exception as error:
186
+ raise ValueError("Invalid Datavzrd configuration") from error
187
+ if not isinstance(config, Mapping):
188
+ raise TypeError("Datavzrd config must be a mapping or a YAML filename")
189
+ snapshot = {"views": {"results": {"dataset": "data"}}} | jsonify(
190
+ config, context="Datavzrd config"
191
+ )
192
+ views = snapshot["views"]
193
+ if isinstance(views, dict) and len(views) == 1 and "default-view" not in snapshot:
194
+ snapshot["default-view"] = next(iter(views))
195
+ return dataframe_csv(frame), snapshot
196
+
197
+
198
+ @register
199
+ class datavzrd(Renderer):
200
+ """Registered renderer for ``transcript.datavzrd`` snapshots."""
201
+
202
+ name = "datavzrd"
203
+ version = (1,)
204
+
205
+ def __init__(self, frame, config: Mapping | str | Path | None = None):
206
+ if config is None:
207
+ config = {}
208
+ csv, config = _check_input(frame, config)
209
+ if not isinstance(csv, str):
210
+ raise ValueError("Datavzrd output data requires CSV string content")
211
+ config_ = jsonify(config, context="Datavzrd config")
212
+ _validate_config(config_)
213
+ self.obj = {"csv": csv, "config": config_}
214
+
215
+ @staticmethod
216
+ def infer_config(frame) -> dict[str, Any]:
217
+ """Suggest a configuration from a DataFrame's columns.
218
+
219
+ This is opt-in: ``datavzrd(frame)`` omits configuration and keeps
220
+ Datavzrd's own defaults. Pass the result explicitly, for example
221
+ ``datavzrd(frame, datavzrd.infer_config(frame))``, to start from:
222
+
223
+ - numeric columns -> a bar plot,
224
+ - short categorical text (or boolean) columns -> pills,
225
+ - text columns whose longest value exceeds ``_TEXT_LIMIT`` -> ellipsis.
226
+
227
+ Only the managed single view ``results`` is produced; a column that
228
+ cannot be classified (a non-DataFrame or custom frame, dates, numbers
229
+ stored as objects) is left to Datavzrd, and the plain view is returned
230
+ when nothing can be inferred.
231
+ """
232
+ columns = {}
233
+ for label, dtype in _columns(frame):
234
+ spec = _column_spec(frame, label, dtype)
235
+ if spec is not None:
236
+ columns[str(label)] = spec
237
+ if not columns:
238
+ return {"views": {"results": {"dataset": "data"}}}
239
+ return {
240
+ "views": {
241
+ "results": {
242
+ "dataset": "data",
243
+ "render-table": {"columns": columns},
244
+ }
245
+ }
246
+ }
247
+
248
+ def serialize(self):
249
+ """Serialize the CSV and configuration into the archived fence."""
250
+ body = json.dumps(self.obj, sort_keys=True, indent=2, allow_nan=False)
251
+ return body
252
+
253
+ @classmethod
254
+ def to_html(cls, slot):
255
+ """Validate stored data, then return its inner HTML and report files."""
256
+ parsed = cls._validate(slot.value)
257
+ return cls._htmlout("", cls._build(parsed))
258
+
259
+ @classmethod
260
+ def _validate(cls, data: str):
261
+ try:
262
+ parsed = json.loads(data)
263
+ except json.JSONDecodeError as error:
264
+ raise ValueError("Datavzrd output data must be a JSON mapping") from error
265
+ if not isinstance(parsed, dict):
266
+ raise ValueError("Datavzrd output data must be a mapping")
267
+ if not isinstance(parsed.get("csv"), str):
268
+ raise ValueError("Datavzrd output data requires CSV string content")
269
+ if not isinstance(parsed.get("config"), dict):
270
+ raise ValueError("Datavzrd output config must be a mapping")
271
+ _validate_config(parsed["config"])
272
+ return parsed
273
+
274
+ @classmethod
275
+ def _build(cls, parsed: dict):
276
+ """Return all report files; no temporary paths survive in the result."""
277
+ executable = shutil.which("datavzrd")
278
+ if executable is None:
279
+ raise RuntimeError(
280
+ "Datavzrd HTML export requires the datavzrd executable on PATH; "
281
+ "install it with: conda install -c conda-forge datavzrd"
282
+ )
283
+ config = parsed["config"]
284
+ dataset = config.setdefault("datasets", {}).setdefault("data", {})
285
+ dataset["path"] = "data.csv"
286
+ with tempfile.TemporaryDirectory(prefix="transcript-datavzrd-") as directory:
287
+ root = Path(directory)
288
+ (root / "data.csv").write_text(parsed["csv"], encoding="utf-8", newline="")
289
+ (root / "config.yaml").write_text(
290
+ json.dumps(config, ensure_ascii=False, allow_nan=False),
291
+ encoding="utf-8",
292
+ )
293
+ result = subprocess.run(
294
+ [executable, "config.yaml", "--output", "report"],
295
+ cwd=root,
296
+ capture_output=True,
297
+ text=True,
298
+ timeout=300,
299
+ check=False,
300
+ )
301
+ if result.returncode:
302
+ message = result.stderr.strip() or result.stdout.strip()
303
+ raise RuntimeError(f"Datavzrd failed: {message}")
304
+ report = root / "report"
305
+ files = {}
306
+ for path in sorted(report.rglob("*")):
307
+ if path.is_symlink() or not path.resolve().is_relative_to(report):
308
+ raise ValueError(
309
+ "Datavzrd report contains a file outside its directory"
310
+ )
311
+ if path.is_file():
312
+ name = path.relative_to(report).as_posix()
313
+ mime = mimetypes.guess_type(name)[0] or "application/octet-stream"
314
+ files[name] = (mime, path.read_bytes())
315
+ if "index.html" not in files:
316
+ raise RuntimeError("Datavzrd did not produce an index.html entry point")
317
+ return files
318
+
319
+ runtime = (
320
+ Path(__file__).with_name("datavzrd_runtime.js").read_text(encoding="utf-8")
321
+ )
@@ -0,0 +1,362 @@
1
+ /* Serve Datavzrd reports entirely from the files embedded in this document. */
2
+ (async () => {
3
+ "use strict";
4
+ const registry = JSON.parse(document.getElementById("transcript-reports").textContent);
5
+ const origin = "https://transcript.invalid/";
6
+ const decoder = new TextDecoder();
7
+
8
+ function base64Bytes(content) {
9
+ return Uint8Array.from(atob(content), c => c.charCodeAt(0));
10
+ }
11
+
12
+ async function gunzip(bytes) {
13
+ const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
14
+ return new Uint8Array(await new Response(stream).arrayBuffer());
15
+ }
16
+
17
+ // Files shared by several reports are decompressed once.
18
+ const cache = new Map();
19
+ function materialize(hash) {
20
+ if (!cache.has(hash)) {
21
+ cache.set(hash, (async () => {
22
+ const file = registry.pool[hash];
23
+ const raw = base64Bytes(file.content);
24
+ return {mime: file.mime, bytes: file.gzip ? await gunzip(raw) : raw};
25
+ })());
26
+ }
27
+ return cache.get(hash);
28
+ }
29
+
30
+ async function filesFor(id) {
31
+ const entries = Object.entries(registry.reports[id]);
32
+ const pairs = await Promise.all(
33
+ entries.map(async ([name, hash]) => [name, await materialize(hash)]),
34
+ );
35
+ return Object.fromEntries(pairs);
36
+ }
37
+
38
+ function resolve(path, base = origin) {
39
+ const url = new URL(path, base);
40
+ return url.origin === new URL(origin).origin ? url : null;
41
+ }
42
+
43
+ function key(url) {
44
+ return decodeURIComponent(url.pathname.slice(1));
45
+ }
46
+
47
+ function decode(file) {
48
+ return decoder.decode(file.bytes);
49
+ }
50
+
51
+ function dataURL(content, type) {
52
+ // A sandbox with an opaque origin cannot load blob URLs created by its
53
+ // file:// parent. Data URLs work without granting the frame parent access.
54
+ const bytes = typeof content === "string" ? new TextEncoder().encode(content) : content;
55
+ let binary = "";
56
+ for (let offset = 0; offset < bytes.length; offset += 32768) {
57
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
58
+ }
59
+ return `data:${type};base64,${btoa(binary)}`;
60
+ }
61
+
62
+ function adaptJavaScript(source) {
63
+ // Location is not configurable in browsers. Give Datavzrd its own location
64
+ // so links and query parameters continue to work inside an offline srcdoc.
65
+ // Skip literals and comments: names, descriptions and data are not code.
66
+ // Native template strings contain markup; their handlers are adapted when
67
+ // attached below, rather than rewriting the template's visible text.
68
+ const tokens = /("(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|`(?:\\[\s\S]|[^`\\])*`|\/\/[^\r\n]*|\/\*[\s\S]*?\*\/)|\bwindow\.location\b/g;
69
+ return source.replace(tokens, (token, literal, offset) => {
70
+ if (literal) return literal;
71
+ const assignment = /^\s*=(?!=)/.test(source.slice(offset + token.length));
72
+ return `window.__transcriptLocation${assignment ? ".href" : ""}`;
73
+ });
74
+ }
75
+
76
+ // This function is injected before any native report script, including in
77
+ // search dialogs. It communicates with the shell using postMessage so the
78
+ // shell controls navigation, resource loading and nested frames.
79
+ function bootstrap(url, id, parentId, depth, channel) {
80
+ let shell = window;
81
+ for (let index = 0; index < depth; index++) shell = shell.parent;
82
+ const children = new Map();
83
+ let sequence = 0;
84
+ const send = message => shell.postMessage({channel, id, ...message}, "*");
85
+ const navigate = (path, target = "_self") => send({action: "navigate", path, target});
86
+ const address = new URL(url);
87
+ const location = {
88
+ get href() { return address.href; },
89
+ set href(path) { navigate(path); },
90
+ get search() { return address.search; },
91
+ get hash() { return address.hash; },
92
+ set hash(hash) { address.hash = hash; },
93
+ get pathname() { return address.pathname; },
94
+ get protocol() { return address.protocol; },
95
+ get host() { return address.host; },
96
+ get hostname() { return address.hostname; },
97
+ get port() { return address.port; },
98
+ get origin() { return address.origin; },
99
+ assign: navigate,
100
+ replace: navigate,
101
+ reload() { navigate(address.href); },
102
+ toString() { return address.href; },
103
+ };
104
+ window.__transcriptLocation = location;
105
+ // Datavzrd builds its controls with inline event handlers, which a
106
+ // hash-based CSP blocks. Re-attach them as listeners instead, keeping the
107
+ // element as `this` and preserving `return false` default prevention.
108
+ const inlineEvents = [
109
+ "onclick", "onchange", "oninput", "onkeyup", "onkeydown", "onsubmit",
110
+ "ondblclick",
111
+ ];
112
+ const inlineSelector = inlineEvents.map(name => `[${name}]`).join(",");
113
+ function convertInlineHandlers(element) {
114
+ for (const name of inlineEvents) {
115
+ if (!element.hasAttribute(name)) continue;
116
+ let code = element.getAttribute(name);
117
+ element.removeAttribute(name);
118
+ // The view selector is generated inside a native JavaScript template.
119
+ code = code.replace(/^\s*location\s*=\s*this\.value\s*;?\s*$/,
120
+ "window.__transcriptLocation.href = this.value;");
121
+ code = code.replace(/\bwindow\.location(?=\s*=)/,
122
+ "window.__transcriptLocation.href");
123
+ const handler = new Function("event", code);
124
+ element.addEventListener(name.slice(2), function (event) {
125
+ if (handler.call(this, event) === false) event.preventDefault();
126
+ });
127
+ }
128
+ }
129
+ function convertInlineTree(root) {
130
+ if (root.nodeType === 1) convertInlineHandlers(root);
131
+ if (root.querySelectorAll) {
132
+ for (const element of root.querySelectorAll(inlineSelector)) {
133
+ convertInlineHandlers(element);
134
+ }
135
+ }
136
+ }
137
+ new MutationObserver(records => {
138
+ for (const record of records) {
139
+ for (const node of record.addedNodes) {
140
+ if (node.nodeType === 1) convertInlineTree(node);
141
+ }
142
+ }
143
+ }).observe(document.documentElement, {subtree: true, childList: true});
144
+ convertInlineTree(document);
145
+ // Datavzrd is a full-viewport app (`#page-container { min-height: 100vh }`),
146
+ // which leaves a small table surrounded by empty space when embedded.
147
+ // Relax it and report the real content height so the shell can size the frame.
148
+ const sizing = document.createElement("style");
149
+ // `flow-root` keeps the header spacer margin inside the container so its
150
+ // measured height matches the visible content.
151
+ sizing.textContent =
152
+ "#page-container { min-height: 0 !important; display: flow-root; }";
153
+ document.head.append(sizing);
154
+ function reportHeight(container) {
155
+ send({action: "resize", height: Math.ceil(container.getBoundingClientRect().height)});
156
+ }
157
+ const heightWatch = new MutationObserver(() => {
158
+ const container = document.getElementById("page-container");
159
+ if (!container) return;
160
+ heightWatch.disconnect();
161
+ new ResizeObserver(() => reportHeight(container)).observe(container);
162
+ reportHeight(container);
163
+ });
164
+ heightWatch.observe(document.documentElement, {subtree: true, childList: true});
165
+ function local(path) {
166
+ if (!path || path.startsWith("#")) return false;
167
+ try { return new URL(path, address).origin === address.origin; }
168
+ catch { return false; }
169
+ }
170
+ function loadFrame(frame, path) {
171
+ let childId = frame.dataset.transcriptFrame;
172
+ if (!childId) {
173
+ childId = `${id}-${++sequence}`;
174
+ frame.dataset.transcriptFrame = childId;
175
+ children.set(childId, frame);
176
+ }
177
+ send({action: "frame", frameId: childId, path});
178
+ }
179
+ const setAttribute = Element.prototype.setAttribute;
180
+ Element.prototype.setAttribute = function (name, value) {
181
+ if (this instanceof HTMLIFrameElement && name.toLowerCase() === "src" && local(String(value))) {
182
+ loadFrame(this, String(value));
183
+ return;
184
+ }
185
+ return setAttribute.call(this, name, value);
186
+ };
187
+ const frameSrc = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, "src");
188
+ Object.defineProperty(HTMLIFrameElement.prototype, "src", {
189
+ ...frameSrc,
190
+ set(value) {
191
+ if (local(String(value))) loadFrame(this, String(value));
192
+ else frameSrc.set.call(this, value);
193
+ },
194
+ });
195
+ document.addEventListener("click", event => {
196
+ const anchor = event.target.closest && event.target.closest("a[href]");
197
+ if (!anchor || anchor.hasAttribute("download")) return;
198
+ const path = anchor.getAttribute("href");
199
+ // Fragment links resolve against the parent document in a srcdoc frame,
200
+ // so the default action would reload the report inside itself. Datavzrd
201
+ // still handles them through its own listeners.
202
+ if (!path || path.startsWith("#")) {
203
+ event.preventDefault();
204
+ return;
205
+ }
206
+ if (!local(path)) return;
207
+ event.preventDefault();
208
+ navigate(path, anchor.getAttribute("target") || "_self");
209
+ }, true);
210
+ window.addEventListener("message", event => {
211
+ if (event.source !== shell || event.data?.channel !== channel) return;
212
+ const message = event.data;
213
+ if (message.action === "html") {
214
+ const frame = children.get(message.frameId);
215
+ if (frame) frame.srcdoc = message.html;
216
+ } else if (message.action === "download") {
217
+ const anchor = document.createElement("a");
218
+ anchor.href = message.url;
219
+ anchor.download = message.filename;
220
+ anchor.click();
221
+ } else if (message.action === "error") {
222
+ const error = document.createElement("p");
223
+ error.setAttribute("role", "alert");
224
+ error.textContent = message.message;
225
+ document.body.prepend(error);
226
+ }
227
+ });
228
+ }
229
+
230
+ function createReport(files, container) {
231
+ const channel = `transcript-datavzrd-${Math.random().toString(36).slice(2)}`;
232
+ const urls = new Map();
233
+ const frames = new Map();
234
+ const report = document.createElement("iframe");
235
+ report.className = "datavzrd-page";
236
+ report.title = "Datavzrd report";
237
+ report.setAttribute("sandbox", "allow-scripts allow-downloads allow-popups allow-popups-to-escape-sandbox");
238
+ report.style.cssText = "width:100%;height:480px;max-height:90vh;border:0;display:block";
239
+ container.append(report);
240
+
241
+ function resource(path, base) {
242
+ if (/^(?:data|blob):/i.test(path)) return path;
243
+ const url = resolve(path, base);
244
+ if (!url) throw new Error(`The offline report requires an external resource: ${path}`);
245
+ if (!files[key(url)]) throw new Error(`The offline report does not contain ${key(url)}.`);
246
+ const name = key(url);
247
+ if (!urls.has(name)) {
248
+ const file = files[name];
249
+ let content;
250
+ if (/javascript/.test(file.mime) || name.endsWith(".js")) {
251
+ content = adaptJavaScript(decode(file));
252
+ } else if (file.mime === "text/css") {
253
+ content = rewriteCSS(decode(file), url.href);
254
+ } else {
255
+ content = file.bytes;
256
+ }
257
+ urls.set(name, dataURL(content, file.mime));
258
+ }
259
+ return urls.get(name) + url.hash;
260
+ }
261
+
262
+ function rewriteCSS(css, base) {
263
+ return css.replace(/url\(\s*(['"]?)([^)'"\s]+)\1\s*\)/g,
264
+ (match, quote, path) => path.startsWith("#") ? match : `url("${resource(path, base)}")`);
265
+ }
266
+
267
+ function page(address, id, parentId, depth) {
268
+ const name = key(address);
269
+ if (!files[name]) throw new Error(`The offline report does not contain ${name}.`);
270
+ const html = new DOMParser().parseFromString(decode(files[name]), "text/html");
271
+ html.querySelectorAll("base").forEach(base => base.remove());
272
+ html.querySelectorAll("link[href],img[src],source[src],video[src],audio[src]").forEach(element => {
273
+ const attribute = element.hasAttribute("src") ? "src" : "href";
274
+ element.setAttribute(attribute, resource(element.getAttribute(attribute), address.href));
275
+ element.removeAttribute("integrity");
276
+ element.removeAttribute("crossorigin");
277
+ });
278
+ html.querySelectorAll("script").forEach(element => {
279
+ const type = (element.getAttribute("type") || "").toLowerCase();
280
+ // Data and template scripts are not code and must keep their text.
281
+ const isJavaScript = !type || /(?:java|ecma)script|module/.test(type);
282
+ if (element.hasAttribute("src")) {
283
+ element.setAttribute("src", resource(element.getAttribute("src"), address.href));
284
+ } else if (isJavaScript && element.textContent.trim()) {
285
+ const source = adaptJavaScript(element.textContent);
286
+ element.textContent = "";
287
+ element.setAttribute("src", dataURL(source, "text/javascript"));
288
+ }
289
+ element.removeAttribute("integrity");
290
+ element.removeAttribute("crossorigin");
291
+ });
292
+ html.querySelectorAll("style").forEach(style => { style.textContent = rewriteCSS(style.textContent, address.href); });
293
+ html.querySelectorAll("[style]").forEach(element => {
294
+ element.setAttribute("style", rewriteCSS(element.getAttribute("style"), address.href));
295
+ });
296
+ const script = html.createElement("script");
297
+ script.src = dataURL(
298
+ `(${bootstrap.toString()})(${[address.href, id, parentId, depth, channel].map(value => JSON.stringify(value)).join(",")});`,
299
+ "text/javascript",
300
+ );
301
+ html.head.prepend(script);
302
+ return "<!doctype html>\n" + html.documentElement.outerHTML;
303
+ }
304
+
305
+ function show(id, address) {
306
+ const frame = frames.get(id);
307
+ // Native downloads are files too, not pages to interpret as HTML.
308
+ const file = files[key(address)];
309
+ if (!file) throw new Error(`The offline report does not contain ${key(address)}.`);
310
+ if (file.mime !== "text/html") {
311
+ frame.window?.postMessage({channel, action: "download", url: resource(address.href, origin), filename: key(address).split("/").pop()}, "*");
312
+ return;
313
+ }
314
+ frame.address = address;
315
+ const html = page(address, id, frame.parentId, frame.depth);
316
+ if (id === "root") report.srcdoc = html;
317
+ else frame.owner.postMessage({channel, action: "html", frameId: id, html}, "*");
318
+ }
319
+
320
+ window.addEventListener("message", event => {
321
+ const message = event.data;
322
+ if (message?.channel !== channel || !frames.has(message.id)) return;
323
+ const current = frames.get(message.id);
324
+ if (message.id === "root" && event.source !== report.contentWindow) return;
325
+ current.window = event.source;
326
+ if (message.action === "resize") {
327
+ // Only the top report drives the embedded frame height.
328
+ if (message.id === "root") {
329
+ report.style.height = `${Math.max(120, message.height)}px`;
330
+ }
331
+ return;
332
+ }
333
+ try {
334
+ const address = resolve(message.path, current.address.href);
335
+ if (!address) return;
336
+ if (message.action === "frame") {
337
+ frames.set(message.frameId, {owner: event.source, parentId: message.id, depth: current.depth + 1});
338
+ show(message.frameId, address);
339
+ } else if (message.action === "navigate") {
340
+ const target = message.target === "_parent" ? current.parentId || "root" : message.target === "_top" ? "root" : message.id;
341
+ show(target, address);
342
+ }
343
+ } catch (error) {
344
+ event.source.postMessage({channel, action: "error", message: error.message}, "*");
345
+ }
346
+ });
347
+ frames.set("root", {parentId: null, depth: 1});
348
+ show("root", new URL("index.html", origin));
349
+ }
350
+
351
+ const selector = '[data-tmd-report][data-tmd-renderer="datavzrd"]';
352
+ for (const container of document.querySelectorAll(selector)) {
353
+ try {
354
+ createReport(await filesFor(container.dataset.tmdReport), container);
355
+ } catch (error) {
356
+ const message = document.createElement("p");
357
+ message.setAttribute("role", "alert");
358
+ message.textContent = `transcript: could not load the Datavzrd report: ${error}`;
359
+ container.append(message);
360
+ }
361
+ }
362
+ })();