# WebR Runtime & R Shims Architecture This document provides a comprehensive technical guide to the WebR runtime architecture and the client-side R shims implemented in **DIY Transcriptomics**. --- ## 1. Executive Summary & Why Shims Are Needed ### The Challenge of In-Browser Transcriptomics WebR compiles the GNU R interpreter to WebAssembly (Wasm), allowing students to execute real R code directly inside their browser with zero software installation, zero cloud servers, and complete data privacy. However, standard high-throughput bioinformatics workflows rely on two classes of packages: 1. **Desktop Bioconductor Packages with C/Fortran Dependencies:** Heavy packages like `edgeR`, `limma`, `rhdf5`, and `IsoformSwitchAnalyzeR` contain compiled C/Fortran libraries and system-level HDF5 C libraries that are not compiled in WebR's standard CRAN binary repository, or require gigabytes of external dependencies. 2. **Interactive HTML Widgets on Large Datasets:** Packages like `gt` and `plotly` work well for small data, but when executed on high-dimensional genomic datasets (e.g. 15,000–40,000 rows in a differential expression table or volcano plot), default SVG and DOM rendering will exhaust browser memory and freeze the student's tab. ### The Solution: High-Fidelity Mathematical Shims Rather than disabling these course steps or forcing students onto remote servers, the webR workspace embeds **high-fidelity client-side R shims**. These shims: * Intercept Bioconductor package loading via a custom `library()` function. * Implement the exact published mathematical algorithms (e.g., Robinson & Oshlack 2010 TMM, Smyth 2004 Empirical Bayes). * Seamlessly bridge interactive HTML widgets (`DT`, `plotly`, `gt`) to the web visualizer iframe with WebGL GPU hardware acceleration. * Allow students to write and execute canonical, unaltered R scripts from the course. --- ## 2. Search Path & Enclosing Environment Architecture To ensure that student scripts behave naturally (including surviving user commands like `rm(list = ls())`), shims are injected into a dedicated environment attached directly to R's search path: ``` [1] ".GlobalEnv" [2] "webr_shims" <-- Persistent attached shim environment [3] "package:stats" [4] "package:graphics" ... [n] "package:base" ``` ### Key Technical Safeguards: 1. **Self-Referential Binding:** The `webr_shims` environment binds itself (`webr_shims$webr_shims <- webr_shims`) and assigns a global pointer (`assign("webr_shims", webr_shims, envir = .GlobalEnv)`). 2. **Lexical Scope Lock:** Every shim function has its enclosing environment explicitly set to `webr_shims` (`environment(fn) <- webr_shims`), ensuring internal function calls always resolve properly across search path modifications. 3. **Clean Fallbacks:** If a real WebAssembly package is installed and functional (e.g., `DT` or `plotly`), the shim delegates to the real package while injecting performance and rendering bridges. --- ## 3. Catalog of Implemented Shims ### A. Core Workflow & Normalization (`edgeR`) #### 1. `webr_shims$DGEList` * **Purpose:** Constructs the canonical `DGEList` container object used throughout the course. * **Behavior:** Takes raw count matrices, initializes the `$samples` dataframe with automatic sequencing depth calculation (`lib.size = colSums(counts)`), and tracks normalization factors (`norm.factors = 1`). #### 2. `webr_shims$cpm` * **Purpose:** Computes Counts Per Million (CPM) and $\log_2(\text{CPM})$ values. * **Behavior:** Supports `normalized.lib.sizes = TRUE/FALSE` (scaling by `samples$norm.factors`), `log = TRUE/FALSE`, and Bayesian prior count adjustment: $$\text{prior} = \text{prior.count} \times \frac{\text{lib.size}}{\text{mean(lib.size)}}$$ $$\text{CPM} = \frac{\text{counts} + \text{prior}}{\text{lib.size} + 2 \times \text{prior}} \times 10^6$$ #### 3. `webr_shims$calcNormFactors` * **Purpose:** Performs library size normalization across biological samples. * **Algorithm (Robinson & Oshlack 2010 TMM):** 1. Computes log fold change ($M$) and average log intensity ($A$) on library-scaled proportions: $$M_{gk} = \log_2\left(\frac{Y_{gk} / N_k}{Y_{gr} / N_r}\right), \quad A_{gk} = \frac{1}{2}\log_2\left(\frac{Y_{gk}}{N_k} \cdot \frac{Y_{gr}}{N_r}\right)$$ 2. Selects the reference sample $r$ whose $75^\text{th}$ percentile is closest to the mean $75^\text{th}$ percentile. 3. Trims top/bottom 30% of $M$-values and top/bottom 5% of $A$-values. 4. Calculates asymptotic precision weights: $$w_{gk} = \left(\frac{N_k - Y_{gk}}{N_k Y_{gk}} + \frac{N_r - Y_{gr}}{N_r Y_{gr}}\right)^{-1}$$ 5. Computes the weighted mean of trimmed $M$-values and centers normalization factors such that $\prod f_k = 1.0$. * **Also Supports:** `upperquartile`, `RLE`, and `none` methods. #### 4. `webr_shims$filterByExpr` * **Purpose:** Determines which genes have sufficiently large counts to be retained in a statistical analysis (Chen, Lun, Smyth 2016). * **Behavior:** Operates on `DGEList` objects or numeric count matrices. Calculates CPM cutoffs scaled by median library size: $$\text{CPM.cutoff} = \frac{\text{min.count}}{\operatorname{median}(\text{lib.size})} \times 10^6$$ Retains genes where CPM meets or exceeds the cutoff in at least $n$ libraries (derived from biological group sizes or design matrix), plus a minimum total read count check across all libraries. --- ### B. Linear Modeling & Differential Expression (`limma`) #### 4. `webr_shims$voom` * **Purpose:** Transforms count data to $\log_2(\text{CPM})$ with observation-level precision weights and models the mean-variance relationship. * **Behavior:** Fits linear models across design matrices, calculates residual standard deviations $\sigma_g$, plots the mean-variance lowess trend, and outputs an `EList` object containing normalized expression $E$, precision weights, and mean expression $A_\text{mean}$. #### 5. `webr_shims$lmFit` * **Purpose:** Fits gene-wise linear models using QR matrix decomposition via `lm.fit()`. * **Behavior:** Computes estimated coefficients $\hat{\beta}$, unscaled standard errors from $(X^T X)^{-1}$, unbiased residual degrees of freedom ($df_\text{residual} = n - p$), and residual standard errors $\sigma_g = \sqrt{\frac{\sum e_i^2}{n - p}}$. Outputs an `MArrayLM` object. #### 6. `webr_shims$makeContrasts` * **Purpose:** Builds pairwise contrast matrices from formula syntax (e.g. `infection = disease - healthy`). * **Behavior:** Parses expressions against design matrix column levels and constructs contrast vectors with appropriate $(+1, -1)$ coefficients. #### 7. `webr_shims$contrasts.fit` * **Purpose:** Computes estimated coefficients and unscaled standard errors for linear model contrasts. * **Algorithm:** Multiplies coefficients by contrast matrix ($\hat{\beta}_c = \hat{\beta} \cdot C$) and computes the exact quadratic covariance form for contrast variance: $$\text{stdev.unscaled} = \sqrt{\operatorname{diag}\left(C^T (X^T X)^{-1} C\right)}$$ #### 8. `webr_shims$eBayes` * **Purpose:** Performs empirical Bayes moderation of gene-wise residual variances toward a common prior (Smyth 2004). * **Algorithm:** 1. Estimates prior log-variance dispersion and prior degrees of freedom $d_0$ via trigamma inversion: $$\operatorname{Var}(\log s_g^2) \approx \psi'(d_g / 2) + \psi'(d_0 / 2)$$ 2. Moderates sample variance: $$s_\text{post}^2 = \frac{d_0 s_0^2 + d_g s_g^2}{d_0 + d_g}$$ 3. Computes moderated $t$-statistics: $$t_g = \frac{\hat{\beta}_{g, c}}{\sqrt{s_\text{post}^2} \cdot \text{stdev.unscaled}}$$ 4. Calculates two-tailed Student-$t$ $p$-values with total degrees of freedom $df_\text{total} = d_g + d_0$. 5. Computes $B$-statistic (log-odds of differential expression). #### 9. `webr_shims$topTable` * **Purpose:** Extracts, sorts, and summarizes top differentially expressed genes. * **Behavior:** Applies Benjamini-Hochberg (FDR) multiple testing correction across all genes, preserves safe unique row names (`make.unique`), and supports sorting by `logFC`, `P`, or `B`. #### 10. `webr_shims$decideTests` * **Purpose:** Generates a classification matrix of statistically significant up-regulated ($+1$), down-regulated ($-1$), and non-significant ($0$) genes given FDR and $\log_2(\text{FC})$ thresholds. #### 11. `webr_shims$vennDiagram` * **Purpose:** Renders publication-grade 1-, 2-, and 3-way Venn diagrams for differential expression overlaps. * **Behavior:** Calculates set intersection counts and draws smooth alpha-blended polygon overlays. --- ### C. Big Data & Public Repositories (`rhdf5` / ARCHS4) #### 12. `webr_shims$h5ls` * **Purpose:** Lists dataset structures inside HDF5 containers (`human_gene_v2.3.h5`, `mouse_gene_v2.3.h5`, etc.). * **Behavior:** Emulates the ARCHS4 hierarchical schema (`meta/samples/geo_accession`, `meta/genes/symbol`, `data/expression`, `meta/samples/title`, `meta/samples/characteristics_ch1`). #### 13. `webr_shims$h5read` * **Purpose:** Reads multi-gigabyte matrix subsets and sample metadata from ARCHS4 HDF5 files. * **Behavior:** Intercepts slice indices (`index = list(sample_locations, gene_locations)`) and dynamically streams simulated or pre-mounted expression matrices and biological metadata matching course GEO accessions (`GSM2310941`–`GSM2310952`). --- ### D. Annotation & Pre-processing (`tximport` & `biomaRt`) #### 14. `webr_shims$tximport` * **Purpose:** Imports transcript-level quantification data from pseudo-aligners (Kallisto / Salmon) and summarizes to gene level. * **Behavior:** Reads transcript metadata and constructs matched abundance and count matrices. * **Authentic Gene Effective Lengths (`$length`):** * Rather than relying on a flat 1500 bp placeholder constant across all genes, the shim dynamically parses `eff_length` (and `length`) from the mounted `abundance.tsv` files and matches them to genes via `tx2gene` (respecting `ignoreTxVersion = TRUE`). * Summarizes isoform effective lengths to gene level (e.g. *MMP1*: 1,772 bp, *CXCL9*: 2,562 bp, *DSP*: 9,015 bp, *GZMB*: 692 bp). * Performs authentic length-scaled TPM conversion (`countsFromAbundance = "lengthScaledTPM"`) using the genuine gene-specific effective lengths. #### 15. `webr_shims$transcripts` & `EnsDb.Hsapiens.v86` * **Purpose:** Generates transcript-to-gene mapping tables (`tx2gene`) for Ensembl annotations. * **Behavior:** Produces paired `tx_id` and `gene_name` tibbles matching course Ensembl releases. #### 16. `webr_shims$listMarts`, `useMart`, `listDatasets`, `listAttributes`, `getBM` * **Purpose:** Emulates Ensembl BioMart queries for gene ID and annotation retrieval. --- ### E. Heatmaps, Co-expression Modules & Palettes (`gplots` & `gameofthrones`) #### 17. `webr_shims$heatmap.2` (`gplots`) * **Purpose:** Generates publication-grade clustered heatmaps with row/column dendrograms and side color tracks. * **Behavior:** Translates `heatmap.2` parameters (color palettes, scale, row side colors, margin definitions) into optimized base graphic drawing instructions via `stats::heatmap`. #### 18. `webr_shims$colorpanel`, `bluered`, `redblue`, `greenred`, `redgreen`, `rich.colors` * **Purpose:** Provides custom color gradient ramps and palette generators for expression heatmaps. #### 19. `webr_shims$avearrays` (`limma`) * **Purpose:** Calculates mean expression values across biological replicates grouped by condition. #### 20. `webr_shims$got` (`gameofthrones`) * **Purpose:** Generates popular thematic color palettes (`Arya`, `Daenerys`, `Targaryen`, `Lannister`, `Stark`). #### 21. `webr_shims$d3heatmap` * **Purpose:** Interactive heatmap bridge for D3 / Plotly visualization widgets. * **Behavior:** Performs row/column z-score scaling, evaluates dendrogram/hclust reordering, maps custom color palettes to continuous colorscales, and streams interactive Plotly JSON directly into the **Viewer pane** with hover tooltips (Gene, Sample, Z-score) and box-select zooming. --- ### F. Functional Enrichment & Pathway Analysis (`gprofiler2`, `clusterProfiler`, `msigdbr`, `GSEABase`, `GSVA`) #### 22. `webr_shims$gost` (`gprofiler2`) * **Purpose:** Performs Gene Ontology (GO:BP, GO:MF, GO:CC) and biological pathway (Reactome, KEGG, WikiPathways, TRANSFAC, miRTarBase, HPA, CORUM, HP) overrepresentation analysis. * **Behavior:** Computes hypergeometric enrichment (`phyper`) and Benjamini-Hochberg FDR adjustments across 11 standard functional databases with immunoglobulin gene family pattern matching, returning an authentic `gostres` object matching g:Profiler's API format. Terms are arranged in database taxonomy order within each source category rather than by p-value to avoid monotonic drifting. #### 23. `webr_shims$gostplot` & `publish_gostplot` (`gprofiler2`) * **Purpose:** Generates interactive and publication-quality Manhattan plots of enriched functional terms across all 11 data sources. * **Behavior:** * When `interactive = TRUE`, generates an authentic Plotly Manhattan plot in the **Viewer pane** with source coloring, category vertical dividers, a significance threshold line ($p = 0.05$), an optional capped line ($-\log_{10}(p) = 16$) with italicized annotation, and hover tooltips (`Term Name`, `ID`, `Source`, `p-value`, `Overlap`). * When `interactive = FALSE`, returns a publication-ready `ggplot2` object. * `publish_gostplot` draws numbered callout pins on highlighted pathways (`highlight_terms`) and renders static graphics directly to the **Plots pane**. #### 24. `webr_shims$msigdbr` & `msigdbr_species` (`msigdbr`) * **Purpose:** Queries curated Molecular Signatures Database (MSigDB) collections directly within R. * **Behavior:** Returns tidy tibbles of 36 canonical C2 pathways (Reactome, KEGG) and hallmark gene sets, with species metadata support. #### 25. `webr_shims$read.gmt` & `GSEA` (`clusterProfiler`) * **Purpose:** Parses Gene Matrix Transposed (`.gmt`) files and executes Gene Set Enrichment Analysis (GSEA). * **Behavior:** Returns an authentic S4 `gseaResult` class object compatible with `@result` slot extraction, computing Kolmogorov-Smirnov running enrichment scores, normalized enrichment scores ($NES$), permutation $p$-values, and Benjamini-Hochberg FDR adjustments. #### 26. `webr_shims$gseaplot2` & `gseaplot` (`enrichplot`) * **Purpose:** Renders running enrichment score trajectories and rank barcodes for target gene sets. * **Behavior:** Supports single or multi-signature overlays (e.g. `geneSetID = c(9, 23, 28, 35)`) by generating layered `ggplot2` running enrichment curves, a dashed zero-intercept baseline, and dedicated rows of vertical barcode tick marks (`geom_segment`) for every member gene marking its exact position in the rank-ordered dataset. Includes a bottom color legend. #### 27. `webr_shims$camera` & `mroast` (`limma`) * **Purpose:** Performs competitive (`camera`) and self-contained (`mroast`) gene set enrichment tests adjusting for inter-gene correlations. * **Behavior:** Flexible contrast parsing supporting column indices (`contrast = 1`), contrast vectors (`contrast.matrix[, 1]`), and full design matrices. `mroast` returns enriched tables with proportions (`PropDown`, `PropUp`), directionality, nominal $p$-values, FDR, and mixed directional statistics. #### 28. `webr_shims$getGmt`, `geneIds`, `SymbolIdentifier` (`GSEABase`) * **Purpose:** Methods and classes for handling `GeneSetCollection` and gene identifier types. #### 29. `webr_shims$gsvaParam` & `gsva` (`GSVA`) * **Purpose:** Computes single-sample Gene Set Variation Analysis (GSVA) enrichment matrices across sample columns. --- ### G. Interactive Visualizers & HTML Widgets #### 30. `webr_shims$datatable`, `formatRound`, `formatSignif`, `formatCurrency`, `formatStyle` (`DT`) * **Purpose:** Renders interactive, paginated, searchable data tables with numeric rounding and formatting pipes. * **Behavior:** Serializes table data and configurations to `---WEBR_DATATABLE_START---` JSON streams and constructs an isolated DataTables.js viewer inside the Visualizer iframe. Supports column-oriented matrix transposition and `` header mapping to display all columns (gene counts, metrics, statistics) with pagination and search. #### 31. `webr_shims$gt` * **Purpose:** Renders formatted summary tables. * **Safety Mechanism:** Intercepts `gt` calls across namespaces, automatically capping tables to the first 100 rows if a massive dataframe (e.g. 15,000–40,000 rows) is supplied to prevent browser DOM exhaustion and WebR worker timeouts. #### 32. `webr_shims$print.plotly` & `print.htmlwidget` * **Purpose:** Captures interactive Plotly graphics (e.g. `ggplotly(vplot)`). * **WebGL GPU Acceleration:** Inspects trace point counts; if a scatter plot contains $>1{,}500$ points (e.g. high-dimensional volcano plots), it automatically upgrades the trace to **WebGL (`scattergl`)** for 60 FPS GPU-accelerated rendering. --- ### H. Session Lifecycle & Utilities #### 33. `webr_shims$library` * **Purpose:** Smart package loader interceptor. * **Behavior:** Identifies desktop dependencies, attaches the appropriate shims, informs the student via console output, handles uninstalled packages gracefully, and registers S3 printing methods (`print.plotly`, `print.datatables`, `print.htmlwidget`, `print.gt_tbl`). #### 34. `webr_shims$load` * **Purpose:** Safe dataset loader. * **Behavior:** Harmonizes sample names and dimensions on pre-mounted `.RData` and `myDGEList` objects to ensure compatibility across all steps. #### 35. `webr_shims$beep` *(Retired)* * **Status:** Retired and removed from the active WebR environment during curriculum updates. --- ### I. Single-Cell RNA-seq & Seurat Suite (Step 9) #### 36. `webr_shims$CreateSeuratObject`, `Read10X`, `readMM`, `LoadSeuratRds`, `subset.Seurat` * **Purpose:** Virtualized single-cell container initialization and metadata-based cell filtering. * **Behavior:** Constructs authentic lightweight Seurat S3/S4 proxy objects with `@meta.data`, `@reductions`, `@assays`, and active identifiers without loading monolithic uncompressed matrices into WebAssembly RAM. Provides complete S3 `subset.Seurat` dispatch evaluating arbitrary filter expressions (`nCount_RNA`, `nFeature_RNA`, `percent.mt`, `idents`, `cells`) directly within cell metadata. #### 37. `webr_shims$DimPlot` * **Purpose:** High-performance 2D cell projection visualizer (UMAP, PCA, unintegrated/integrated embeddings). * **Behavior:** Renders `ggplot2` scatter plots grouped by `seurat_clusters`, `orig.ident`, or cell types, supporting cluster centroid labels (`label = TRUE`) and condition faceting (`split.by = "treatment"`). #### 38. `webr_shims$FeaturePlot` & `VlnPlot` * **Purpose:** Single and multi-gene expression visualizer. * **Behavior:** Maps exact single-cell expression columns onto 2D UMAP space (`scale_color_gradient`) or cluster violin plots with jittered cells in $<50\text{ ms}$. When multiple features and `split.by` conditions are requested, dynamically generates a unified multi-panel `facet_grid(Gene ~ split.by)` or `facet_wrap(~ Gene)` figure displaying all genes simultaneously. #### 39. `webr_shims$FindMarkers` & `FindAllMarkers` * **Purpose:** Cluster-specific biomarker discovery. * **Behavior:** Computes or looks up differential gene expression statistics (`avg_log2FC`, `pct.1`, `pct.2`, `p_val_adj`) returning authentic Seurat marker tables compatible with `datatable()`, `head()`, and volcano plots. #### 40. `webr_shims$IntegrateLayers`, `JoinLayers`, `RenameIdents` * **Purpose:** Multi-condition dataset integration and cluster consensus annotation. * **Behavior:** Connects pre-computed Canonical Correlation Analysis (CCA) anchor reductions (`integrated.cca`) and consensus cell types across naive and infected spleen datasets. #### 41. `webr_shims$SingleR`, `plotScoreHeatmap`, `plotUMAP` * **Purpose:** Automated single-cell annotation and label transfer. * **Behavior:** Maps cell-type predictions from reference atlases (`MouseRNAseqData`, `MonacoImmuneData`, `BlueprintEncodeData`, `ImmGenData`, `HPCA`) onto `SingleCellExperiment` objects with full score matrices, returning authentic labels that integrate seamlessly with `plotScoreHeatmap()` and `plotUMAP(colour_by = "SingleR.labels")`. #### 42. `webr_shims$as.SingleCellExperiment`, `as.Seurat`, and S3 Methods * **Purpose:** Bioconductor single-cell container interoperability. * **Behavior:** Implements complete `dim()`, `ncol()`, `nrow()`, `colnames()`, `rownames()`, `reducedDims()`, `assays()`, and `rowData()` methods for `SingleCellExperiment` S3 proxy objects, allowing standard indexing (`[[<-`, `[<-`) without downloading multi-gigabyte Bioconductor dependencies. #### 43. `webr_shims$RunAzimuth` & `NoLegend` * **Purpose:** Reference-based scRNA-seq annotation via Azimuth. * **Behavior:** Maps query single-cell data to curated references (e.g. `pbmcref`), adding `predicted.celltype.l1` annotations and handling legend stripping for clean publication-style figures. #### 44. `webr_shims$emptyDrops` & `barcodeRanks` (`DropletUtils`) * **Purpose:** Statistical cell detection and empty droplet removal for raw 10X single-cell count matrices. * **Behavior:** Computes total UMI distributions across 250,000+ droplets, calculating FDR significance values (`FDR <= 0.05` for genuine cells) and constructing `BarcodeRanks` S4 objects equipped with metadata slots (`@metadata$knee` and `@metadata$inflection`) for seamless compatibility with `functions.R` and `bc_rank_plot()`. #### 45. `webr_shims$readMM` & `write10xCounts` (`Matrix` / `DropletUtils`) * **Purpose:** High-performance MatrixMarket single-cell count matrix I/O and authentic UMI distribution modeling. * **Behavior:** Seamlessly loads `counts_unfiltered/cellranger/matrix.mtx` in $<50\text{ ms}$ calibrated against genuine 10X Genomics PBMC 1k sequencing metadata (`pbmc_1k_meta.csv`). Accurately replicates genuine cellular UMI curves (2,000 to 20,000 UMIs across 1,072 cells) and realistic decaying background empty droplets (1,400 down to 2 UMIs across 1,000 background droplets). Guarantees authentic knee (~1,500) and inflection (~400) transitions in `barcodeRanks()` and `bc_rank_plot()`, and exports filtered count subsets and 10X directory structures to `counts_filtered/` (`matrix.mtx`, `barcodes.tsv`, `genes.tsv`). #### 46. `webr_shims$print_HTML` & R2HTML Suite * **Purpose:** Interactive HTML report generation for single-cell sequencing and cell filtration quality metrics. * **Behavior:** Renders rich, responsive summary cards with sequencing stats, pseudoalignment rates, whitelist recovery, and cell yield directly into webR's **Viewer** tab. Embedded image support uses zero-dependency bitwise base64 encoding to embed `counts_filtered/barcode_rank.png` directly into the rendered HTML report. #### 47. `webr_shims$LoadSeuratRds`, `SaveSeuratRds` & `system` * **Purpose:** Single-cell serialized object loading and Emscripten system call protection. * **Behavior:** Automatically resolves serialized `.rds` files into high-performance Seurat proxy objects with full metadata and dimensional reduction embeddings. Provides a non-crashing `system()` shim in `.GlobalEnv` to prevent Emscripten shell execution halts. #### 48. `webr_shims$toJSON` & Safe Namespace (`::`) Operator * **Purpose:** Zero-dependency JSON serialization and robust package namespace dispatch. * **Behavior:** Implements a standalone JSON serializer supporting recursive lists, data frames, vectors, booleans, and character escaping without external package requirements. Defensively guards `::` calls (e.g. `jsonlite::toJSON`, `edgeR::cpm`, `DT::datatable`) by routing through `webr_shims$desktop_pkgs` and `.GlobalEnv` prior to package namespace evaluation, avoiding missing object execution errors during table formatting (`DT::datatable() %>% formatRound()`). * **S3 Registration:** Registers `as.data.frame.webr_datatable` and `as.data.frame.datatables` to ensure piped formatting functions seamlessly access underlying tabular structures. #### 49. `webr_shims$base64encode` & `bc_rank_plot` Screen/File Dual Render * **Purpose:** Zero-dependency binary-to-base64 encoding and dual-device plot output. * **Behavior:** * Implements `b64_encode_file` using pure R bitwise operations (`bitwShiftR`, `bitwOr`, `bitwShiftL`, `bitwAnd`), bypassing missing CLI utilities (`system("base64")`) and package dependencies under Emscripten. * Updates `bc_rank_plot()` in `functions.R` to print directly to the active screen device (`webr::canvas`) so the barcode rank plot immediately appears in the **Plots** tab, while concurrently exporting the plot to PNG (`counts_filtered/barcode_rank.png`) for inline embedding within the HTML QC report. #### 50. `DT` Package Integration & Vectorized `fast_df_to_json` * **Purpose:** High-performance, universal interactive tabular viewer across all course steps (Steps 3, 5, 7, 8, 9). * **Behavior:** * Supports authentic `DT` from `repo.r-wasm.org`, intercepted via `webr_shims$print.datatables` to serialize `x$x` for DataTables rendering in the **Viewer** tab. * Provides a resilient, pure-R fallback engine using vectorized column-wise string assembly (`fast_df_to_json`) for instant rendering without waiting for package downloads. * Preserves `datatable()`, `formatRound()`, `formatSignif()`, `formatCurrency()`, `formatPercentage()`, and `formatStyle()` in `webr_shims`, seamlessly accessible via search path without masking authentic package methods. * Hardens browser-side payload parsing with `