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.
Files changed (55) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +268 -2
  3. package/dist/index.d.ts +290 -0
  4. package/dist/index.js +50 -0
  5. package/dist/node/archive.d.ts +4 -0
  6. package/dist/node/archive.js +115 -0
  7. package/dist/node/client.d.ts +188 -0
  8. package/dist/node/client.js +669 -0
  9. package/dist/node/connection.d.ts +56 -0
  10. package/dist/node/connection.js +240 -0
  11. package/dist/node/errors.d.ts +14 -0
  12. package/dist/node/errors.js +13 -0
  13. package/dist/node/handler.d.ts +56 -0
  14. package/dist/node/handler.js +208 -0
  15. package/dist/node/index.d.ts +15 -0
  16. package/dist/node/index.js +14 -0
  17. package/dist/node/paths.d.ts +51 -0
  18. package/dist/node/paths.js +115 -0
  19. package/dist/node/program.d.ts +74 -0
  20. package/dist/node/program.js +385 -0
  21. package/dist/node/state.d.ts +7 -0
  22. package/dist/node/state.js +12 -0
  23. package/dist/node/suggest.d.ts +13 -0
  24. package/dist/node/suggest.js +87 -0
  25. package/dist/node/types.d.ts +142 -0
  26. package/dist/node/types.js +13 -0
  27. package/dist/node/version.d.ts +10 -0
  28. package/dist/node/version.js +50 -0
  29. package/dist/node/wire.d.ts +32 -0
  30. package/dist/node/wire.js +44 -0
  31. package/dist/react/index.d.ts +121 -0
  32. package/dist/react/index.js +205 -0
  33. package/dist/web/announce.d.ts +51 -0
  34. package/dist/web/announce.js +141 -0
  35. package/dist/web/attach.d.ts +77 -0
  36. package/dist/web/attach.js +89 -0
  37. package/dist/web/box.d.ts +57 -0
  38. package/dist/web/box.js +150 -0
  39. package/dist/web/dom.d.ts +80 -0
  40. package/dist/web/dom.js +265 -0
  41. package/dist/web/index.d.ts +8 -0
  42. package/dist/web/index.js +8 -0
  43. package/dist/web/logic.d.ts +308 -0
  44. package/dist/web/logic.js +467 -0
  45. package/dist/web/overlay.d.ts +56 -0
  46. package/dist/web/overlay.js +211 -0
  47. package/dist/web/style.css +193 -0
  48. package/dist/web/suggester.d.ts +189 -0
  49. package/dist/web/suggester.js +696 -0
  50. package/dist/web/ui.d.ts +65 -0
  51. package/dist/web/ui.js +32 -0
  52. package/dist/web/usage.d.ts +39 -0
  53. package/dist/web/usage.js +84 -0
  54. package/package.json +89 -4
  55. package/program.json +35 -0
@@ -0,0 +1,56 @@
1
+ import { type Socket } from 'node:net';
2
+ import { GraylingError } from './errors.js';
3
+ import type { GraylingPaths } from './paths.js';
4
+ import type { Wire } from './wire.js';
5
+ /** The longest line, in bytes (without the line feed): docs/protocol.md. */
6
+ export declare const MAX_LINE: number;
7
+ export interface ConnHandlers {
8
+ /** `{"event": …}` lines. */
9
+ event(e: Wire): void;
10
+ /** Lines that were not JSON objects (counted, never shown). */
11
+ garbage?(): void;
12
+ }
13
+ export declare class Conn {
14
+ private readonly socket;
15
+ private readonly handlers;
16
+ /** Resolves when the connection has ended, whoever ended it. */
17
+ readonly closed: Promise<void>;
18
+ isClosed: boolean;
19
+ /** Why it ended. */
20
+ reason: string;
21
+ /** The host said `replaced`: it is about to close this connection. */
22
+ replaced: boolean;
23
+ private resolveClosed;
24
+ private pending;
25
+ private next;
26
+ private chunks;
27
+ private partial;
28
+ /** A line without an id that is an error (the host could not read a request): the handshake's. */
29
+ onNullError?: (e: GraylingError) => void;
30
+ constructor(socket: Socket, handlers: ConnHandlers);
31
+ private onData;
32
+ private line;
33
+ /** A request: its id (to cancel it) and its answer, which has the id and the fields of the host's answer. */
34
+ request(op: string, fields?: Wire, timeoutMs?: number): {
35
+ id: number;
36
+ promise: Promise<Wire>;
37
+ };
38
+ /** Gives up an answer that is no longer wanted: its promise is rejected as `aborted`, and the host is told to cancel. */
39
+ cancel(id: number): void;
40
+ private end;
41
+ close(): void;
42
+ }
43
+ /** Opens the socket (the host's, not yet said hello to). Rejects when nothing listens. */
44
+ export declare function openSocket(paths: GraylingPaths, handlers: ConnHandlers): Promise<Conn>;
45
+ /** The short environment a started host gets: what it needs to find its folders and the network, nothing else. */
46
+ export declare function hostEnv(env: NodeJS.ProcessEnv): Record<string, string>;
47
+ export interface Spawned {
48
+ /** The exit code once the program has ended (null: by a signal); undefined while it runs. */
49
+ exit: {
50
+ code: number | null;
51
+ } | undefined;
52
+ /** Why it could not be started at all. */
53
+ error: Error | undefined;
54
+ }
55
+ /** Starts `program serve` detached from this process (its own process group; Windows: no console), no stdio, a short environment. */
56
+ export declare function spawnHost(program: string, env: NodeJS.ProcessEnv, extraArgs?: string[]): Spawned;
@@ -0,0 +1,240 @@
1
+ /** One connection to the engine host: lines of JSON over a socket, requests answered by id, events passed on. */
2
+ import { spawn } from 'node:child_process';
3
+ import { connect as netConnect } from 'node:net';
4
+ import { GraylingError, messageOf } from './errors.js';
5
+ /** The longest line, in bytes (without the line feed): docs/protocol.md. */
6
+ export const MAX_LINE = 8 * 1024 * 1024;
7
+ export class Conn {
8
+ socket;
9
+ handlers;
10
+ /** Resolves when the connection has ended, whoever ended it. */
11
+ closed;
12
+ isClosed = false;
13
+ /** Why it ended. */
14
+ reason = '';
15
+ /** The host said `replaced`: it is about to close this connection. */
16
+ replaced = false;
17
+ resolveClosed;
18
+ pending = new Map();
19
+ next = 1;
20
+ chunks = [];
21
+ partial = 0;
22
+ /** A line without an id that is an error (the host could not read a request): the handshake's. */
23
+ onNullError;
24
+ constructor(socket, handlers) {
25
+ this.socket = socket;
26
+ this.handlers = handlers;
27
+ this.closed = new Promise((r) => (this.resolveClosed = r));
28
+ socket.setNoDelay(true);
29
+ socket.on('data', (c) => this.onData(c));
30
+ socket.on('error', (e) => this.end(`the connection failed: ${messageOf(e)}`));
31
+ socket.on('close', () => this.end('the engine host ended the connection'));
32
+ socket.on('end', () => this.end('the engine host ended the connection'));
33
+ if (socket.destroyed)
34
+ this.end('the connection failed');
35
+ }
36
+ onData(chunk) {
37
+ let start = 0;
38
+ for (;;) {
39
+ const nl = chunk.indexOf(10, start);
40
+ if (nl < 0) {
41
+ const rest = chunk.subarray(start);
42
+ this.partial += rest.length;
43
+ if (this.partial > MAX_LINE)
44
+ return this.end('the engine host sent a line longer than the protocol allows');
45
+ if (rest.length)
46
+ this.chunks.push(rest);
47
+ return;
48
+ }
49
+ const last = chunk.subarray(start, nl);
50
+ const line = this.chunks.length ? Buffer.concat([...this.chunks, last]) : last;
51
+ this.chunks = [];
52
+ this.partial = 0;
53
+ if (line.length > MAX_LINE)
54
+ return this.end('the engine host sent a line longer than the protocol allows');
55
+ this.line(line);
56
+ if (this.isClosed)
57
+ return;
58
+ start = nl + 1;
59
+ }
60
+ }
61
+ line(raw) {
62
+ if (raw.length === 0)
63
+ return;
64
+ let v;
65
+ try {
66
+ v = JSON.parse(raw.toString('utf8'));
67
+ }
68
+ catch {
69
+ this.handlers.garbage?.();
70
+ return;
71
+ }
72
+ if (!v || typeof v !== 'object' || Array.isArray(v))
73
+ return void this.handlers.garbage?.();
74
+ const m = v;
75
+ if (typeof m.event === 'string') {
76
+ try {
77
+ this.handlers.event(m);
78
+ }
79
+ catch {
80
+ // a listener's failure is not the connection's
81
+ }
82
+ return;
83
+ }
84
+ const id = m.id;
85
+ if ((typeof id !== 'number' && typeof id !== 'string') || !this.pending.has(Number(id))) {
86
+ if (id == null && m.error && typeof m.error === 'object')
87
+ this.onNullError?.(errorOf(m));
88
+ return;
89
+ }
90
+ const p = this.pending.get(Number(id));
91
+ this.pending.delete(Number(id));
92
+ if (p.timer)
93
+ clearTimeout(p.timer);
94
+ if (m.error && typeof m.error === 'object') {
95
+ const e = errorOf(m);
96
+ if (e.code === 'replaced')
97
+ this.replaced = true;
98
+ p.reject(e);
99
+ }
100
+ else
101
+ p.resolve(m);
102
+ }
103
+ /** A request: its id (to cancel it) and its answer, which has the id and the fields of the host's answer. */
104
+ request(op, fields = {}, timeoutMs = 30_000) {
105
+ if (this.isClosed)
106
+ return { id: 0, promise: Promise.reject(new GraylingError('closed', this.reason || 'the connection has ended')) };
107
+ const id = this.next++;
108
+ const line = JSON.stringify({ ...fields, id, op }) + '\n';
109
+ if (Buffer.byteLength(line) > MAX_LINE + 1) {
110
+ return { id, promise: Promise.reject(new GraylingError('bad', `the request is longer than the protocol allows (${MAX_LINE} bytes)`)) };
111
+ }
112
+ const promise = new Promise((resolve, reject) => {
113
+ const timer = setTimeout(() => {
114
+ this.pending.delete(id);
115
+ reject(new GraylingError('timeout', `the engine host did not answer ${op} in time`));
116
+ }, timeoutMs);
117
+ this.pending.set(id, { resolve, reject, timer });
118
+ });
119
+ try {
120
+ this.socket.write(line, (err) => {
121
+ if (err)
122
+ this.end(`the connection failed: ${err.message}`);
123
+ });
124
+ }
125
+ catch (e) {
126
+ this.end(`the connection failed: ${messageOf(e)}`);
127
+ }
128
+ return { id, promise };
129
+ }
130
+ /** Gives up an answer that is no longer wanted: its promise is rejected as `aborted`, and the host is told to cancel. */
131
+ cancel(id) {
132
+ const p = this.pending.get(id);
133
+ if (!p)
134
+ return;
135
+ this.pending.delete(id);
136
+ if (p.timer)
137
+ clearTimeout(p.timer);
138
+ p.reject(new GraylingError('aborted', 'the request was cancelled'));
139
+ if (!this.isClosed)
140
+ this.request('cancel', { target: id }, 5_000).promise.catch(() => { });
141
+ }
142
+ end(reason) {
143
+ if (this.isClosed)
144
+ return;
145
+ this.isClosed = true;
146
+ this.reason = reason;
147
+ this.socket.destroy();
148
+ const all = [...this.pending.values()];
149
+ this.pending.clear();
150
+ for (const p of all) {
151
+ if (p.timer)
152
+ clearTimeout(p.timer);
153
+ p.reject(new GraylingError('closed', reason));
154
+ }
155
+ this.resolveClosed();
156
+ }
157
+ close() {
158
+ this.end('the connection was closed');
159
+ }
160
+ }
161
+ function errorOf(m) {
162
+ const e = m.error;
163
+ const code = typeof e.code === 'string' ? e.code : 'failed';
164
+ let message = typeof e.message === 'string' ? e.message : JSON.stringify(e);
165
+ const err = new GraylingError(code, message);
166
+ if (code === 'protocol' && Array.isArray(m.protocols)) {
167
+ err.protocols = m.protocols.filter((p) => typeof p === 'number');
168
+ message = `${message} (the host speaks protocols ${err.protocols.join(', ')})`;
169
+ err.message = message;
170
+ }
171
+ return err;
172
+ }
173
+ /** Opens the socket (the host's, not yet said hello to). Rejects when nothing listens. */
174
+ export function openSocket(paths, handlers) {
175
+ const path = paths.socket.kind === 'unix' ? paths.socket.path : paths.socket.name;
176
+ return new Promise((resolve, reject) => {
177
+ const s = netConnect({ path });
178
+ const fail = (e) => {
179
+ s.destroy();
180
+ reject(e);
181
+ };
182
+ s.once('error', fail);
183
+ s.once('connect', () => {
184
+ s.off('error', fail);
185
+ resolve(new Conn(s, handlers));
186
+ });
187
+ });
188
+ }
189
+ // ---- starting the host ----------------------------------------------------------------------------------------------------
190
+ /** The environment names the program is given (the others are left out), besides the prefixes below. */
191
+ const KEEP_ENV = new Set([
192
+ 'PATH',
193
+ 'HOME',
194
+ 'USER',
195
+ 'LOGNAME',
196
+ 'LANG',
197
+ 'LC_ALL',
198
+ 'TMPDIR',
199
+ 'USERPROFILE',
200
+ 'LOCALAPPDATA',
201
+ 'APPDATA',
202
+ 'PROGRAMDATA',
203
+ 'SYSTEMROOT',
204
+ 'SYSTEMDRIVE',
205
+ 'WINDIR',
206
+ 'COMSPEC',
207
+ 'PATHEXT',
208
+ 'TEMP',
209
+ 'TMP',
210
+ 'CUDA_VISIBLE_DEVICES',
211
+ 'HTTPS_PROXY',
212
+ 'HTTP_PROXY',
213
+ 'ALL_PROXY',
214
+ 'NO_PROXY',
215
+ 'SSL_CERT_FILE',
216
+ 'SSL_CERT_DIR',
217
+ 'HF_ENDPOINT',
218
+ ]);
219
+ const KEEP_PREFIX = ['XDG_', 'LC_', 'GRAYLING'];
220
+ /** The short environment a started host gets: what it needs to find its folders and the network, nothing else. */
221
+ export function hostEnv(env) {
222
+ const out = {};
223
+ for (const [k, v] of Object.entries(env)) {
224
+ if (v === undefined)
225
+ continue;
226
+ const name = k.toUpperCase();
227
+ if (KEEP_ENV.has(name) || KEEP_PREFIX.some((p) => name.startsWith(p)))
228
+ out[k] = v;
229
+ }
230
+ return out;
231
+ }
232
+ /** Starts `program serve` detached from this process (its own process group; Windows: no console), no stdio, a short environment. */
233
+ export function spawnHost(program, env, extraArgs = []) {
234
+ const state = { exit: undefined, error: undefined };
235
+ const child = spawn(program, ['serve', ...extraArgs], { detached: true, stdio: 'ignore', windowsHide: true, env: hostEnv(env) });
236
+ child.once('error', (e) => (state.error = e));
237
+ child.once('exit', (code) => (state.exit = { code }));
238
+ child.unref();
239
+ return state;
240
+ }
@@ -0,0 +1,14 @@
1
+ /** The codes of the errors the engine host answers with (docs/protocol.md), and the ones this client adds. */
2
+ export type GraylingErrorCode = 'op' | 'bad' | 'protocol' | 'replaced' | 'busy' | 'cannot' | 'failed' | 'hello' | 'unavailable' | 'closed' | 'timeout' | 'not-running' | 'no-program' | 'start-failed' | 'unsupported' | 'no-manifest' | 'download' | 'checksum' | 'unpack' | 'aborted';
3
+ /** What goes wrong when talking to the engine host: `code` says what, `message` says it for a person. */
4
+ export declare class GraylingError extends Error {
5
+ readonly name = "GraylingError";
6
+ readonly code: GraylingErrorCode | (string & {});
7
+ /** For the error `protocol`: the protocols the host speaks. */
8
+ protocols?: number[];
9
+ constructor(code: GraylingError['code'], message: string, options?: {
10
+ cause?: unknown;
11
+ });
12
+ }
13
+ /** The message of anything thrown. */
14
+ export declare const messageOf: (e: unknown) => string;
@@ -0,0 +1,13 @@
1
+ /** What goes wrong when talking to the engine host: `code` says what, `message` says it for a person. */
2
+ export class GraylingError extends Error {
3
+ name = 'GraylingError';
4
+ code;
5
+ /** For the error `protocol`: the protocols the host speaks. */
6
+ protocols;
7
+ constructor(code, message, options) {
8
+ super(message, options);
9
+ this.code = code;
10
+ }
11
+ }
12
+ /** The message of anything thrown. */
13
+ export const messageOf = (e) => (e instanceof Error ? e.message : String(e));
@@ -0,0 +1,56 @@
1
+ /**
2
+ * A small `(req, res)` function for `node:http` and frameworks: it takes the POST of a text box (`attach(textarea, { url })`),
3
+ * asks the engine host and answers 200 with the response or 204 with nothing. When the connection closes before the answer, the
4
+ * suggestion is cancelled on the host.
5
+ */
6
+ import type { IncomingMessage, ServerResponse } from 'node:http';
7
+ import type { SuggestRequest, SuggestResponse, SuggestSettings } from '../index.js';
8
+ import type { GraylingRequestOptions, GraylingSuggestRequest } from './types.js';
9
+ /** What a request is refused with: an HTTP status and a message for a person. */
10
+ export declare class RequestError extends Error {
11
+ readonly status: number;
12
+ readonly name = "RequestError";
13
+ constructor(status: number, message: string);
14
+ }
15
+ /** A request's body, checked: a text of a few thousand characters at most per field (the last ones; the first of `after`). */
16
+ export declare function cleanRequest(body: unknown): SuggestRequest;
17
+ /** What the handler asks for suggestions: a `Grayling`, or anything with its `suggest`. */
18
+ export interface SuggestSource {
19
+ suggest(req: GraylingSuggestRequest, o?: {
20
+ signal?: AbortSignal;
21
+ tab?: string;
22
+ }): Promise<SuggestResponse | null>;
23
+ }
24
+ export interface HandlerOptions {
25
+ /**
26
+ * The app's own settings (`enabled`, `where`, `precision`, …), read for every request (give a function when they can change):
27
+ * they decide whether to suggest at all and the options each request goes with (`optionsFor`).
28
+ */
29
+ settings?: SuggestSettings | (() => SuggestSettings);
30
+ /**
31
+ * Lower level than `settings`: the options of a request, or false for nothing (204). Runs after `settings`, and may be async, so
32
+ * that it can look at who asks.
33
+ */
34
+ options?: (req: SuggestRequest, http: IncomingMessage) => GraylingRequestOptions | false | undefined | Promise<GraylingRequestOptions | false | undefined>;
35
+ /** The most bytes of a body: 256 KB. */
36
+ maxBytes?: number;
37
+ /**
38
+ * Only a page of the same origin may ask (true, the default): a request with an `Origin` or `Sec-Fetch-Site` of another site is
39
+ * refused with 403, and so is one that is not `application/json` (which a page of another site cannot send without asking first).
40
+ * false: no such check (the server checks who asks in some other way).
41
+ */
42
+ sameOrigin?: boolean;
43
+ /**
44
+ * The `Host` values the server answers to, such as `['localhost:4775']`. A server that listens on a local address should give
45
+ * them: a page of another site can be made to point at it by name (DNS rebinding), and it then passes the same-origin check.
46
+ */
47
+ allowedHosts?: string[];
48
+ /** Other origins that may ask, such as `['https://app.example.com']`: they are answered with the CORS headers. */
49
+ origins?: string[];
50
+ }
51
+ /**
52
+ * `(req, res) => Promise<void>` for a POST route: the body is a `SuggestRequest` (checked by `cleanRequest`), the answer 200 with a
53
+ * `SuggestResponse`, or 204 when there is none. With Express: `app.post('/api/suggest', express.json(), handler(g))`; with Fastify:
54
+ * `handler(g)(request.raw, reply.raw, request.body)` and `reply.hijack()`. It never throws.
55
+ */
56
+ export declare function handler(source: SuggestSource, o?: HandlerOptions): (req: IncomingMessage, res: ServerResponse, body?: unknown) => Promise<void>;
@@ -0,0 +1,208 @@
1
+ import { GraylingError } from './errors.js';
2
+ import { optionsFor } from './suggest.js';
3
+ /** What a request is refused with: an HTTP status and a message for a person. */
4
+ export class RequestError extends Error {
5
+ status;
6
+ name = 'RequestError';
7
+ constructor(status, message) {
8
+ super(message);
9
+ this.status = status;
10
+ }
11
+ }
12
+ const SURFACES = ['chat', 'doc', 'text'];
13
+ /** The most characters of each text field kept (the text box sends 2,000). */
14
+ const LIMIT = 4000;
15
+ /** The text after the caret: the box sends 300 characters; this keeps the first 600 of what is sent. */
16
+ const AFTER_MAX = 600;
17
+ /** A request's body, checked: a text of a few thousand characters at most per field (the last ones; the first of `after`). */
18
+ export function cleanRequest(body) {
19
+ const b = body && typeof body === 'object' && !Array.isArray(body) ? body : null;
20
+ if (!b)
21
+ throw new RequestError(400, 'Send the request as an object');
22
+ if (typeof b.surface !== 'string' || !SURFACES.includes(b.surface))
23
+ throw new RequestError(400, 'surface: chat, doc or text');
24
+ if (typeof b.text !== 'string')
25
+ throw new RequestError(400, 'text: the text before the caret');
26
+ const opt = (k, max = LIMIT) => {
27
+ const v = b[k];
28
+ if (v == null)
29
+ return undefined;
30
+ if (typeof v !== 'string')
31
+ throw new RequestError(400, `${k}: text`);
32
+ return v.length > max ? v.slice(-max) : v;
33
+ };
34
+ const id = (k) => {
35
+ const v = b[k];
36
+ if (v == null || v === '')
37
+ return undefined;
38
+ if (typeof v !== 'string' || v.length > 200)
39
+ throw new RequestError(400, `${k}: a short text`);
40
+ return v;
41
+ };
42
+ const req = { surface: b.surface, text: b.text.length > LIMIT ? b.text.slice(-LIMIT) : b.text };
43
+ const reply = opt('reply');
44
+ const prev = opt('prev');
45
+ const doc = opt('doc');
46
+ const session = id('session');
47
+ const client = id('client');
48
+ const after = b.after;
49
+ if (after != null) {
50
+ if (typeof after !== 'string')
51
+ throw new RequestError(400, 'after: text');
52
+ if (after)
53
+ req.after = after.length > AFTER_MAX ? after.slice(0, AFTER_MAX) : after;
54
+ }
55
+ if (b.apart != null) {
56
+ if (typeof b.apart !== 'boolean')
57
+ throw new RequestError(400, 'apart: true or false');
58
+ if (b.apart)
59
+ req.apart = true;
60
+ }
61
+ if (b.want != null) {
62
+ if (b.want !== 'all' && b.want !== 'fix')
63
+ throw new RequestError(400, 'want: all or fix');
64
+ if (b.want === 'fix')
65
+ req.want = 'fix';
66
+ }
67
+ if (reply)
68
+ req.reply = reply;
69
+ if (prev)
70
+ req.prev = prev;
71
+ if (doc)
72
+ req.doc = doc;
73
+ if (session)
74
+ req.session = session;
75
+ if (client)
76
+ req.client = client;
77
+ return req;
78
+ }
79
+ const json = (res, status, body) => {
80
+ const text = JSON.stringify(body);
81
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(text), 'cache-control': 'no-store' });
82
+ res.end(text);
83
+ };
84
+ const none = (res) => {
85
+ res.writeHead(204, { 'cache-control': 'no-store' });
86
+ res.end();
87
+ };
88
+ /** The body: what a framework has parsed already (`req.body`, or the third argument), or the stream read up to `max` bytes. */
89
+ async function readBody(req, given, max) {
90
+ const parsed = given !== undefined ? given : req.body;
91
+ if (parsed !== undefined) {
92
+ if (typeof parsed === 'string' || Buffer.isBuffer(parsed))
93
+ return parseJson(parsed.toString('utf8'));
94
+ return parsed;
95
+ }
96
+ const length = Number(req.headers['content-length']);
97
+ if (Number.isFinite(length) && length > max)
98
+ throw new RequestError(413, 'The request is too large');
99
+ const chunks = [];
100
+ let size = 0;
101
+ for await (const c of req) {
102
+ size += c.length;
103
+ if (size > max)
104
+ throw new RequestError(413, 'The request is too large');
105
+ chunks.push(c);
106
+ }
107
+ return parseJson(Buffer.concat(chunks).toString('utf8'));
108
+ }
109
+ function parseJson(text) {
110
+ try {
111
+ return JSON.parse(text);
112
+ }
113
+ catch {
114
+ throw new RequestError(400, 'The body is not JSON');
115
+ }
116
+ }
117
+ /** The origin of the page asking, if it says; refuses (403) a request from another site. Returns the origin to answer with CORS for. */
118
+ function checkOrigin(req, o) {
119
+ const host = req.headers.host ?? '';
120
+ if (o.allowedHosts && !o.allowedHosts.includes(host))
121
+ throw new RequestError(403, 'This host name is not served here');
122
+ if (o.sameOrigin === false)
123
+ return undefined;
124
+ const origin = req.headers.origin;
125
+ const site = req.headers['sec-fetch-site'];
126
+ if (origin && o.origins?.includes(origin))
127
+ return origin;
128
+ if (typeof site === 'string' && site !== 'same-origin' && site !== 'none')
129
+ throw new RequestError(403, 'Only the page of this server may ask');
130
+ if (origin) {
131
+ let h = '';
132
+ try {
133
+ h = new URL(origin).host;
134
+ }
135
+ catch {
136
+ // not a URL: refused below
137
+ }
138
+ if (h !== host)
139
+ throw new RequestError(403, 'Only the page of this server may ask');
140
+ }
141
+ return undefined;
142
+ }
143
+ /**
144
+ * `(req, res) => Promise<void>` for a POST route: the body is a `SuggestRequest` (checked by `cleanRequest`), the answer 200 with a
145
+ * `SuggestResponse`, or 204 when there is none. With Express: `app.post('/api/suggest', express.json(), handler(g))`; with Fastify:
146
+ * `handler(g)(request.raw, reply.raw, request.body)` and `reply.hijack()`. It never throws.
147
+ */
148
+ export function handler(source, o = {}) {
149
+ const max = o.maxBytes ?? 256 * 1024;
150
+ return async (req, res, given) => {
151
+ const ac = new AbortController();
152
+ // The request is closed (the person typed on): the suggestion is cancelled.
153
+ res.on('close', () => {
154
+ if (!res.writableFinished)
155
+ ac.abort();
156
+ });
157
+ try {
158
+ const cors = o.sameOrigin === false ? undefined : checkOrigin(req, o);
159
+ if (cors) {
160
+ res.setHeader('access-control-allow-origin', cors);
161
+ res.setHeader('vary', 'Origin');
162
+ if (req.method === 'OPTIONS') {
163
+ res.setHeader('access-control-allow-methods', 'POST');
164
+ res.setHeader('access-control-allow-headers', 'content-type');
165
+ res.setHeader('access-control-max-age', '600');
166
+ return none(res);
167
+ }
168
+ }
169
+ if (req.method !== 'POST') {
170
+ res.setHeader('allow', 'POST');
171
+ throw new RequestError(405, 'POST a suggest request');
172
+ }
173
+ if (o.sameOrigin !== false && !/^application\/json\b/i.test(String(req.headers['content-type'] ?? ''))) {
174
+ throw new RequestError(415, 'Send the request as application/json');
175
+ }
176
+ const request = cleanRequest(await readBody(req, given, max));
177
+ let options = {};
178
+ if (o.settings) {
179
+ options = optionsFor(typeof o.settings === 'function' ? o.settings() : o.settings, request);
180
+ if (!options)
181
+ return none(res);
182
+ }
183
+ if (o.options) {
184
+ const more = await o.options(request, req);
185
+ if (more === false)
186
+ return none(res);
187
+ options = { ...options, ...more };
188
+ }
189
+ const out = await source.suggest({ ...request, ...options }, { signal: ac.signal, tab: request.client });
190
+ if (!out || ac.signal.aborted)
191
+ return none(res);
192
+ json(res, 200, out);
193
+ }
194
+ catch (e) {
195
+ if (res.writableEnded || res.destroyed)
196
+ return;
197
+ if (e instanceof RequestError) {
198
+ if (e.status === 413)
199
+ res.setHeader('connection', 'close');
200
+ return json(res, e.status, { error: e.message });
201
+ }
202
+ // The host is not there or lost the request: nothing to suggest (not a failure of the page).
203
+ if (e instanceof GraylingError && ['unavailable', 'closed', 'timeout', 'replaced', 'busy', 'aborted'].includes(e.code))
204
+ return none(res);
205
+ json(res, 500, { error: 'Suggestions failed' });
206
+ }
207
+ };
208
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * `grayling/node`: the client of the Grayling engine host for Node servers. `connect()` finds the host (or starts the `grayling`
3
+ * program), keeps the connection, and gives suggestions, the state, settings, counts and learning; `handler()` answers the POSTs
4
+ * of a text box; `findProgram()` and `installProgram()` find and download the program.
5
+ */
6
+ export { connect, Grayling, DEFAULT_TIMEOUTS, PROTOCOL, type ConnectOptions, type SuggestCallOptions, type Timeouts } from './client.js';
7
+ export { cleanRequest, handler, RequestError, type HandlerOptions, type SuggestSource } from './handler.js';
8
+ export { GraylingError, type GraylingErrorCode } from './errors.js';
9
+ export { paths, resolvePaths, pipeName, MAX_SOCKET_PATH, type GraylingOs, type GraylingPaths, type GraylingSocket, type PathFacts, type PathsOptions } from './paths.js';
10
+ export { findProgram, installProgram, currentTarget, programVersion, startableProgram, readManifest, PLATFORM_PACKAGES, TARGETS, type FindProgramOptions, type InstallOptions, type InstallProgress, type ProgramManifest, type Target, } from './program.js';
11
+ export { optionsFor } from './suggest.js';
12
+ export { suggestState } from './state.js';
13
+ export { versionCmp, packageVersion } from './version.js';
14
+ export { GRAYLING_SETTING_DEFAULTS, GRAYLING_SETTING_KEYS } from './types.js';
15
+ export type { AdoptWhat, ClaimedApp, GraylingEvents, GraylingRequestOptions, GraylingSettings, GraylingState, GraylingStatus, GraylingSuggestRequest, HostHello, HostInfo, LearnAction, NoneWhy, SuggestOutcome, TextCounts, TextLine, TextsJob, TextsProvider, UsageAnswer, } from './types.js';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `grayling/node`: the client of the Grayling engine host for Node servers. `connect()` finds the host (or starts the `grayling`
3
+ * program), keeps the connection, and gives suggestions, the state, settings, counts and learning; `handler()` answers the POSTs
4
+ * of a text box; `findProgram()` and `installProgram()` find and download the program.
5
+ */
6
+ export { connect, Grayling, DEFAULT_TIMEOUTS, PROTOCOL } from './client.js';
7
+ export { cleanRequest, handler, RequestError } from './handler.js';
8
+ export { GraylingError } from './errors.js';
9
+ export { paths, resolvePaths, pipeName, MAX_SOCKET_PATH } from './paths.js';
10
+ export { findProgram, installProgram, currentTarget, programVersion, startableProgram, readManifest, PLATFORM_PACKAGES, TARGETS, } from './program.js';
11
+ export { optionsFor } from './suggest.js';
12
+ export { suggestState } from './state.js';
13
+ export { versionCmp, packageVersion } from './version.js';
14
+ export { GRAYLING_SETTING_DEFAULTS, GRAYLING_SETTING_KEYS } from './types.js';
@@ -0,0 +1,51 @@
1
+ /** A Unix socket path of more than this many bytes does not fit in `sockaddr_un` everywhere. */
2
+ export declare const MAX_SOCKET_PATH = 100;
3
+ export type GraylingOs = 'linux' | 'macos' | 'windows';
4
+ /** Where the host listens: a Unix socket file, or a Windows named pipe (`\\.\pipe\grayling-<16 hex digits>`). */
5
+ export type GraylingSocket = {
6
+ kind: 'unix';
7
+ path: string;
8
+ } | {
9
+ kind: 'pipe';
10
+ name: string;
11
+ };
12
+ export interface GraylingPaths {
13
+ /** Settings, the lock, `engine.json`, the log: private to the person. */
14
+ data: string;
15
+ /** Downloaded models. */
16
+ cache: string;
17
+ socket: GraylingSocket;
18
+ /** `<data>/engine.lock` */
19
+ lock: string;
20
+ /** `<data>/engine.json` */
21
+ info: string;
22
+ /** `<data>/host.log` */
23
+ log: string;
24
+ /** `<data>/pids.json` */
25
+ pids: string;
26
+ }
27
+ /** The facts the rules need that the environment does not give. */
28
+ export interface PathFacts {
29
+ os: GraylingOs;
30
+ /** Whether this process runs in a container (Docker leaves `/.dockerenv`). */
31
+ container: boolean;
32
+ /** The user's id (Unix) or SID (Windows), as text. */
33
+ user: string;
34
+ }
35
+ /** The first `digits` hex digits of the SHA-256 of `input`. */
36
+ export declare const sha256Hex: (input: string, digits: number) => string;
37
+ /** 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. */
38
+ export declare const pipeName: (sid: string, data: string) => string;
39
+ /** The rules, for facts and an environment (`env`: a name's value, if set). Throws when there is no home folder to start from. */
40
+ export declare function resolvePaths(facts: PathFacts, env: (name: string) => string | undefined): GraylingPaths;
41
+ /** The user's SID (Windows), once: from `whoami /user /fo csv /nh`, which prints `"DOMAIN\name","S-1-5-21-…"`. */
42
+ export declare function windowsSid(run?: () => string): string;
43
+ export declare const currentOs: () => GraylingOs;
44
+ export interface PathsOptions {
45
+ /** The environment the rules read (default: this process's). */
46
+ env?: NodeJS.ProcessEnv;
47
+ /** `GRAYLING_HOME`: keep everything in this folder (tests, and a person who keeps everything in one place). */
48
+ home?: string;
49
+ }
50
+ /** This computer's, this person's, from the environment: the data folder, the cache, the socket. */
51
+ export declare function paths(o?: PathsOptions): GraylingPaths;