// The smallest QR version that holds a code's whole content at the error correction it uses, counting the content // in one mode for all of it: numeric, alphanumeric or bytes. A mix of modes can only take as many bits or fewer, so // the version is never smaller than the smallest that holds the content. The capacities and what each mode spends // come from data/capacity.json (ISO/IEC 18004). It all runs in the browser: nothing is sent or stored. import { getJson } from './copy.js'; let C; // data/capacity.json export async function loadCapacity(url) { C = await getJson(url); } /** The bits the whole text takes at version v in one mode: numeric or alphanumeric when every character is one of * that mode's, otherwise bytes, in ISO 8859-1 (QR's default) when every character is in it, else in UTF-8 after an * ECI header. GS1's FNC1 marker is counted for every text, since a reading doesn't say whether a code carries it. * The terminator may be cut short, as the standard allows, so it isn't counted. */ function bits(text, v) { const chars = [...text]; const i = C.count_bits_from.filter((from) => v >= from).length - 1; const mode = ['numeric', 'alphanumeric'].find((k) => chars.every((c) => C.modes[k].chars.includes(c))) || 'byte'; const latin = chars.every((c) => c.codePointAt(0) <= 0xff); // In FNC1 mode a literal % in alphanumeric data is written %%, so each % counts twice there. const twice = mode === 'alphanumeric' ? chars.filter((c) => c === '%').length : 0; const n = (latin ? chars.length : new TextEncoder().encode(text).length) + twice; const m = C.modes[mode]; return C.fnc1_bits + (latin ? 0 : C.eci_bits) + C.mode_bits + m.count_bits[i] + m.bits[m.group] * Math.floor(n / m.group) + m.bits[n % m.group]; } /** The smallest version (1 to 40) whose data codewords at error correction ec ('L', 'M', 'Q' or 'H') hold the whole * text; null for an empty text, an error correction it doesn't know, or a text no version holds. */ export function smallestVersion(text, ec) { const cw = C?.data_codewords?.[ec]; if (!Array.isArray(cw) || !text) return null; const v = cw.findIndex((c, k) => bits(text, k + 1) <= 8 * c) + 1; return v || null; } /** The smaller version a read picture's whole content fits, at the error correction zxing-cpp read, or null. Only for * an uncut text the scanners themselves gave (its UTF-8 bytes are the content's: the server's own ISO 8859-1 * reading of other bytes may hide a character set the code names in an ECI header), with the version from a scanner, * and only below that version. */ export function smallerVersion(r) { const c = r?.content; const v = r?.checks?.modules_from === 'scanner' ? r.checks.version : null; const whole = c?.text != null && !c.cut && c.bytes === new TextEncoder().encode(c.text).length; if (!whole || v == null) return null; const v2 = smallestVersion(c.text, r.ec_level); return v2 != null && v2 < v ? v2 : null; }