rucan 0.0.0-stage → 0.1.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.
@@ -0,0 +1,142 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdir, readFile, realpath, rename, unlink, writeFile, } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import { isAbsolute, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { promisify } from "node:util";
8
+ import { compareVersions, stableVersion, version } from "./version.js";
9
+ const registry = "https://registry.npmjs.org";
10
+ const ttl = 6 * 60 * 60 * 1000;
11
+ function directory() {
12
+ const configured = process.env.XDG_CACHE_HOME;
13
+ return join(configured && isAbsolute(configured)
14
+ ? configured
15
+ : join(homedir(), ".cache"), "rucan");
16
+ }
17
+ async function save(name, contents) {
18
+ const path = directory();
19
+ await mkdir(path, { recursive: true, mode: 0o700 });
20
+ const temporary = join(path, randomUUID());
21
+ try {
22
+ await writeFile(temporary, contents, { mode: 0o600, flag: "wx" });
23
+ await rename(temporary, join(path, name));
24
+ }
25
+ finally {
26
+ await unlink(temporary).catch(() => { });
27
+ }
28
+ }
29
+ async function readCache() {
30
+ try {
31
+ const raw = JSON.parse(await readFile(join(directory(), "updates.json"), "utf8"));
32
+ if (typeof raw !== "object" ||
33
+ raw === null ||
34
+ !("checkedAt" in raw) ||
35
+ typeof raw.checkedAt !== "number" ||
36
+ raw.checkedAt > Date.now() ||
37
+ raw.checkedAt < 0) {
38
+ return undefined;
39
+ }
40
+ const latest = "latest" in raw ? stableVersion(raw.latest) : undefined;
41
+ return { checkedAt: raw.checkedAt, ...(latest ? { latest } : {}) };
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ }
47
+ async function fetchLatest() {
48
+ const response = await fetch(`${registry}/rucan/latest`, {
49
+ signal: AbortSignal.timeout(1800),
50
+ headers: { accept: "application/json" },
51
+ });
52
+ if (!response.ok || !response.body)
53
+ return undefined;
54
+ const reader = response.body.getReader();
55
+ const chunks = [];
56
+ let size = 0;
57
+ try {
58
+ for (;;) {
59
+ const result = await reader.read();
60
+ if (result.done)
61
+ break;
62
+ size += result.value.length;
63
+ if (size > 65536)
64
+ return undefined;
65
+ chunks.push(result.value);
66
+ }
67
+ }
68
+ finally {
69
+ await reader.cancel().catch(() => { });
70
+ }
71
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
72
+ return typeof body === "object" && body !== null && "version" in body
73
+ ? stableVersion(body.version)
74
+ : undefined;
75
+ }
76
+ export async function availableUpdate(force = false) {
77
+ const cached = await readCache();
78
+ let latest = cached?.latest;
79
+ if (force || !cached || Date.now() - cached.checkedAt > ttl) {
80
+ try {
81
+ latest = await fetchLatest();
82
+ await save("updates.json", JSON.stringify({ checkedAt: Date.now(), latest })).catch(() => { });
83
+ }
84
+ catch {
85
+ // An outage should still allow a previously cached update to be displayed.
86
+ }
87
+ }
88
+ if (!latest || compareVersions(latest, version) <= 0)
89
+ return undefined;
90
+ const skip = await readFile(join(directory(), "skip-version"), "utf8").catch(() => "");
91
+ return !force && skip.trim() === latest ? undefined : latest;
92
+ }
93
+ export async function skipUpdate(target) {
94
+ if (!stableVersion(target))
95
+ throw new Error("Invalid version to skip");
96
+ await save("skip-version", target + "\n");
97
+ }
98
+ async function installMethod() {
99
+ const packageDirectory = await realpath(fileURLToPath(new URL("../../", import.meta.url)));
100
+ const managers = ["npm", "pnpm"];
101
+ const results = await Promise.all(managers.map(async (manager) => {
102
+ try {
103
+ const { stdout } = await promisify(execFile)(manager, ["root", "--global"], {
104
+ encoding: "utf8",
105
+ maxBuffer: 16384,
106
+ timeout: 2000,
107
+ });
108
+ return (await realpath(join(stdout.trim(), "rucan"))) ===
109
+ packageDirectory
110
+ ? manager
111
+ : undefined;
112
+ }
113
+ catch {
114
+ return undefined;
115
+ }
116
+ }));
117
+ return results.find((manager) => manager !== undefined);
118
+ }
119
+ export async function installUpdate(target) {
120
+ if (!stableVersion(target) || compareVersions(target, version) <= 0)
121
+ throw new Error("Expected a newer stable version");
122
+ const method = await installMethod();
123
+ if (!method)
124
+ throw new Error("This installation is managed externally. Install the update using the original installation method.");
125
+ const args = [
126
+ method === "pnpm" ? "add" : "install",
127
+ "--global",
128
+ "--ignore-scripts",
129
+ `--registry=${registry}`,
130
+ `rucan@${target}`,
131
+ ];
132
+ await new Promise((resolve, reject) => {
133
+ const child = spawn(method, args, { stdio: "inherit" });
134
+ child.once("error", reject);
135
+ child.once("exit", (code) => {
136
+ if (code === 0)
137
+ resolve();
138
+ else
139
+ reject(new Error(`Update exited with status ${code}`));
140
+ });
141
+ });
142
+ }
@@ -0,0 +1,30 @@
1
+ import { createRequire } from "node:module";
2
+ const metadata = createRequire(import.meta.url)("../../package.json");
3
+ export function stableVersion(value) {
4
+ if (typeof value !== "string" ||
5
+ !/^(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/u.test(value))
6
+ return undefined;
7
+ return value;
8
+ }
9
+ function packageVersion() {
10
+ if (typeof metadata === "object" &&
11
+ metadata !== null &&
12
+ "version" in metadata) {
13
+ const version = stableVersion(metadata.version);
14
+ if (version)
15
+ return version;
16
+ }
17
+ throw new Error("Invalid rucan package version");
18
+ }
19
+ export const version = packageVersion();
20
+ export function compareVersions(first, second) {
21
+ if (!stableVersion(first) || !stableVersion(second))
22
+ throw new Error("Expected stable version numbers");
23
+ const right = second.split(".").map(Number);
24
+ for (const [position, left] of first.split(".").map(Number).entries()) {
25
+ const difference = left - (right[position] ?? 0);
26
+ if (difference)
27
+ return Math.sign(difference);
28
+ }
29
+ return 0;
30
+ }
@@ -0,0 +1,94 @@
1
+ const pasteStart = Buffer.from("\x1b[200~");
2
+ const pasteEnd = Buffer.from("\x1b[201~");
3
+ const mouseStart = Buffer.from("\x1b[<");
4
+ function mouseReport(bytes) {
5
+ const prefix = bytes.subarray(0, mouseStart.length);
6
+ if (!mouseStart.subarray(0, prefix.length).equals(prefix))
7
+ return undefined;
8
+ const text = bytes.subarray(0, 32).toString("latin1");
9
+ const match = /^\x1b\[<(\d{1,3});(\d{1,5});(\d{1,5})([Mm])/u.exec(text);
10
+ if (match) {
11
+ const [, button, col, row, action] = match;
12
+ return {
13
+ event: {
14
+ button: Number(button),
15
+ col: Number(col),
16
+ row: Number(row),
17
+ release: action === "m",
18
+ },
19
+ length: match[0].length,
20
+ };
21
+ }
22
+ return bytes.length < 32 && /^(?:\x1b|\x1b\[|\x1b\[<[\d;]*)$/u.test(text)
23
+ ? "incomplete"
24
+ : undefined;
25
+ }
26
+ /** Recognize the menu prefix, bracketed paste, and the outer terminal's SGR mouse reports. */
27
+ export class InputRouter {
28
+ #paste = false;
29
+ #tail = Buffer.alloc(0);
30
+ #prefix;
31
+ constructor(prefix) {
32
+ this.#prefix = prefix.charCodeAt(prefix.length - 1) - 96;
33
+ }
34
+ get hasPending() {
35
+ return this.#tail.length > 0;
36
+ }
37
+ takePending() {
38
+ const result = this.#tail;
39
+ this.#tail = Buffer.alloc(0);
40
+ return result;
41
+ }
42
+ *route(chunk) {
43
+ const tail = this.takePending();
44
+ const input = tail.length > 0 ? Buffer.concat([tail, chunk]) : chunk;
45
+ let start = 0;
46
+ for (let index = 0; index < input.length; index++) {
47
+ const byte = input[index];
48
+ let event;
49
+ let length = 1;
50
+ let incomplete = false;
51
+ if (byte === this.#prefix && !this.#paste) {
52
+ event = { type: "prefix" };
53
+ }
54
+ else if (byte === 0x1b) {
55
+ const remainder = input.subarray(index);
56
+ const marker = this.#paste ? pasteEnd : pasteStart;
57
+ const candidate = remainder.subarray(0, marker.length);
58
+ if (marker.subarray(0, candidate.length).equals(candidate)) {
59
+ if (candidate.length < marker.length) {
60
+ incomplete = true;
61
+ }
62
+ else {
63
+ this.#paste = !this.#paste;
64
+ event = { type: this.#paste ? "paste-start" : "paste-end" };
65
+ length = marker.length;
66
+ }
67
+ }
68
+ else if (!this.#paste) {
69
+ const mouse = mouseReport(remainder);
70
+ if (mouse === "incomplete")
71
+ incomplete = true;
72
+ else if (mouse) {
73
+ event = { type: "mouse", ...mouse.event };
74
+ length = mouse.length;
75
+ }
76
+ }
77
+ }
78
+ if (!event && !incomplete)
79
+ continue;
80
+ if (index > start)
81
+ yield { type: "bytes", bytes: input.subarray(start, index) };
82
+ if (incomplete) {
83
+ this.#tail = Buffer.from(input.subarray(index));
84
+ return;
85
+ }
86
+ if (event)
87
+ yield event;
88
+ index += length - 1;
89
+ start = index + 1;
90
+ }
91
+ if (start < input.length)
92
+ yield { type: "bytes", bytes: input.subarray(start) };
93
+ }
94
+ }