BlueGit

timfa posprint

Files

posprint / lib / browser / posprint_url.js

posprint_url.js

posprint_url.js 1.2 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 * @param {{ noconfirm?: boolean }} [options]
9 * @returns {Promise<string>}
10 */
11export async function posprintUrl(pos, options = {}) {
12 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
13 if (typeof CompressionStream === 'undefined') {
14 throw new Error("CompressionStream('deflate-raw') is not available in this browser");
15 }
16
17 const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
18 const buffer = await new Response(stream).arrayBuffer();
19 const b64 = bytesToBase64Url(new Uint8Array(buffer));
20 let url = `posprint://print?v=1&d=${b64}`;
21 if (options.noconfirm) {
22 url += '&noconfirm=1';
23 }
24 return url;
25}
26
27function bytesToBase64Url(bytes) {
28 let binary = '';
29 for (let i = 0; i < bytes.length; i++) {
30 binary += String.fromCharCode(bytes[i]);
31 }
32 const b64 = btoa(binary);
33 return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
34}