UNPKG

@eagleoutice/flowr-dev

Version:

Static Dataflow Analyzer and Program Slicer for the R Programming Language

59 lines 2.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.toBase64 = toBase64; exports.toBase64Url = toBase64Url; exports.fromBase64Url = fromBase64Url; exports.packForUrl = packForUrl; exports.unpackFromUrl = unpackFromUrl; const lz_string_1 = require("lz-string"); /** * Base64 for the pages flowR ships, which run in a browser and therefore have `btoa`/`atob` rather than * node's `Buffer`. The url-safe pair is what lets the playground keep a script in its own address, so a * link is the example. */ /** bytes as base64 */ function toBase64(bytes) { let binary = ''; for (const byte of bytes) { binary += String.fromCharCode(byte); } return btoa(binary); } /** text as base64 in the alphabet a url carries without escaping anything, padding dropped */ function toBase64Url(text) { return toBase64(new TextEncoder().encode(text)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, ''); } /** the inverse of {@link toBase64Url}, `undefined` for anything that is not what it produced */ function fromBase64Url(text) { try { const binary = atob(text.replaceAll('-', '+').replaceAll('_', '/')); return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(binary, character => character.charCodeAt(0))); } catch { return undefined; /* a link someone edited by hand */ } } /** Text as short as it goes while staying a url: compressed when that helps, plain base64 when it does not. */ function packForUrl(text) { const plain = toBase64Url(text); if (text.length === 0) { return "t" /* Packing.Plain */ + plain; } const compressed = (0, lz_string_1.compressToEncodedURIComponent)(text); return compressed.length < plain.length ? "z" /* Packing.Compressed */ + compressed : "t" /* Packing.Plain */ + plain; } /** The inverse of {@link packForUrl}, `undefined` for anything it did not produce. */ function unpackFromUrl(payload) { const rest = payload.slice(1); try { switch (payload[0]) { case "z" /* Packing.Compressed */: return (0, lz_string_1.decompressFromEncodedURIComponent)(rest) ?? undefined; case "t" /* Packing.Plain */: return fromBase64Url(rest); default: return undefined; } } catch { return undefined; /* a link someone edited by hand */ } } //# sourceMappingURL=url-encoding.js.map