qrcat 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/bin/qrcat.js +225 -0
  4. package/package.json +38 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Joan Miquel Torres Rigo <joanmi@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ qrcat - Add QR codes for urls in your terminal output
2
+ -----------------------------------------------------
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+
5
+ qrcat is a terminal filter that detects URLs in your terminal output and generates additional rows with QR codes for those URLs. This allows you to easily scan the QR codes with your phone or other device to quickly access the URLs.
6
+
7
+ **Example:**
8
+
9
+ ```bash
10
+ $ # Capture a terminal session, including both stdout and stderr
11
+ $ (
12
+ $ trap 'stty sane' EXIT
13
+ $ script -qefc 'npm publish' /dev/null | qrcat
14
+ $ )
15
+ ```
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ npm install -g qrcat
21
+ ```
22
+
23
+ Or run from a checkout with `npm install` followed by `node bin/qrcat.js` (or `npm link`).
24
+
25
+ ## Usage
26
+
27
+ Pipe any command through `qrcat`. Each line is echoed unchanged; after any line
28
+ containing an `http(s)` URL, one QR code per URL is printed directly below it.
29
+ Multiple URLs on one line each get their own QR code.
30
+
31
+ ```bash
32
+ command | qrcat
33
+ qrcat --help
34
+ qrcat --version
35
+ ```
36
+
37
+ ### Interactive commands and output streams
38
+
39
+ qrcat reads **stdin only**. A plain `|` connects stdout, while `2> >(qrcat)` sends
40
+ only stderr. Commands may write different URLs to different streams. For
41
+ example, `npm publish` writes its initial publishing notice to stderr, but its
42
+ web-auth URL to stdout. Thus `npm publish 2> >(qrcat)` can show a QR for the
43
+ registry notice but not the auth URL.
44
+
45
+ Redirecting stdout directly can also change command behavior: npm only runs its
46
+ interactive web-auth flow when stdout is a TTY. `npm publish > >(qrcat)` makes
47
+ stdout a pipe, and can make npm exit with `EOTP` instead of starting that flow.
48
+
49
+ On Linux with util-linux `script`, capture both streams through a pseudo-terminal
50
+ so the command still sees a TTY while qrcat receives its output:
51
+
52
+ ```bash
53
+ (
54
+ trap 'stty sane' EXIT
55
+ script -qefc 'npm publish' /dev/null | qrcat
56
+ )
57
+ ```
58
+
59
+ This is useful for other interactive commands too. For non-interactive commands,
60
+ ordinary pipes or process substitution are simpler; choose the stream(s) that
61
+ actually contain the URLs. Process substitution (`> >(qrcat)`) requires bash or
62
+ zsh and is not POSIX `sh`.
63
+
64
+ #### Caveat: restore the terminal after Ctrl+C
65
+
66
+ On some systems, interrupting `script` with Ctrl+C can leave the outer terminal
67
+ in raw mode. You may stop seeing typed input, and Ctrl+C may no longer interrupt
68
+ the next command. Recover with:
69
+
70
+ ```bash
71
+ stty sane
72
+ ```
73
+
74
+ The example above runs `script` in a subshell with an `EXIT` trap to restore
75
+ terminal settings automatically, including when interrupted.
76
+
77
+ qrcat emits newline-terminated lines as soon as they arrive. It also flushes an
78
+ unterminated line after 100 ms of input inactivity, which supports interactive
79
+ prompts that write partial lines. This idle flush may split a line if a program
80
+ pauses for longer than 100 ms while writing it.
81
+
82
+ ANSI colour codes are stripped before URL detection, so coloured output works,
83
+ including URLs split by colour sequences and OSC 8 hyperlinks.
84
+
85
+ QR codes are drawn with Unicode half-block characters and 24-bit ANSI colour, so
86
+ they need a terminal with truecolor and `▀` support.
87
+
88
+ ## Development
89
+
90
+ ```bash
91
+ npm install
92
+ npm test # node:test suite
93
+ ```
94
+
95
+ ## License
96
+
97
+ [MIT](LICENSE)
98
+
99
+ ## Keywords
100
+
101
+ filter – cat – url – cli – terminal
package/bin/qrcat.js ADDED
@@ -0,0 +1,225 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync, realpathSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import QRCode from 'qrcode';
6
+
7
+ const RESET = '\x1b[0m';
8
+ const FG_DARK = '\x1b[38;2;0;0;0m';
9
+ const FG_LIGHT = '\x1b[38;2;255;255;255m';
10
+ const BG_DARK = '\x1b[48;2;0;0;0m';
11
+ const BG_LIGHT = '\x1b[48;2;255;255;255m';
12
+
13
+ // CSI, OSC (BEL or ST terminated), other single-byte escapes, and C1 CSI.
14
+ const ANSI_RE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[()#][\x20-\x7e]|[@-_])|\x9b[0-?]*[ -/]*[@-~]/g;
15
+ const URL_RE = /https?:\/\/[^\s<>"'`\x1b]+/gi;
16
+ const TRAILING_PUNCT_RE = /[.,;:!?)\]}'">]+$/;
17
+
18
+ const DEFAULT_OPTIONS = { errorCorrectionLevel: 'M', quietZone: 4 };
19
+ const IDLE_FLUSH_MS = 100;
20
+
21
+ /** Remove terminal escape sequences (colours, OSC 8 links, etc.). */
22
+ export function stripAnsi(text) {
23
+ return text.replace(ANSI_RE, '');
24
+ }
25
+
26
+ function extractUrls(text) {
27
+ const urls = new Set();
28
+ for (const match of text.matchAll(URL_RE)) {
29
+ const url = match[0].replace(TRAILING_PUNCT_RE, '');
30
+ if (url) urls.add(url);
31
+ }
32
+ return urls;
33
+ }
34
+
35
+ /**
36
+ * Extract unique http(s) URLs from a line, trimming adjacent punctuation.
37
+ * The stripped copy handles URLs split by colour codes; the raw copy keeps
38
+ * URLs that only exist inside OSC 8 hyperlinks. Raw fragments that are just a
39
+ * prefix of a complete stripped URL are discarded.
40
+ */
41
+ export function findUrls(text) {
42
+ const stripped = extractUrls(stripAnsi(text));
43
+ const urls = new Set(stripped);
44
+ for (const url of extractUrls(text)) {
45
+ const isFragment = [...stripped].some((full) => full.length > url.length && full.startsWith(url));
46
+ if (!isFragment) urls.add(url);
47
+ }
48
+ return [...urls];
49
+ }
50
+
51
+ /**
52
+ * Render a URL as a QR using Unicode upper-half blocks: the foreground colour
53
+ * is the top module, the background colour the bottom one. Two module rows are
54
+ * packed into each terminal row, which keeps the code roughly square.
55
+ */
56
+ export function renderQr(url, options = {}) {
57
+ const { errorCorrectionLevel, quietZone } = { ...DEFAULT_OPTIONS, ...options };
58
+ const qr = QRCode.create(url, { errorCorrectionLevel });
59
+ const size = qr.modules.size + 2 * quietZone;
60
+
61
+ const isDark = (row, col) => {
62
+ const r = row - quietZone;
63
+ const c = col - quietZone;
64
+ if (r < 0 || c < 0 || r >= qr.modules.size || c >= qr.modules.size) return false;
65
+ return qr.modules.get(r, c) === 1;
66
+ };
67
+
68
+ const lines = [];
69
+ for (let row = 0; row < size; row += 2) {
70
+ let line = '';
71
+ for (let col = 0; col < size; col++) {
72
+ const top = isDark(row, col);
73
+ const bottom = row + 1 < size ? isDark(row + 1, col) : false;
74
+ line += (top ? FG_DARK : FG_LIGHT) + (bottom ? BG_DARK : BG_LIGHT) + '▀';
75
+ }
76
+ lines.push(line + RESET);
77
+ }
78
+ return lines.join('\n');
79
+ }
80
+
81
+ /** Full output block for one input line: the original line, then a QR per URL. */
82
+ export function formatLine(line, options = {}) {
83
+ const urls = findUrls(line);
84
+ if (urls.length === 0) return line;
85
+ const blocks = urls.map((url) => `\n\n${renderQr(url, options)}`);
86
+ return line + blocks.join('') + '\n';
87
+ }
88
+
89
+ /**
90
+ * Process input as it arrives. Complete lines are emitted immediately; an
91
+ * unterminated line is emitted after a short idle period so interactive tools
92
+ * that write a URL without a final newline can still produce a QR promptly.
93
+ */
94
+ export function processInput(input, output = process.stdout, idleFlushMs = IDLE_FLUSH_MS) {
95
+ input.setEncoding('utf8');
96
+
97
+ return new Promise((resolve, reject) => {
98
+ let pending = '';
99
+ let timer;
100
+ let previousWasCR = false;
101
+ let skipNextDelimiter = false;
102
+
103
+ const clearTimer = () => {
104
+ if (timer) clearTimeout(timer);
105
+ timer = undefined;
106
+ };
107
+
108
+ const lineEnding = output.isTTY ? '\r\n' : '\n';
109
+ const emitLine = (line) =>
110
+ output.write((formatLine(line) + '\n').replace(/\n/g, lineEnding));
111
+
112
+ const onError = (error) => {
113
+ clearTimer();
114
+ reject(error);
115
+ };
116
+
117
+ const flushIdle = () => {
118
+ timer = undefined;
119
+ if (!pending) return;
120
+ try {
121
+ emitLine(pending);
122
+ pending = '';
123
+ // The idle flush supplies the line ending; don't emit an extra empty
124
+ // line if the input's actual delimiter arrives later.
125
+ skipNextDelimiter = true;
126
+ } catch (error) {
127
+ onError(error);
128
+ }
129
+ };
130
+
131
+ const onData = (chunk) => {
132
+ clearTimer();
133
+ try {
134
+ for (const char of chunk) {
135
+ if (char === '\n' && previousWasCR) {
136
+ previousWasCR = false;
137
+ continue;
138
+ }
139
+
140
+ previousWasCR = false;
141
+ if (char === '\n' || char === '\r') {
142
+ if (skipNextDelimiter) {
143
+ skipNextDelimiter = false;
144
+ } else {
145
+ emitLine(pending);
146
+ pending = '';
147
+ }
148
+ previousWasCR = char === '\r';
149
+ continue;
150
+ }
151
+
152
+ skipNextDelimiter = false;
153
+ pending += char;
154
+ }
155
+
156
+ if (pending) timer = setTimeout(flushIdle, idleFlushMs);
157
+ } catch (error) {
158
+ onError(error);
159
+ }
160
+ };
161
+
162
+ const onEnd = () => {
163
+ clearTimer();
164
+ try {
165
+ if (pending) emitLine(pending);
166
+ resolve();
167
+ } catch (error) {
168
+ reject(error);
169
+ }
170
+ };
171
+
172
+ input.on('data', onData);
173
+ input.once('end', onEnd);
174
+ input.once('error', onError);
175
+ });
176
+ }
177
+
178
+ function printHelp() {
179
+ process.stdout.write(
180
+ 'qrcat - add QR codes for URLs in terminal output\n\n' +
181
+ 'Usage: command | qrcat\n\n' +
182
+ 'Reads stdin line by line, echoes each line unchanged, and prints a QR\n' +
183
+ 'code right after any line containing an http(s) URL. Unterminated lines\n' +
184
+ 'are flushed after 100 ms of input inactivity.\n\n' +
185
+ 'Options:\n' +
186
+ ' -h, --help show this help\n' +
187
+ ' -v, --version show version\n',
188
+ );
189
+ }
190
+
191
+ async function main() {
192
+ const args = process.argv.slice(2);
193
+ if (args.includes('-h') || args.includes('--help')) {
194
+ printHelp();
195
+ return;
196
+ }
197
+ if (args.includes('-v') || args.includes('--version')) {
198
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
199
+ process.stdout.write(`${pkg.version}\n`);
200
+ return;
201
+ }
202
+
203
+ process.stdout.on('error', (err) => {
204
+ if (err.code === 'EPIPE') process.exit(0);
205
+ throw err;
206
+ });
207
+
208
+ await processInput(process.stdin);
209
+ }
210
+
211
+ function isMainModule() {
212
+ if (!process.argv[1]) return false;
213
+ try {
214
+ return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+
220
+ if (isMainModule()) {
221
+ main().catch((err) => {
222
+ process.stderr.write(`qrcat: ${err.message}\n`);
223
+ process.exitCode = 1;
224
+ });
225
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "qrcat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Output filter to add QR codes to URLs",
5
+ "keywords": [
6
+ "QR",
7
+ "filter",
8
+ "cat",
9
+ "url",
10
+ "cli",
11
+ "terminal"
12
+ ],
13
+ "homepage": "https://github.com/bitifet/qrcat#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/bitifet/qrcat/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/bitifet/qrcat.git"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Joan Miquel Torres <joanmi@gmail.com>",
23
+ "type": "module",
24
+ "main": "bin/qrcat.js",
25
+ "bin": {
26
+ "qrcat": "bin/qrcat.js"
27
+ },
28
+ "files": [
29
+ "bin"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "scripts": {
35
+ "test": "node --test"
36
+ },
37
+ "dependencies": {
38
+ "qrcode": "1.5.4"
39
+ }
40
+ }