BlueGit

timfa posprint

Files

posprint / lib / browser / posprint_url.js

posprint_url.js

posprint_url.js 1.0 KiB Download Raw
1/**
2 * Build a posprint:// URL from a .pos document (object or JSON string).
3 *
4 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 *
7 * @param {object|string} pos
8 * @returns {Promise<string>}
9 */
10export async function posprintUrl(pos) {
11 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12 if (typeof CompressionStream === 'undefined') {
13 throw new Error("CompressionStream('deflate-raw') is not available in this browser");
14 }
15
16 const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17 const buffer = await new Response(stream).arrayBuffer();
18 const b64 = bytesToBase64Url(new Uint8Array(buffer));
19 return `posprint://print?v=1&d=${b64}`;
20}
21
22function bytesToBase64Url(bytes) {
23 let binary = '';
24 for (let i = 0; i < bytes.length; i++) {
25 binary += String.fromCharCode(bytes[i]);
26 }
27 const b64 = btoa(binary);
28 return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
29}