@viict/tread 0.3.0

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.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # tread
2
+
3
+ A terminal reader for markdown, CSV, JSON and source code — `less`, but it
4
+ understands what it is showing: collapsible headings, real tables, colored
5
+ links, and navigation across a corpus of linked documents.
6
+
7
+ ```sh
8
+ npx @viict/tread README.md
9
+ ```
10
+
11
+ > The unscoped name `tread` on npm belongs to an unrelated package. The scope is
12
+ > not optional: `npx @viict/tread`.
13
+
14
+ Or install it so the binary is on your `PATH` as `tread`:
15
+
16
+ ```sh
17
+ npm install -g @viict/tread
18
+ ```
19
+
20
+ ## What this package is
21
+
22
+ `tread` is a Rust program with no dependencies. This package is a small launcher
23
+ that downloads the build for your machine on first run, verifies its SHA-256
24
+ against the checksums published with the release, and then gets out of the way.
25
+ Nothing is downloaded at install time, so `npm ci --ignore-scripts` and pnpm's
26
+ default script blocking are not a problem.
27
+
28
+ The binary is kept per version under your platform's data directory:
29
+
30
+ | Platform | Location |
31
+ | --- | --- |
32
+ | Linux | `$XDG_DATA_HOME/tread/<version>/`, else `~/.local/share/tread/<version>/` |
33
+ | macOS | `~/Library/Application Support/tread/<version>/` |
34
+ | Windows | `%LOCALAPPDATA%\tread\<version>\` |
35
+
36
+ Older versions are removed once a new one has been fetched.
37
+
38
+ ## Using a binary you already have
39
+
40
+ Set `TREAD_BINARY` and nothing is ever downloaded:
41
+
42
+ ```sh
43
+ export TREAD_BINARY=/usr/local/bin/tread
44
+ ```
45
+
46
+ That is the right answer for a machine with several user accounts sharing one
47
+ install, and for a CI runner with no route to the internet. If `TREAD_BINARY`
48
+ names something that is not there, the run fails — it never falls back to
49
+ downloading a second copy behind your back.
50
+
51
+ ## Other ways to install
52
+
53
+ ```sh
54
+ cargo install tread # from crates.io, builds from source
55
+ ```
56
+
57
+ Prebuilt archives for every supported platform, and the `SHA256SUMS` this
58
+ launcher verifies against, are on the
59
+ [releases page](https://github.com/viict/tread/releases).
60
+
61
+ ## Licence
62
+
63
+ MIT OR Apache-2.0.
package/bin/tread.js ADDED
@@ -0,0 +1,253 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // The npm entry point for tread.
5
+ //
6
+ // This file is a launcher, not the program. `tread` is a Rust binary with no
7
+ // dependencies; npm carries a five-kilobyte shim that finds the right build for
8
+ // this machine, fetches it once, and hands the terminal over to it.
9
+ //
10
+ // Three rules shape everything below:
11
+ //
12
+ // * Nothing runs that was not verified. The archive's SHA-256 is checked
13
+ // against the SHA256SUMS published with the release before the file is put
14
+ // anywhere it could be executed. A download that does not match is deleted
15
+ // and the run fails loudly.
16
+ // * The binary is state, not cache. It lives under the platform's *data*
17
+ // directory, because a cache is something the OS may delete — macOS purges
18
+ // ~/Library/Caches under disk pressure — and a binary that vanishes leaves
19
+ // an offline machine unable to run tread at all. The table below mirrors
20
+ // src/plat/dirs.rs; if one changes, change both.
21
+ // * A version is a directory. Upgrading needs no invalidation logic: a new
22
+ // version writes a new directory and the old ones are pruned once the new
23
+ // binary has run.
24
+ //
25
+ // TREAD_BINARY points at a tread you already have and skips all of it, which is
26
+ // what a single global install on a multi-user machine wants, and what a locked
27
+ // down CI runner needs. It is honoured exactly: if it names something that is
28
+ // not there, the run fails rather than quietly downloading a second copy.
29
+ //
30
+ // Zero dependencies here too — only node's own https, crypto and fs, plus the
31
+ // archive reader in ../lib/unpack.js. The launcher reads the very archives the
32
+ // releases page publishes and `install.sh` verifies; the release is not asked
33
+ // to carry a second, npm-shaped copy of every binary.
34
+
35
+ const { spawnSync } = require("child_process");
36
+ const crypto = require("crypto");
37
+ const fs = require("fs");
38
+ const https = require("https");
39
+ const os = require("os");
40
+ const path = require("path");
41
+
42
+ const { extract } = require("../lib/unpack.js");
43
+
44
+ const VERSION = require("../package.json").version;
45
+ const REPO = "viict/tread";
46
+ const MAX_BYTES = 32 * 1024 * 1024;
47
+ const MAX_REDIRECTS = 5;
48
+
49
+ /// node's platform-arch pair to the Rust target its release asset is named for.
50
+ const TARGETS = {
51
+ "linux-x64": "x86_64-unknown-linux-musl",
52
+ "linux-arm64": "aarch64-unknown-linux-musl",
53
+ "darwin-x64": "x86_64-apple-darwin",
54
+ "darwin-arm64": "aarch64-apple-darwin",
55
+ "win32-x64": "x86_64-pc-windows-msvc",
56
+ "win32-arm64": "aarch64-pc-windows-msvc",
57
+ };
58
+
59
+ function die(message) {
60
+ console.error(`tread: ${message}`);
61
+ process.exit(1);
62
+ }
63
+
64
+ /// Where downloaded binaries live, before the version is appended.
65
+ ///
66
+ /// An explicitly set XDG_DATA_HOME wins everywhere, including macOS: a user who
67
+ /// exports it has said where their data goes.
68
+ function dataRoot() {
69
+ const xdg = process.env.XDG_DATA_HOME;
70
+ if (xdg) {
71
+ return path.join(xdg, "tread");
72
+ }
73
+ if (process.platform === "win32") {
74
+ // %LOCALAPPDATA%, never %APPDATA%: the roaming half of a Windows profile is
75
+ // synced to the domain server, and a machine-specific binary must not
76
+ // travel to a machine it was not built for.
77
+ const local =
78
+ process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
79
+ return path.join(local, "tread");
80
+ }
81
+ if (process.platform === "darwin") {
82
+ return path.join(os.homedir(), "Library", "Application Support", "tread");
83
+ }
84
+ return path.join(os.homedir(), ".local", "share", "tread");
85
+ }
86
+
87
+ function exeName() {
88
+ return process.platform === "win32" ? "tread.exe" : "tread";
89
+ }
90
+
91
+ /// GET `url` and buffer the body, following the redirect GitHub sends to its
92
+ /// asset store. Bounded: a body that will not fit in memory is not a release.
93
+ function get(url, redirects = 0) {
94
+ return new Promise((resolve, reject) => {
95
+ const req = https.get(
96
+ url,
97
+ { headers: { "user-agent": `tread-npm/${VERSION}` } },
98
+ (res) => {
99
+ const { statusCode, headers } = res;
100
+ if (statusCode >= 300 && statusCode < 400 && headers.location) {
101
+ res.resume();
102
+ if (redirects >= MAX_REDIRECTS) {
103
+ reject(new Error("too many redirects"));
104
+ return;
105
+ }
106
+ resolve(get(new URL(headers.location, url).toString(), redirects + 1));
107
+ return;
108
+ }
109
+ if (statusCode !== 200) {
110
+ res.resume();
111
+ reject(new Error(`HTTP ${statusCode} for ${url}`));
112
+ return;
113
+ }
114
+ const chunks = [];
115
+ let size = 0;
116
+ res.on("data", (c) => {
117
+ size += c.length;
118
+ if (size > MAX_BYTES) {
119
+ req.destroy();
120
+ reject(new Error("response is larger than a release could be"));
121
+ return;
122
+ }
123
+ chunks.push(c);
124
+ });
125
+ res.on("end", () => resolve(Buffer.concat(chunks)));
126
+ }
127
+ );
128
+ req.on("error", reject);
129
+ req.setTimeout(60_000, () => {
130
+ req.destroy();
131
+ reject(new Error("timed out"));
132
+ });
133
+ });
134
+ }
135
+
136
+ /// The SHA-256 the release published for `asset`, as lower-case hex.
137
+ ///
138
+ /// SHA256SUMS is the concatenation of `sha256sum` output, one `<hex> <name>`
139
+ /// line per artifact. An asset missing from it is a release we refuse to trust,
140
+ /// not one we install anyway.
141
+ function sumFor(sums, asset) {
142
+ for (const line of sums.toString("utf8").split("\n")) {
143
+ const [hex, name] = line.trim().split(/\s+/);
144
+ if (name === asset && /^[0-9a-f]{64}$/.test(hex)) {
145
+ return hex;
146
+ }
147
+ }
148
+ return null;
149
+ }
150
+
151
+ /// Fetch, verify and unpack the binary for this platform into `dir`.
152
+ ///
153
+ /// The write is atomic by rename from a pid-named temporary, so two first runs
154
+ /// racing each other both succeed and one of them wins the rename. No lock file
155
+ /// is needed and none is left behind if a run is killed mid-download.
156
+ async function install(dir, target) {
157
+ const win = process.platform === "win32";
158
+ const asset = `tread-v${VERSION}-${target}${win ? ".zip" : ".tar.gz"}`;
159
+ const base = `https://github.com/${REPO}/releases/download/v${VERSION}`;
160
+ process.stderr.write(`tread: fetching ${asset}\n`);
161
+
162
+ const [sums, packed] = await Promise.all([
163
+ get(`${base}/SHA256SUMS`),
164
+ get(`${base}/${asset}`),
165
+ ]);
166
+
167
+ const want = sumFor(sums, asset);
168
+ if (!want) {
169
+ throw new Error(`${asset} is not listed in SHA256SUMS`);
170
+ }
171
+ const got = crypto.createHash("sha256").update(packed).digest("hex");
172
+ if (got !== want) {
173
+ throw new Error(`checksum mismatch for ${asset}: expected ${want}, got ${got}`);
174
+ }
175
+
176
+ // Only now, with the archive proven to be the one the release published, is
177
+ // anything read out of it.
178
+ const binary = extract(asset, packed, exeName());
179
+ if (!binary) {
180
+ throw new Error(`${asset} does not contain ${exeName()}`);
181
+ }
182
+
183
+ fs.mkdirSync(dir, { recursive: true });
184
+ const tmp = path.join(dir, `.tread-${process.pid}`);
185
+ fs.writeFileSync(tmp, binary, { mode: 0o755 });
186
+ fs.renameSync(tmp, path.join(dir, exeName()));
187
+ }
188
+
189
+ /// Drop every version directory but this one, once this one is known good.
190
+ function prune(root, keep) {
191
+ let entries = [];
192
+ try {
193
+ entries = fs.readdirSync(root);
194
+ } catch {
195
+ return;
196
+ }
197
+ for (const name of entries) {
198
+ if (name !== keep) {
199
+ fs.rmSync(path.join(root, name), { recursive: true, force: true });
200
+ }
201
+ }
202
+ }
203
+
204
+ /// Hand the terminal to the binary: stdio is inherited, so raw mode, resize and
205
+ /// the terminal's own drag-select all reach it untouched, and tread's exit code
206
+ /// is this process's exit code.
207
+ function run(bin) {
208
+ const r = spawnSync(bin, process.argv.slice(2), { stdio: "inherit" });
209
+ if (r.error) {
210
+ die(`could not run ${bin}: ${r.error.message}`);
211
+ }
212
+ process.exit(r.status === null ? 1 : r.status);
213
+ }
214
+
215
+ async function main() {
216
+ const override = process.env.TREAD_BINARY;
217
+ if (override) {
218
+ if (!fs.existsSync(override)) {
219
+ die(`TREAD_BINARY is set to ${override}, which does not exist`);
220
+ }
221
+ run(override);
222
+ }
223
+
224
+ const key = `${process.platform}-${process.arch}`;
225
+ const target = TARGETS[key];
226
+ if (!target) {
227
+ die(
228
+ `no published build for ${key}. Install from source with ` +
229
+ `\`cargo install tread\`, or point TREAD_BINARY at a tread you built.`
230
+ );
231
+ }
232
+
233
+ const root = dataRoot();
234
+ const dir = path.join(root, VERSION);
235
+ const bin = path.join(dir, exeName());
236
+
237
+ if (!fs.existsSync(bin)) {
238
+ try {
239
+ await install(dir, target);
240
+ } catch (e) {
241
+ die(
242
+ `could not install the ${target} build: ${e.message}\n` +
243
+ ` tread was not downloaded, so nothing unverified has been run.\n` +
244
+ ` Offline or behind a proxy? Install it yourself and set TREAD_BINARY.`
245
+ );
246
+ }
247
+ prune(root, VERSION);
248
+ }
249
+
250
+ run(bin);
251
+ }
252
+
253
+ main().catch((e) => die(e.message));
package/lib/unpack.js ADDED
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+
3
+ // Pulling one file out of a release archive, with node's zlib and nothing else.
4
+ //
5
+ // The release publishes a `.tar.gz` per unix target and a `.zip` per Windows
6
+ // one, each holding the binary beside the README, the licences and `docs/`.
7
+ // Those archives are what `install.sh` verifies and what a person downloads by
8
+ // hand, so the npm launcher reads the same bytes rather than asking the release
9
+ // to carry a second, npm-shaped copy of every binary.
10
+ //
11
+ // node has `zlib` built in and no archive reader. Both formats are simple
12
+ // enough to walk directly: a tar is 512-byte headers each followed by its
13
+ // file's bytes, and a zip is a central directory of entries pointing at
14
+ // deflate streams `zlib.inflateRawSync` already understands. That is about a
15
+ // hundred lines here against a dependency in a package that has none — and
16
+ // against three megabytes of duplicated binary on every release.
17
+ //
18
+ // Both readers are handed an archive whose SHA-256 has *already* been checked
19
+ // against the release's `SHA256SUMS` (see `bin/tread.js`), so this code parses
20
+ // bytes that are known to be the ones the release published. It is deliberately
21
+ // strict anyway: unknown shapes return null rather than guessing, and nothing
22
+ // here writes to disk or follows a path out of the archive — the caller asks
23
+ // for one base name and gets bytes back.
24
+
25
+ const zlib = require("zlib");
26
+
27
+ /// A NUL-terminated fixed-width field, as tar writes them.
28
+ function cstr(buf) {
29
+ const end = buf.indexOf(0);
30
+ return buf.toString("utf8", 0, end === -1 ? buf.length : end);
31
+ }
32
+
33
+ /// The last path component, for either separator.
34
+ function base(name) {
35
+ const cut = Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\"));
36
+ return cut === -1 ? name : name.slice(cut + 1);
37
+ }
38
+
39
+ /// The bytes of the file named `want` inside a gzipped tar, or null.
40
+ ///
41
+ /// Only regular files are considered: type `0`, or a NUL for the pre-POSIX
42
+ /// spelling of the same thing. Every other entry — directories, long-name
43
+ /// extensions, anything unrecognised — is skipped rather than interpreted.
44
+ function fromTarGz(packed, want) {
45
+ const tar = zlib.gunzipSync(packed);
46
+ let at = 0;
47
+ while (at + 512 <= tar.length) {
48
+ const head = tar.subarray(at, at + 512);
49
+ if (head[0] === 0) {
50
+ return null; // the two zero blocks that end an archive
51
+ }
52
+ const name = cstr(head.subarray(0, 100));
53
+ const size = parseInt(cstr(head.subarray(124, 136)).trim() || "0", 8);
54
+ if (!Number.isFinite(size) || size < 0 || at + 512 + size > tar.length) {
55
+ return null;
56
+ }
57
+ const type = head[156];
58
+ const body = at + 512;
59
+ if ((type === 0x30 || type === 0) && base(name) === want) {
60
+ return tar.subarray(body, body + size);
61
+ }
62
+ at = body + Math.ceil(size / 512) * 512;
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /// Offset of the end-of-central-directory record, searching from the end.
68
+ ///
69
+ /// The record is 22 bytes plus a comment of up to 64 KiB, so the search window
70
+ /// is bounded by the format rather than by the file.
71
+ function endOfDirectory(buf) {
72
+ const floor = Math.max(0, buf.length - (22 + 0xffff));
73
+ for (let at = buf.length - 22; at >= floor; at--) {
74
+ if (buf.readUInt32LE(at) === 0x06054b50) {
75
+ return at;
76
+ }
77
+ }
78
+ return -1;
79
+ }
80
+
81
+ /// The bytes of the file named `want` inside a zip, or null.
82
+ ///
83
+ /// Stored (method 0) and deflated (method 8) entries are read; anything else is
84
+ /// skipped. Sizes come from the central directory, which is authoritative even
85
+ /// when the local header defers them to a data descriptor.
86
+ function fromZip(buf, want) {
87
+ const eocd = endOfDirectory(buf);
88
+ if (eocd === -1) {
89
+ return null;
90
+ }
91
+ const count = buf.readUInt16LE(eocd + 10);
92
+ let at = buf.readUInt32LE(eocd + 16);
93
+ for (let i = 0; i < count; i++) {
94
+ if (at + 46 > buf.length || buf.readUInt32LE(at) !== 0x02014b50) {
95
+ return null;
96
+ }
97
+ const method = buf.readUInt16LE(at + 10);
98
+ const packed = buf.readUInt32LE(at + 20);
99
+ const nameLen = buf.readUInt16LE(at + 28);
100
+ const extraLen = buf.readUInt16LE(at + 30);
101
+ const commentLen = buf.readUInt16LE(at + 32);
102
+ const local = buf.readUInt32LE(at + 42);
103
+ const name = buf.toString("utf8", at + 46, at + 46 + nameLen);
104
+ if (base(name) === want && (method === 0 || method === 8)) {
105
+ return inflateAt(buf, local, packed, method);
106
+ }
107
+ at += 46 + nameLen + extraLen + commentLen;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /// Read one entry's data, given where its *local* header sits. The local
113
+ /// header repeats the name and extra fields at its own lengths, which are the
114
+ /// only way to know where the data starts.
115
+ function inflateAt(buf, local, packed, method) {
116
+ if (local + 30 > buf.length || buf.readUInt32LE(local) !== 0x04034b50) {
117
+ return null;
118
+ }
119
+ const nameLen = buf.readUInt16LE(local + 26);
120
+ const extraLen = buf.readUInt16LE(local + 28);
121
+ const from = local + 30 + nameLen + extraLen;
122
+ if (from + packed > buf.length) {
123
+ return null;
124
+ }
125
+ const raw = buf.subarray(from, from + packed);
126
+ return method === 0 ? raw : zlib.inflateRawSync(raw);
127
+ }
128
+
129
+ /// Pull `want` out of whichever archive shape `asset` names.
130
+ function extract(asset, bytes, want) {
131
+ return asset.endsWith(".zip")
132
+ ? fromZip(bytes, want)
133
+ : fromTarGz(bytes, want);
134
+ }
135
+
136
+ module.exports = { extract, fromTarGz, fromZip };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@viict/tread",
3
+ "version": "0.3.0",
4
+ "private": false,
5
+ "description": "A terminal reader for markdown, CSV, JSON and source code. Zero dependencies.",
6
+ "keywords": [
7
+ "pager",
8
+ "markdown",
9
+ "csv",
10
+ "json",
11
+ "terminal",
12
+ "less",
13
+ "cli"
14
+ ],
15
+ "homepage": "https://github.com/viict/tread#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/viict/tread.git"
19
+ },
20
+ "bugs": "https://github.com/viict/tread/issues",
21
+ "license": "MIT OR Apache-2.0",
22
+ "type": "commonjs",
23
+ "bin": {
24
+ "tread": "bin/tread.js"
25
+ },
26
+ "files": [
27
+ "bin/tread.js",
28
+ "lib/unpack.js",
29
+ "README.md"
30
+ ],
31
+ "engines": {
32
+ "node": ">=16"
33
+ }
34
+ }