grayling 0.0.0-stage → 0.1.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.
- package/LICENSE +661 -0
- package/README.md +268 -2
- package/dist/index.d.ts +290 -0
- package/dist/index.js +50 -0
- package/dist/node/archive.d.ts +4 -0
- package/dist/node/archive.js +115 -0
- package/dist/node/client.d.ts +188 -0
- package/dist/node/client.js +669 -0
- package/dist/node/connection.d.ts +56 -0
- package/dist/node/connection.js +240 -0
- package/dist/node/errors.d.ts +14 -0
- package/dist/node/errors.js +13 -0
- package/dist/node/handler.d.ts +56 -0
- package/dist/node/handler.js +208 -0
- package/dist/node/index.d.ts +15 -0
- package/dist/node/index.js +14 -0
- package/dist/node/paths.d.ts +51 -0
- package/dist/node/paths.js +115 -0
- package/dist/node/program.d.ts +74 -0
- package/dist/node/program.js +385 -0
- package/dist/node/state.d.ts +7 -0
- package/dist/node/state.js +12 -0
- package/dist/node/suggest.d.ts +13 -0
- package/dist/node/suggest.js +87 -0
- package/dist/node/types.d.ts +142 -0
- package/dist/node/types.js +13 -0
- package/dist/node/version.d.ts +10 -0
- package/dist/node/version.js +50 -0
- package/dist/node/wire.d.ts +32 -0
- package/dist/node/wire.js +44 -0
- package/dist/react/index.d.ts +121 -0
- package/dist/react/index.js +205 -0
- package/dist/web/announce.d.ts +51 -0
- package/dist/web/announce.js +141 -0
- package/dist/web/attach.d.ts +77 -0
- package/dist/web/attach.js +89 -0
- package/dist/web/box.d.ts +57 -0
- package/dist/web/box.js +150 -0
- package/dist/web/dom.d.ts +80 -0
- package/dist/web/dom.js +265 -0
- package/dist/web/index.d.ts +8 -0
- package/dist/web/index.js +8 -0
- package/dist/web/logic.d.ts +308 -0
- package/dist/web/logic.js +467 -0
- package/dist/web/overlay.d.ts +56 -0
- package/dist/web/overlay.js +211 -0
- package/dist/web/style.css +193 -0
- package/dist/web/suggester.d.ts +189 -0
- package/dist/web/suggester.js +696 -0
- package/dist/web/ui.d.ts +65 -0
- package/dist/web/ui.js +32 -0
- package/dist/web/usage.d.ts +39 -0
- package/dist/web/usage.js +84 -0
- package/package.json +89 -4
- package/program.json +35 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where things are: the data and cache folders and the engine host's socket (docs/protocol.md, "Where"). The same rules as
|
|
3
|
+
* crates/grayling-protocol/src/paths.rs, as plain functions of the system, the environment and a few facts about the computer,
|
|
4
|
+
* so that each system's rules are tested on any system.
|
|
5
|
+
*/
|
|
6
|
+
import { execFileSync } from 'node:child_process';
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { existsSync } from 'node:fs';
|
|
9
|
+
import { posix } from 'node:path';
|
|
10
|
+
import { GraylingError, messageOf } from './errors.js';
|
|
11
|
+
/** A Unix socket path of more than this many bytes does not fit in `sockaddr_un` everywhere. */
|
|
12
|
+
export const MAX_SOCKET_PATH = 100;
|
|
13
|
+
/** The first `digits` hex digits of the SHA-256 of `input`. */
|
|
14
|
+
export const sha256Hex = (input, digits) => createHash('sha256').update(input, 'utf8').digest('hex').slice(0, digits);
|
|
15
|
+
/** The pipe's name: `\\.\pipe\grayling-` and the first 16 hex digits of the SHA-256 of the SID, a line feed, and the data folder. */
|
|
16
|
+
export const pipeName = (sid, data) => `\\\\.\\pipe\\grayling-${sha256Hex(`${sid}\n${data}`, 16)}`;
|
|
17
|
+
/** `base` and `name`, as Rust's `Path::join` does for a relative name: a separator only when `base` does not end in one. */
|
|
18
|
+
function join(os, base, name) {
|
|
19
|
+
const win = os === 'windows';
|
|
20
|
+
const last = base[base.length - 1];
|
|
21
|
+
const sep = win ? '\\' : '/';
|
|
22
|
+
const has = last === '/' || (win && last === '\\');
|
|
23
|
+
return base + (has ? '' : sep) + (win ? name.replace(/\//g, '\\') : name);
|
|
24
|
+
}
|
|
25
|
+
/** The rules, for facts and an environment (`env`: a name's value, if set). Throws when there is no home folder to start from. */
|
|
26
|
+
export function resolvePaths(facts, env) {
|
|
27
|
+
const os = facts.os;
|
|
28
|
+
const get = (k) => {
|
|
29
|
+
const v = env(k);
|
|
30
|
+
return v ? v : undefined;
|
|
31
|
+
};
|
|
32
|
+
const home = () => {
|
|
33
|
+
const h = get(os === 'windows' ? 'USERPROFILE' : 'HOME');
|
|
34
|
+
if (!h)
|
|
35
|
+
throw new GraylingError('failed', "cannot tell where this person's home folder is (HOME is not set)");
|
|
36
|
+
return h;
|
|
37
|
+
};
|
|
38
|
+
const abs = (v) => (v && posix.isAbsolute(v) ? v : undefined);
|
|
39
|
+
const override = get('GRAYLING_HOME');
|
|
40
|
+
let data;
|
|
41
|
+
if (override)
|
|
42
|
+
data = override;
|
|
43
|
+
else if (os === 'linux') {
|
|
44
|
+
const x = abs(get('XDG_DATA_HOME'));
|
|
45
|
+
data = x ? join(os, x, 'grayling') : join(os, home(), '.local/share/grayling');
|
|
46
|
+
}
|
|
47
|
+
else if (os === 'macos')
|
|
48
|
+
data = join(os, home(), 'Library/Application Support/Grayling');
|
|
49
|
+
else {
|
|
50
|
+
// Not under AppData: a packaged (Store) app's writes there are redirected into its package (two data folders, two engines), and
|
|
51
|
+
// %LOCALAPPDATA%\Grayling is where the setup program installs. The person's own folder, like the other systems' dot folders.
|
|
52
|
+
data = join(os, home(), '.grayling');
|
|
53
|
+
}
|
|
54
|
+
let cache;
|
|
55
|
+
if (override || (facts.container && os !== 'windows'))
|
|
56
|
+
cache = join(os, data, 'cache');
|
|
57
|
+
else if (os === 'linux') {
|
|
58
|
+
const x = abs(get('XDG_CACHE_HOME'));
|
|
59
|
+
cache = x ? join(os, x, 'grayling') : join(os, home(), '.cache/grayling');
|
|
60
|
+
}
|
|
61
|
+
else if (os === 'macos')
|
|
62
|
+
cache = join(os, home(), 'Library/Caches/Grayling');
|
|
63
|
+
else
|
|
64
|
+
cache = join(os, data, 'cache');
|
|
65
|
+
let socket;
|
|
66
|
+
if (os === 'windows')
|
|
67
|
+
socket = { kind: 'pipe', name: pipeName(facts.user, data) };
|
|
68
|
+
else {
|
|
69
|
+
const runtime = os === 'linux' && !override ? abs(get('XDG_RUNTIME_DIR')) : undefined;
|
|
70
|
+
const path = runtime ? join(os, runtime, 'grayling/engine.sock') : join(os, data, 'run/engine.sock');
|
|
71
|
+
socket = {
|
|
72
|
+
kind: 'unix',
|
|
73
|
+
path: Buffer.byteLength(path) > MAX_SOCKET_PATH ? `/tmp/grayling-${facts.user}-${sha256Hex(data, 12)}/engine.sock` : path,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
data,
|
|
78
|
+
cache,
|
|
79
|
+
socket,
|
|
80
|
+
lock: join(os, data, 'engine.lock'),
|
|
81
|
+
info: join(os, data, 'engine.json'),
|
|
82
|
+
log: join(os, data, 'host.log'),
|
|
83
|
+
pids: join(os, data, 'pids.json'),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
let sid;
|
|
87
|
+
/** Windows' own `whoami.exe`, not the first `whoami` of the PATH (the one of Git's tools, which comes first in a Git Bash, takes other arguments). */
|
|
88
|
+
const systemWhoami = () => `${(process.env.SystemRoot || process.env.windir || 'C:\\Windows').replace(/[\\/]+$/, '')}\\System32\\whoami.exe`;
|
|
89
|
+
/** The user's SID (Windows), once: from `whoami /user /fo csv /nh`, which prints `"DOMAIN\name","S-1-5-21-…"`. */
|
|
90
|
+
export function windowsSid(run = () => execFileSync(systemWhoami(), ['/user', '/fo', 'csv', '/nh'], { encoding: 'utf8', windowsHide: true, timeout: 10_000 })) {
|
|
91
|
+
if (sid)
|
|
92
|
+
return sid;
|
|
93
|
+
let out;
|
|
94
|
+
try {
|
|
95
|
+
out = run();
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
throw new GraylingError('failed', `cannot tell who this person is (whoami: ${messageOf(e)})`, { cause: e });
|
|
99
|
+
}
|
|
100
|
+
const m = /"(S-\d+(?:-\d+)+)"/.exec(out);
|
|
101
|
+
if (!m)
|
|
102
|
+
throw new GraylingError('failed', `cannot read the user's SID from: ${out.trim()}`);
|
|
103
|
+
return (sid = m[1]);
|
|
104
|
+
}
|
|
105
|
+
export const currentOs = () => (process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : 'linux');
|
|
106
|
+
/** This computer's, this person's, from the environment: the data folder, the cache, the socket. */
|
|
107
|
+
export function paths(o = {}) {
|
|
108
|
+
const env = o.home ? { ...(o.env ?? process.env), GRAYLING_HOME: o.home } : (o.env ?? process.env);
|
|
109
|
+
const os = currentOs();
|
|
110
|
+
const user = os === 'windows' ? windowsSid() : String(process.getuid?.() ?? '');
|
|
111
|
+
const container = os !== 'windows' && existsSync('/.dockerenv');
|
|
112
|
+
// Windows names are not case sensitive.
|
|
113
|
+
const get = os === 'windows' ? (k) => env[Object.keys(env).find((x) => x.toUpperCase() === k) ?? k] : (k) => env[k];
|
|
114
|
+
return resolvePaths({ os, container, user }, get);
|
|
115
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { type PathsOptions } from './paths.js';
|
|
2
|
+
/** The systems a program is built for (Rust target triples). */
|
|
3
|
+
export declare const TARGETS: readonly ['x86_64-unknown-linux-gnu', 'aarch64-unknown-linux-gnu', 'aarch64-apple-darwin', 'x86_64-apple-darwin', 'x86_64-pc-windows-msvc', 'aarch64-pc-windows-msvc'];
|
|
4
|
+
export type Target = (typeof TARGETS)[number];
|
|
5
|
+
/** The npm package of each target (`optionalDependencies` of `grayling`, see packages/platforms). In a scope, where nobody else can make packages. */
|
|
6
|
+
export declare const PLATFORM_PACKAGES: Record<Target, {
|
|
7
|
+
name: string;
|
|
8
|
+
os: string;
|
|
9
|
+
cpu: string;
|
|
10
|
+
libc?: string;
|
|
11
|
+
}>;
|
|
12
|
+
/** The target this process runs on, or null when no program is published for it (32-bit, musl, other systems). */
|
|
13
|
+
export declare function currentTarget(platform?: string, arch?: string, onMusl?: boolean): Target | null;
|
|
14
|
+
export interface FindProgramOptions extends PathsOptions {
|
|
15
|
+
/** A path of one's own (it is used when it exists). */
|
|
16
|
+
program?: string;
|
|
17
|
+
/** The app's folder, to look for the platform package from (default: the working folder). */
|
|
18
|
+
appDir?: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The `grayling` program to start: `program`, `GRAYLING_BIN`, the platform package (`@algoprog/grayling-<platform>-<arch>`, looked for from
|
|
22
|
+
* this module and from the app's folder), `<data>/bin/<version>/grayling[.exe]` (what `installProgram` makes). Null when none is
|
|
23
|
+
* there. Each is used only when the file exists.
|
|
24
|
+
*/
|
|
25
|
+
export declare function findProgram(o?: FindProgramOptions): string | null;
|
|
26
|
+
export interface StartableOptions extends PathsOptions {
|
|
27
|
+
/** Another system than this one (tests). */
|
|
28
|
+
platform?: string;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The program to start the engine host with. On Windows a running program locks its file, and a program started from
|
|
32
|
+
* `node_modules` would lock that folder (`npm install`, and an app's own installer, fail while the host runs): the program of a
|
|
33
|
+
* package is copied to `<data>\bin\<version>\grayling.exe` first (a temporary file, then renamed; used as it is when its size and
|
|
34
|
+
* SHA-256 are the same; a copy that cannot be replaced because it runs is fine when it is the same), and that copy is started.
|
|
35
|
+
* The folders of older versions there are removed when nothing holds them. Anywhere else, and for a program that is not in a
|
|
36
|
+
* package (`GRAYLING_BIN`, one's own, `installProgram`'s), it is the path given. `findProgram()` still says where the package's own is.
|
|
37
|
+
*/
|
|
38
|
+
export declare function startableProgram(program: string, o?: StartableOptions): Promise<string>;
|
|
39
|
+
/** The version a program says it is (`grayling version`), once per path; null when it does not say. */
|
|
40
|
+
export declare function programVersion(program: string, env?: NodeJS.ProcessEnv): string | null;
|
|
41
|
+
/** `program.json`, made at release time (packages/platforms/scripts/platform-packages.mjs): what to download for each target. */
|
|
42
|
+
export interface ProgramManifest {
|
|
43
|
+
version: string;
|
|
44
|
+
targets: Partial<Record<Target, {
|
|
45
|
+
file: string;
|
|
46
|
+
size: number;
|
|
47
|
+
sha256: string;
|
|
48
|
+
}>>;
|
|
49
|
+
}
|
|
50
|
+
/** The `program.json` that ships in this package, or null when there is none (a development copy). */
|
|
51
|
+
export declare function readManifest(): ProgramManifest | null;
|
|
52
|
+
export interface InstallProgress {
|
|
53
|
+
phase: 'download' | 'check' | 'unpack';
|
|
54
|
+
/** Bytes of the archive downloaded so far, and in all. */
|
|
55
|
+
received: number;
|
|
56
|
+
total: number;
|
|
57
|
+
}
|
|
58
|
+
export interface InstallOptions extends FindProgramOptions {
|
|
59
|
+
signal?: AbortSignal;
|
|
60
|
+
progress?: (p: InstallProgress) => void;
|
|
61
|
+
/** Where the release files are (default: the GitHub release of this version). For tests and mirrors. */
|
|
62
|
+
baseUrl?: string;
|
|
63
|
+
/** Another target than this system's (tests). */
|
|
64
|
+
target?: Target;
|
|
65
|
+
/** What to download, when the app has it from somewhere else than the package's own `program.json` (tests). */
|
|
66
|
+
manifest?: ProgramManifest | null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Downloads the `grayling` program for this version and this system from the GitHub release, checks its size and SHA-256 against
|
|
70
|
+
* `program.json` (which ships in the package), and unpacks it into `<data>/bin/<version>/`: into a folder of its own first, then
|
|
71
|
+
* renamed, so that a program that is there is whole. A download that stopped is resumed. Returns the program's path (at once when
|
|
72
|
+
* it is there already).
|
|
73
|
+
*/
|
|
74
|
+
export declare function installProgram(o?: InstallOptions): Promise<string>;
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
/** Finding the `grayling` program, and downloading it when it is not there. */
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
4
|
+
import { accessSync, chmodSync, constants, createReadStream, readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { copyFile, mkdir, open, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import { dirname, join, resolve, sep } from 'node:path';
|
|
8
|
+
import { fromTarGz, fromZip } from './archive.js';
|
|
9
|
+
import { hostEnv } from './connection.js';
|
|
10
|
+
import { GraylingError, messageOf } from './errors.js';
|
|
11
|
+
import { paths } from './paths.js';
|
|
12
|
+
import { packageRoot, packageVersion } from './version.js';
|
|
13
|
+
/** The systems a program is built for (Rust target triples). */
|
|
14
|
+
export const TARGETS = [
|
|
15
|
+
'x86_64-unknown-linux-gnu',
|
|
16
|
+
'aarch64-unknown-linux-gnu',
|
|
17
|
+
'aarch64-apple-darwin',
|
|
18
|
+
'x86_64-apple-darwin',
|
|
19
|
+
'x86_64-pc-windows-msvc',
|
|
20
|
+
'aarch64-pc-windows-msvc',
|
|
21
|
+
];
|
|
22
|
+
/** The npm package of each target (`optionalDependencies` of `grayling`, see packages/platforms). In a scope, where nobody else can make packages. */
|
|
23
|
+
export const PLATFORM_PACKAGES = {
|
|
24
|
+
'x86_64-unknown-linux-gnu': { name: '@algoprog/grayling-linux-x64', os: 'linux', cpu: 'x64', libc: 'glibc' },
|
|
25
|
+
'aarch64-unknown-linux-gnu': { name: '@algoprog/grayling-linux-arm64', os: 'linux', cpu: 'arm64', libc: 'glibc' },
|
|
26
|
+
'aarch64-apple-darwin': { name: '@algoprog/grayling-darwin-arm64', os: 'darwin', cpu: 'arm64' },
|
|
27
|
+
'x86_64-apple-darwin': { name: '@algoprog/grayling-darwin-x64', os: 'darwin', cpu: 'x64' },
|
|
28
|
+
'x86_64-pc-windows-msvc': { name: '@algoprog/grayling-win32-x64', os: 'win32', cpu: 'x64' },
|
|
29
|
+
'aarch64-pc-windows-msvc': { name: '@algoprog/grayling-win32-arm64', os: 'win32', cpu: 'arm64' },
|
|
30
|
+
};
|
|
31
|
+
let musl;
|
|
32
|
+
/** Whether this Linux uses musl (Alpine): the report of Node says which C library it runs on. */
|
|
33
|
+
function isMusl() {
|
|
34
|
+
if (musl !== undefined)
|
|
35
|
+
return musl;
|
|
36
|
+
try {
|
|
37
|
+
const report = process.report?.getReport();
|
|
38
|
+
musl = !report?.header?.glibcVersionRuntime;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
musl = false;
|
|
42
|
+
}
|
|
43
|
+
return musl;
|
|
44
|
+
}
|
|
45
|
+
/** The target this process runs on, or null when no program is published for it (32-bit, musl, other systems). */
|
|
46
|
+
export function currentTarget(platform = process.platform, arch = process.arch, onMusl) {
|
|
47
|
+
if (platform === 'linux') {
|
|
48
|
+
if (onMusl ?? isMusl())
|
|
49
|
+
return null;
|
|
50
|
+
return arch === 'x64' ? 'x86_64-unknown-linux-gnu' : arch === 'arm64' ? 'aarch64-unknown-linux-gnu' : null;
|
|
51
|
+
}
|
|
52
|
+
if (platform === 'darwin')
|
|
53
|
+
return arch === 'arm64' ? 'aarch64-apple-darwin' : arch === 'x64' ? 'x86_64-apple-darwin' : null;
|
|
54
|
+
if (platform === 'win32')
|
|
55
|
+
return arch === 'x64' ? 'x86_64-pc-windows-msvc' : arch === 'arm64' ? 'aarch64-pc-windows-msvc' : null;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
const exeName = () => (process.platform === 'win32' ? 'grayling.exe' : 'grayling');
|
|
59
|
+
/** Whether `file` is a program that can be run (on Unix: made executable when it is not, as an npm install may leave it). */
|
|
60
|
+
function runnable(file) {
|
|
61
|
+
try {
|
|
62
|
+
if (!statSync(file).isFile())
|
|
63
|
+
return false;
|
|
64
|
+
if (process.platform === 'win32')
|
|
65
|
+
return true;
|
|
66
|
+
try {
|
|
67
|
+
accessSync(file, constants.X_OK);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
chmodSync(file, 0o755);
|
|
71
|
+
accessSync(file, constants.X_OK);
|
|
72
|
+
}
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* The `grayling` program to start: `program`, `GRAYLING_BIN`, the platform package (`@algoprog/grayling-<platform>-<arch>`, looked for from
|
|
81
|
+
* this module and from the app's folder), `<data>/bin/<version>/grayling[.exe]` (what `installProgram` makes). Null when none is
|
|
82
|
+
* there. Each is used only when the file exists.
|
|
83
|
+
*/
|
|
84
|
+
export function findProgram(o = {}) {
|
|
85
|
+
const env = o.env ?? process.env;
|
|
86
|
+
for (const p of [o.program, env.GRAYLING_BIN])
|
|
87
|
+
if (p && runnable(p))
|
|
88
|
+
return p;
|
|
89
|
+
const target = currentTarget();
|
|
90
|
+
if (target) {
|
|
91
|
+
const pkg = PLATFORM_PACKAGES[target].name;
|
|
92
|
+
const from = [createRequire(import.meta.url), createRequire(join(o.appDir ?? process.cwd(), 'noop.js'))];
|
|
93
|
+
for (const req of from) {
|
|
94
|
+
try {
|
|
95
|
+
const file = join(dirname(req.resolve(`${pkg}/package.json`)), 'bin', exeName());
|
|
96
|
+
if (runnable(file))
|
|
97
|
+
return file;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// not installed there
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
const file = join(paths(o).data, 'bin', packageVersion(), exeName());
|
|
106
|
+
if (runnable(file))
|
|
107
|
+
return file;
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// no data folder to look in
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
/** Whether `file` is inside a package folder (a `node_modules` folder somewhere above it). */
|
|
115
|
+
function inPackage(file) {
|
|
116
|
+
return resolve(file).split(sep).includes('node_modules');
|
|
117
|
+
}
|
|
118
|
+
const hashes = new Map();
|
|
119
|
+
/** The SHA-256 of a file, kept for as long as its size and modification time are the same. */
|
|
120
|
+
async function sha256Cached(file) {
|
|
121
|
+
const st = await stat(file);
|
|
122
|
+
const key = `${file}\n${st.size}\n${st.mtimeMs}`;
|
|
123
|
+
let h = hashes.get(key);
|
|
124
|
+
if (!h) {
|
|
125
|
+
h = await sha256Of(file);
|
|
126
|
+
hashes.set(key, h);
|
|
127
|
+
}
|
|
128
|
+
return h;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The program to start the engine host with. On Windows a running program locks its file, and a program started from
|
|
132
|
+
* `node_modules` would lock that folder (`npm install`, and an app's own installer, fail while the host runs): the program of a
|
|
133
|
+
* package is copied to `<data>\bin\<version>\grayling.exe` first (a temporary file, then renamed; used as it is when its size and
|
|
134
|
+
* SHA-256 are the same; a copy that cannot be replaced because it runs is fine when it is the same), and that copy is started.
|
|
135
|
+
* The folders of older versions there are removed when nothing holds them. Anywhere else, and for a program that is not in a
|
|
136
|
+
* package (`GRAYLING_BIN`, one's own, `installProgram`'s), it is the path given. `findProgram()` still says where the package's own is.
|
|
137
|
+
*/
|
|
138
|
+
export async function startableProgram(program, o = {}) {
|
|
139
|
+
const platform = o.platform ?? process.platform;
|
|
140
|
+
if (platform !== 'win32' || !inPackage(program))
|
|
141
|
+
return program;
|
|
142
|
+
try {
|
|
143
|
+
const version = packageVersion();
|
|
144
|
+
const bin = join(paths(o).data, 'bin');
|
|
145
|
+
const dest = join(bin, version, 'grayling.exe');
|
|
146
|
+
const [size, hash] = [(await stat(program)).size, await sha256Cached(program)];
|
|
147
|
+
const same = async () => (await sizeOf(dest)) === size && (await sha256Of(dest)) === hash;
|
|
148
|
+
if (!(await same().catch(() => false))) {
|
|
149
|
+
await mkdir(join(bin, version), { recursive: true, mode: 0o700 });
|
|
150
|
+
const tmp = join(bin, version, `grayling.exe.${process.pid}-${randomBytes(4).toString('hex')}.tmp`);
|
|
151
|
+
try {
|
|
152
|
+
await copyFile(program, tmp);
|
|
153
|
+
try {
|
|
154
|
+
await rename(tmp, dest);
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
// The copy there runs (or another process just made it): fine when it is the same file; else the package's own is used.
|
|
158
|
+
if (!(await same().catch(() => false)))
|
|
159
|
+
return program;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
await rm(tmp, { force: true });
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
await removeOldVersions(bin, version);
|
|
167
|
+
return dest;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return program;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Removes the version folders of `<data>/bin` other than `keep` (one that holds a running program stays: it cannot be removed). */
|
|
174
|
+
async function removeOldVersions(bin, keep) {
|
|
175
|
+
for (const name of await readdir(bin).catch(() => [])) {
|
|
176
|
+
if (name === keep || name.startsWith('.') || !/^\d/.test(name) || name.endsWith('.tmp'))
|
|
177
|
+
continue;
|
|
178
|
+
await rm(join(bin, name), { recursive: true, force: true }).catch(() => undefined);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const versions = new Map();
|
|
182
|
+
/** The version a program says it is (`grayling version`), once per path; null when it does not say. */
|
|
183
|
+
export function programVersion(program, env = process.env) {
|
|
184
|
+
if (versions.has(program))
|
|
185
|
+
return versions.get(program) ?? null;
|
|
186
|
+
let v = null;
|
|
187
|
+
try {
|
|
188
|
+
const out = execFileSync(program, ['version'], { encoding: 'utf8', timeout: 10_000, windowsHide: true, env: hostEnv(env), stdio: ['ignore', 'pipe', 'ignore'] });
|
|
189
|
+
v = /grayling\s+(\S+)/.exec(out)?.[1] ?? null;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
v = null;
|
|
193
|
+
}
|
|
194
|
+
versions.set(program, v);
|
|
195
|
+
return v;
|
|
196
|
+
}
|
|
197
|
+
/** The `program.json` that ships in this package, or null when there is none (a development copy). */
|
|
198
|
+
export function readManifest() {
|
|
199
|
+
try {
|
|
200
|
+
return JSON.parse(readFileSync(join(packageRoot(), 'program.json'), 'utf8'));
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const sleep = (ms, signal) => new Promise((resolve) => {
|
|
207
|
+
const t = setTimeout(resolve, ms);
|
|
208
|
+
signal?.addEventListener('abort', () => (clearTimeout(t), resolve()), { once: true });
|
|
209
|
+
});
|
|
210
|
+
const sizeOf = (p) => stat(p).then((s) => s.size, () => 0);
|
|
211
|
+
function aborted(signal) {
|
|
212
|
+
return signal?.aborted ? new GraylingError('aborted', 'the download was cancelled') : null;
|
|
213
|
+
}
|
|
214
|
+
/** Downloads `url` into `part`, resuming what is there (a Range request), up to three tries. */
|
|
215
|
+
async function download(url, part, size, o) {
|
|
216
|
+
let lastError;
|
|
217
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
218
|
+
let have = await sizeOf(part);
|
|
219
|
+
if (have > size) {
|
|
220
|
+
await rm(part, { force: true });
|
|
221
|
+
have = 0;
|
|
222
|
+
}
|
|
223
|
+
if (have === size)
|
|
224
|
+
return;
|
|
225
|
+
try {
|
|
226
|
+
const res = await fetch(url, { headers: have ? { range: `bytes=${have}-` } : {}, signal: o.signal, redirect: 'follow' });
|
|
227
|
+
let append = have > 0;
|
|
228
|
+
if (res.status === 206) {
|
|
229
|
+
if (!res.headers.get('content-range')?.startsWith(`bytes ${have}-`))
|
|
230
|
+
append = false;
|
|
231
|
+
}
|
|
232
|
+
else if (res.status === 200)
|
|
233
|
+
append = false;
|
|
234
|
+
else if (res.status === 416) {
|
|
235
|
+
await rm(part, { force: true });
|
|
236
|
+
throw new GraylingError('download', `${url}: the server cannot resume the download (HTTP 416); starting again`);
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
throw new GraylingError('download', `${url}: HTTP ${res.status}`);
|
|
240
|
+
if (!res.body)
|
|
241
|
+
throw new GraylingError('download', `${url}: no body`);
|
|
242
|
+
let received = append ? have : 0;
|
|
243
|
+
const fh = await open(part, append ? 'a' : 'w', 0o600);
|
|
244
|
+
try {
|
|
245
|
+
for await (const chunk of res.body) {
|
|
246
|
+
await fh.write(chunk);
|
|
247
|
+
received += chunk.length;
|
|
248
|
+
o.progress?.({ phase: 'download', received, total: size });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
await fh.close();
|
|
253
|
+
}
|
|
254
|
+
if ((await sizeOf(part)) >= size)
|
|
255
|
+
return;
|
|
256
|
+
lastError = new GraylingError('download', `${url}: the connection ended after ${await sizeOf(part)} of ${size} bytes`);
|
|
257
|
+
}
|
|
258
|
+
catch (e) {
|
|
259
|
+
const a = aborted(o.signal);
|
|
260
|
+
if (a)
|
|
261
|
+
throw a;
|
|
262
|
+
lastError = e;
|
|
263
|
+
}
|
|
264
|
+
if (attempt < 3)
|
|
265
|
+
await sleep(attempt * 500, o.signal);
|
|
266
|
+
}
|
|
267
|
+
throw lastError instanceof GraylingError ? lastError : new GraylingError('download', `could not download ${url}: ${messageOf(lastError)}`, { cause: lastError });
|
|
268
|
+
}
|
|
269
|
+
async function sha256Of(file) {
|
|
270
|
+
const h = createHash('sha256');
|
|
271
|
+
for await (const c of createReadStream(file))
|
|
272
|
+
h.update(c);
|
|
273
|
+
return h.digest('hex');
|
|
274
|
+
}
|
|
275
|
+
/** Takes the lock of one install (a file made by the first to ask); one whose process is gone is taken over. */
|
|
276
|
+
async function lockInstall(file, ready, signal) {
|
|
277
|
+
for (;;) {
|
|
278
|
+
try {
|
|
279
|
+
const fh = await open(file, 'wx', 0o600);
|
|
280
|
+
await fh.writeFile(String(process.pid));
|
|
281
|
+
await fh.close();
|
|
282
|
+
return () => rm(file, { force: true });
|
|
283
|
+
}
|
|
284
|
+
catch (e) {
|
|
285
|
+
if (e.code !== 'EEXIST')
|
|
286
|
+
throw e;
|
|
287
|
+
}
|
|
288
|
+
if (ready())
|
|
289
|
+
return 'ready';
|
|
290
|
+
const pid = Number(await readFile(file, 'utf8').catch(() => ''));
|
|
291
|
+
let alive = true;
|
|
292
|
+
if (pid > 0) {
|
|
293
|
+
try {
|
|
294
|
+
process.kill(pid, 0);
|
|
295
|
+
}
|
|
296
|
+
catch (e) {
|
|
297
|
+
alive = e.code === 'EPERM';
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (!alive)
|
|
301
|
+
await rm(file, { force: true });
|
|
302
|
+
else
|
|
303
|
+
await sleep(300, signal);
|
|
304
|
+
const a = aborted(signal);
|
|
305
|
+
if (a)
|
|
306
|
+
throw a;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Downloads the `grayling` program for this version and this system from the GitHub release, checks its size and SHA-256 against
|
|
311
|
+
* `program.json` (which ships in the package), and unpacks it into `<data>/bin/<version>/`: into a folder of its own first, then
|
|
312
|
+
* renamed, so that a program that is there is whole. A download that stopped is resumed. Returns the program's path (at once when
|
|
313
|
+
* it is there already).
|
|
314
|
+
*/
|
|
315
|
+
export async function installProgram(o = {}) {
|
|
316
|
+
const version = packageVersion();
|
|
317
|
+
const exe = exeName();
|
|
318
|
+
const bin = join(paths(o).data, 'bin');
|
|
319
|
+
const final = join(bin, version, exe);
|
|
320
|
+
if (runnable(final))
|
|
321
|
+
return final;
|
|
322
|
+
const target = o.target ?? currentTarget();
|
|
323
|
+
if (!target) {
|
|
324
|
+
const system = `${process.platform} ${process.arch}${process.platform === 'linux' && isMusl() ? ' (musl)' : ''}`;
|
|
325
|
+
throw new GraylingError('unsupported', `No grayling program is published for ${system}; programs exist for ${TARGETS.join(', ')}. Build one with cargo (cargo build --release -p grayling-host) and set GRAYLING_BIN to it.`);
|
|
326
|
+
}
|
|
327
|
+
const manifest = o.manifest === undefined ? readManifest() : o.manifest;
|
|
328
|
+
if (!manifest) {
|
|
329
|
+
throw new GraylingError('no-manifest', `This copy of grayling has no program.json, so it does not know what to download (a development copy?). Install a release from npm, or set GRAYLING_BIN to a grayling program.`);
|
|
330
|
+
}
|
|
331
|
+
if (manifest.version !== version) {
|
|
332
|
+
throw new GraylingError('no-manifest', `program.json is for grayling ${manifest.version}, but this is ${version}. Reinstall the package.`);
|
|
333
|
+
}
|
|
334
|
+
const entry = manifest.targets[target];
|
|
335
|
+
if (!entry) {
|
|
336
|
+
throw new GraylingError('unsupported', `This release of grayling (${version}) has no program for ${target}; it has ${Object.keys(manifest.targets).join(', ') || 'none'}.`);
|
|
337
|
+
}
|
|
338
|
+
const url = `${(o.baseUrl ?? `https://github.com/algoprog/grayling/releases/download/v${version}`).replace(/\/+$/, '')}/${entry.file}`;
|
|
339
|
+
await mkdir(join(bin, '.download'), { recursive: true, mode: 0o700 });
|
|
340
|
+
const part = join(bin, '.download', `${entry.file}.part`);
|
|
341
|
+
const release = await lockInstall(join(bin, '.download', `${version}.lock`), () => runnable(final), o.signal);
|
|
342
|
+
if (release === 'ready')
|
|
343
|
+
return final;
|
|
344
|
+
try {
|
|
345
|
+
if (runnable(final))
|
|
346
|
+
return final;
|
|
347
|
+
await download(url, part, entry.size, o);
|
|
348
|
+
o.progress?.({ phase: 'check', received: entry.size, total: entry.size });
|
|
349
|
+
if ((await sizeOf(part)) !== entry.size || (await sha256Of(part)) !== entry.sha256.toLowerCase()) {
|
|
350
|
+
await rm(part, { force: true });
|
|
351
|
+
throw new GraylingError('checksum', `The download of ${url} is not the file that was published (its size or SHA-256 differ); it was thrown away. Try again.`);
|
|
352
|
+
}
|
|
353
|
+
o.progress?.({ phase: 'unpack', received: entry.size, total: entry.size });
|
|
354
|
+
const bytes = await readFile(part);
|
|
355
|
+
const program = entry.file.endsWith('.zip') ? fromZip(bytes, exe) : fromTarGz(bytes, exe);
|
|
356
|
+
const tmp = join(bin, `${version}.${process.pid}-${randomBytes(4).toString('hex')}.tmp`);
|
|
357
|
+
await mkdir(tmp, { recursive: true, mode: 0o700 });
|
|
358
|
+
try {
|
|
359
|
+
await writeFile(join(tmp, exe), program, { mode: 0o755 });
|
|
360
|
+
try {
|
|
361
|
+
await rename(tmp, join(bin, version));
|
|
362
|
+
}
|
|
363
|
+
catch (e) {
|
|
364
|
+
// Another process unpacked it first: its copy is whole (it was renamed into place).
|
|
365
|
+
if (!runnable(final)) {
|
|
366
|
+
// A folder of that name without the program (an earlier failure): replace it.
|
|
367
|
+
await rm(join(bin, version), { recursive: true, force: true });
|
|
368
|
+
await rename(tmp, join(bin, version)).catch(() => {
|
|
369
|
+
throw e;
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
finally {
|
|
375
|
+
await rm(tmp, { recursive: true, force: true });
|
|
376
|
+
}
|
|
377
|
+
await rm(part, { force: true });
|
|
378
|
+
if (!runnable(final))
|
|
379
|
+
throw new GraylingError('unpack', `the program was unpacked, but ${final} cannot be run`);
|
|
380
|
+
return final;
|
|
381
|
+
}
|
|
382
|
+
finally {
|
|
383
|
+
await release();
|
|
384
|
+
}
|
|
385
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SuggestSettings, SuggestState } from '../index.js';
|
|
2
|
+
import { type GraylingState } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* The `SuggestState` an app's settings page shows: the app's own settings with the host's laid over them (the host's are shared by
|
|
5
|
+
* every client), and the host's status (`off` while the app has suggestions turned off).
|
|
6
|
+
*/
|
|
7
|
+
export declare function suggestState(host: GraylingState, own: SuggestSettings): SuggestState;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { GRAYLING_SETTING_KEYS } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* The `SuggestState` an app's settings page shows: the app's own settings with the host's laid over them (the host's are shared by
|
|
4
|
+
* every client), and the host's status (`off` while the app has suggestions turned off).
|
|
5
|
+
*/
|
|
6
|
+
export function suggestState(host, own) {
|
|
7
|
+
const settings = { ...own, where: { ...own.where }, sources: { ...own.sources } };
|
|
8
|
+
for (const k of GRAYLING_SETTING_KEYS)
|
|
9
|
+
settings[k] = host.settings[k];
|
|
10
|
+
const { engine: _engine, ...status } = host.status;
|
|
11
|
+
return { settings, status: own.enabled ? status : { ...status, state: 'off', detail: undefined } };
|
|
12
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** `suggest`: the request to the wire, the answer back, and what an app's settings make of a request. */
|
|
2
|
+
import type { SuggestResponse, SuggestSettings } from '../index.js';
|
|
3
|
+
import type { GraylingRequestOptions, GraylingSuggestRequest, SuggestOutcome } from './types.js';
|
|
4
|
+
import { type Wire } from './wire.js';
|
|
5
|
+
/** The `suggest` request as it goes over the wire. `tab`: a newer request of the same tab drops the one before it. */
|
|
6
|
+
export declare function suggestToWire(req: GraylingSuggestRequest, tab?: string): Wire;
|
|
7
|
+
/** The host's answer (`{"none": why}` or an `Answer`) as the response a text box takes. */
|
|
8
|
+
export declare function outcomeFromWire(a: Wire, req: Pick<GraylingSuggestRequest, 'next'>): SuggestOutcome<SuggestResponse>;
|
|
9
|
+
/**
|
|
10
|
+
* What an app's own settings make of a request, as Hydor's service does: false when nothing is to be suggested (suggestions are
|
|
11
|
+
* off, or off where the request comes from, or the word inside a text / the fix alone is off), else the options of the request.
|
|
12
|
+
*/
|
|
13
|
+
export declare function optionsFor(s: SuggestSettings, req: Pick<GraylingSuggestRequest, 'surface' | 'want' | 'after' | 'session'>): GraylingRequestOptions | false;
|