@open-artifact/server-sdk 0.0.0-stage → 0.2.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/src/serve.js ADDED
@@ -0,0 +1,779 @@
1
+ /**
2
+ * `serve()`: the skeleton of a type server. One process per type, started by
3
+ * the daemon through `entry.start` (or by hand). It listens on `OPEN_ARTIFACT_PORT` (or
4
+ * a free port), prints the {@link ReadyLine}, answers the daemon's `/__open-artifact/*`
5
+ * routes behind `Bearer OPEN_ARTIFACT_SECRET`, and hands every request under
6
+ * `/<kind>/<token>/` to that artifact's {@link Site}.
7
+ *
8
+ * A type plugs in with `mountSite(root, context)`, which returns a
9
+ * {@link Site}: the object that serves one artifact's pages.
10
+ */
11
+ import { randomBytes } from 'node:crypto';
12
+ import { EventEmitter } from 'node:events';
13
+ import { appendFileSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { createServer } from 'node:http';
15
+ import { hostname } from 'node:os';
16
+ import { basename, isAbsolute, join, resolve } from 'node:path';
17
+ import { OPEN_ARTIFACT_PROTOCOL, OpenArtifactError, TYPE_SERVER_ROUTES, errorBody, } from '@open-artifact/protocol';
18
+ import { TypeApi } from "./daemon.js";
19
+ import { LanNetwork } from "./lan.js";
20
+ import { acceptWebSocket } from "./ws.js";
21
+ /** Protocol version this SDK speaks. */
22
+ export const PROTOCOL = OPEN_ARTIFACT_PROTOCOL;
23
+ /** File a mounted artifact's folder gets, naming the server that serves it. */
24
+ export const STATE_FILE = '.artifact-server.json';
25
+ /** Per-artifact log file, in the artifact folder. */
26
+ const LOG_FILE = '.artifact-server.log';
27
+ /** WebSocket subprotocol that carries a site's server-sent event stream. */
28
+ export const STREAM_PROTOCOL = 'baoyu-sse';
29
+ /** Close codes at and above this one mean "the stream was refused with HTTP status (code - 4000)". */
30
+ const STREAM_REFUSED = 4000;
31
+ /** Host of an artifact's own origin: `<artifact id>.frame.localhost:<port>`. */
32
+ const CONTENT_HOST = /^(art_[0-9a-z]+)\.frame\.localhost:(\d+)$/;
33
+ const isLoopback = (address) => address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
34
+ /** What a long action's call answers with, besides its task id. */
35
+ export const LONG_ACTION_NOTE = 'This action runs in the background: its result comes to you as a message that starts with "[Artifact task finished]".';
36
+ // ---- helpers ---------------------------------------------------------------------------------------------------------
37
+ function sendJson(res, status, body) {
38
+ const text = JSON.stringify(body ?? null);
39
+ res.writeHead(status, {
40
+ 'Content-Type': 'application/json; charset=utf-8',
41
+ 'Cache-Control': 'no-store',
42
+ 'Content-Length': Buffer.byteLength(text),
43
+ });
44
+ res.end(text);
45
+ }
46
+ function readJsonBody(req, limit = 8 << 20) {
47
+ return new Promise((resolvePromise, reject) => {
48
+ const chunks = [];
49
+ let size = 0;
50
+ req.on('data', (chunk) => {
51
+ size += chunk.length;
52
+ if (size > limit) {
53
+ reject(new OpenArtifactError('too_large', 'The request body is too large.', { status: 413 }));
54
+ req.destroy();
55
+ }
56
+ else
57
+ chunks.push(chunk);
58
+ });
59
+ req.on('end', () => {
60
+ const text = Buffer.concat(chunks).toString('utf8');
61
+ if (!text)
62
+ return resolvePromise({});
63
+ try {
64
+ const value = JSON.parse(text);
65
+ if (value && typeof value === 'object' && !Array.isArray(value))
66
+ resolvePromise(value);
67
+ else
68
+ reject(new OpenArtifactError('invalid_argument', 'The body is not a JSON object.', { status: 400 }));
69
+ }
70
+ catch {
71
+ reject(new OpenArtifactError('invalid_argument', 'The body is not JSON.', { status: 400 }));
72
+ }
73
+ });
74
+ req.on('error', reject);
75
+ });
76
+ }
77
+ function listenOn(server, port, host) {
78
+ return new Promise((resolvePromise, reject) => {
79
+ const onError = (error) => {
80
+ server.off('listening', onListening);
81
+ reject(error);
82
+ };
83
+ const onListening = () => {
84
+ server.off('error', onError);
85
+ resolvePromise(server.address().port);
86
+ };
87
+ server.once('error', onError);
88
+ server.once('listening', onListening);
89
+ server.listen(port, host);
90
+ });
91
+ }
92
+ const notFound = (res) => {
93
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }).end('Not found');
94
+ };
95
+ // ---- StreamResponse --------------------------------------------------------------------------------------------------
96
+ /**
97
+ * The part of an HTTP response a site's event-stream handler uses, carried
98
+ * over one WebSocket: every `write` is one text message, `end` closes it
99
+ * (with `4000 + status` when the handler refused the stream). Emits `close`
100
+ * when the client goes away.
101
+ */
102
+ export class StreamResponse extends EventEmitter {
103
+ /** The WebSocket the stream goes out on. */
104
+ ws;
105
+ /** Status the handler set. */
106
+ statusCode = 200;
107
+ /** Mirrors `ServerResponse.headersSent`. */
108
+ headersSent = false;
109
+ /** Mirrors `ServerResponse.writableEnded`. */
110
+ writableEnded = false;
111
+ /** Mirrors `ServerResponse.destroyed`. */
112
+ destroyed = false;
113
+ /** Wraps an accepted WebSocket. */
114
+ constructor(ws) {
115
+ super();
116
+ this.ws = ws;
117
+ }
118
+ /** Records the status; headers do not travel. */
119
+ writeHead(status, ..._rest) {
120
+ this.statusCode = status;
121
+ this.headersSent = true;
122
+ return this;
123
+ }
124
+ /** Headers do not travel; a no-op. */
125
+ setHeader(..._args) {
126
+ return this;
127
+ }
128
+ /** A no-op. */
129
+ flushHeaders() { }
130
+ /** Sends `chunk` as one text message while the stream is open with status 200. */
131
+ write(chunk) {
132
+ if (this.statusCode === 200 && !this.writableEnded)
133
+ this.ws.sendText(String(chunk));
134
+ return true;
135
+ }
136
+ /** Ends the stream, closing the WebSocket. */
137
+ end(chunk) {
138
+ if (this.writableEnded)
139
+ return this;
140
+ if (chunk !== undefined)
141
+ this.write(chunk);
142
+ this.writableEnded = true;
143
+ this.ws.close(this.statusCode === 200 ? 1000 : STREAM_REFUSED + Math.min(this.statusCode, 999));
144
+ return this;
145
+ }
146
+ /** Ends the stream. */
147
+ destroy() {
148
+ this.destroyed = true;
149
+ return this.end();
150
+ }
151
+ /** The client went away. */
152
+ closed() {
153
+ this.writableEnded = true;
154
+ this.emit('close');
155
+ }
156
+ }
157
+ const stringArg = (args, name) => {
158
+ const value = args[name];
159
+ if (typeof value !== 'string' || !value)
160
+ throw new OpenArtifactError('invalid_argument', `args.${name} must be a non-empty string.`, { status: 400 });
161
+ return value;
162
+ };
163
+ /**
164
+ * The agent's operations on an artifact through a type library: `check`,
165
+ * `upload` and `info` for the agent's `call`, and the reserved `open-artifact.db.*` and
166
+ * `open-artifact.comments.*` the ArtifactData and ArtifactComments tools use. `config`
167
+ * is the type's `open-artifact` block (`style`, `projectDir`).
168
+ */
169
+ export function libraryActions(lib, config = {}) {
170
+ const style = config.style ?? 'root';
171
+ const target = (root) => (style === 'project' ? join(root, config.projectDir ?? 'project') : root);
172
+ const actions = {};
173
+ if (typeof lib.check === 'function') {
174
+ const check = lib.check.bind(lib);
175
+ actions.check = { title: 'Check the artifact', run: async ({ root }) => ({ check: await check(target(root)) }) };
176
+ }
177
+ if (typeof lib.upload === 'function') {
178
+ const upload = lib.upload.bind(lib);
179
+ actions.upload = {
180
+ title: 'Add a file (args.file: an absolute path; name, group)',
181
+ run: async ({ root }, args) => {
182
+ const file = args.file;
183
+ if (typeof file !== 'string' || !isAbsolute(file))
184
+ throw new OpenArtifactError('invalid_argument', 'upload: args.file is an absolute path.', { status: 400 });
185
+ const name = typeof args.name === 'string' && args.name ? args.name : basename(file);
186
+ if (style === 'project')
187
+ return { upload: await upload(target(root), new Uint8Array(readFileSync(file)), name, args.group) };
188
+ return { upload: await upload(target(root), file, name) };
189
+ },
190
+ };
191
+ }
192
+ actions.info = {
193
+ title: 'What the artifact holds',
194
+ run: async ({ root }) => ({ info: typeof lib.readInfo === 'function' ? await lib.readInfo(target(root)) : null }),
195
+ };
196
+ if (typeof lib.readDb === 'function' && typeof lib.writeDb === 'function') {
197
+ const readDb = lib.readDb.bind(lib);
198
+ const writeDb = lib.writeDb.bind(lib);
199
+ actions['open-artifact.db.read'] = {
200
+ hidden: true,
201
+ run: ({ root }, args) => readDb(root, typeof args.path === 'string' && args.path ? args.path : undefined, { query: args.query, limit: args.limit, cursor: args.cursor }),
202
+ };
203
+ actions['open-artifact.db.write'] = {
204
+ hidden: true,
205
+ run: async ({ root }, args) => ({ writes: await writeDb(root, Array.isArray(args.writes) ? args.writes : [], { requireIfMatch: args.require_if_match === true }) }),
206
+ };
207
+ }
208
+ if (typeof lib.commentThreads === 'function') {
209
+ const threads = lib.commentThreads.bind(lib);
210
+ actions['open-artifact.comments.read'] = { hidden: true, run: async ({ root }, args) => ({ threads: await threads(root, !!args.all) }) };
211
+ if (typeof lib.replyComment === 'function') {
212
+ const reply = lib.replyComment.bind(lib);
213
+ actions['open-artifact.comments.reply'] = {
214
+ hidden: true,
215
+ run: async ({ root }, args) => ({ thread: await reply(root, stringArg(args, 'thread_id'), stringArg(args, 'text'), !!args.resolve) }),
216
+ };
217
+ }
218
+ if (typeof lib.resolveComment === 'function') {
219
+ const resolveComment = lib.resolveComment.bind(lib);
220
+ actions['open-artifact.comments.resolve'] = {
221
+ hidden: true,
222
+ run: async ({ root }, args) => ({ thread: await resolveComment(root, stringArg(args, 'thread_id'), !!args.reopen) }),
223
+ };
224
+ }
225
+ }
226
+ return actions;
227
+ }
228
+ /** The type's `artifact-type.json`, read from `dir` (default `OPEN_ARTIFACT_TYPE_DIR`); `{}` when there is none. */
229
+ export function typeManifest(dir = process.env.OPEN_ARTIFACT_TYPE_DIR) {
230
+ if (!dir)
231
+ return {};
232
+ try {
233
+ const value = JSON.parse(readFileSync(join(dir, 'artifact-type.json'), 'utf8'));
234
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
235
+ }
236
+ catch {
237
+ return {};
238
+ }
239
+ }
240
+ /** A type server built on the SDK: the `/__open-artifact/*` routes plus routing to each artifact's site. */
241
+ export class TypeServer {
242
+ /** Type id. */
243
+ type;
244
+ /** Version reported by `/__open-artifact/health`. */
245
+ version;
246
+ /** The Type API client. */
247
+ daemon;
248
+ /** Diagnostic log. */
249
+ log;
250
+ /** The loopback HTTP server. */
251
+ server;
252
+ /** The LAN listeners. */
253
+ lan;
254
+ /** Port once listening. */
255
+ port = 0;
256
+ options;
257
+ secret;
258
+ idleMs;
259
+ byId = new Map();
260
+ byPage = new Map();
261
+ mounting = new Map();
262
+ hosts = new Set();
263
+ lastActivity = Date.now();
264
+ timer = null;
265
+ /** Creates the server; call {@link listen} next. */
266
+ constructor(options) {
267
+ if (typeof options?.mountSite !== 'function')
268
+ throw new TypeError('serve() needs mountSite(root, context).');
269
+ this.options = options;
270
+ this.type = options.type ?? process.env.OPEN_ARTIFACT_TYPE ?? 'type';
271
+ this.version = options.version ?? '0';
272
+ this.secret = options.secret !== undefined ? options.secret : process.env.OPEN_ARTIFACT_SECRET || null;
273
+ this.daemon = options.daemon ?? new TypeApi();
274
+ this.log = options.log ?? ((line) => process.stderr.write(`[${new Date().toISOString()}] ${line}\n`));
275
+ this.idleMs = options.idleMs ?? Number(process.env.OPEN_ARTIFACT_SERVER_IDLE_MS ?? 15 * 60_000);
276
+ this.server = this.makeServer();
277
+ this.lan = new LanNetwork({
278
+ port: () => this.port,
279
+ createServer: () => this.makeServer(),
280
+ stillShared: () => this.anySharing(),
281
+ log: (line) => this.log(line),
282
+ });
283
+ }
284
+ /** `http://127.0.0.1:<port>`, without a trailing slash. */
285
+ get origin() {
286
+ return `http://127.0.0.1:${this.port}`;
287
+ }
288
+ /** Number of mounted artifacts. */
289
+ get openCount() {
290
+ return this.byId.size;
291
+ }
292
+ makeServer() {
293
+ const server = createServer((req, res) => {
294
+ this.onRequest(req, res).catch((error) => {
295
+ if (res.headersSent)
296
+ return void res.destroy();
297
+ const status = error?.status;
298
+ sendJson(res, typeof status === 'number' ? status : 500, errorBody(error));
299
+ });
300
+ });
301
+ server.on('upgrade', (req, socket, head) => this.onUpgrade(req, socket, head));
302
+ return server;
303
+ }
304
+ /** Listens on the configured port, or any free one when it is taken. */
305
+ async listen() {
306
+ const want = this.options.port ?? Number(process.env.OPEN_ARTIFACT_PORT || 0);
307
+ const host = this.options.host ?? '127.0.0.1';
308
+ try {
309
+ this.port = await listenOn(this.server, want, host);
310
+ }
311
+ catch (error) {
312
+ if (error.code !== 'EADDRINUSE' || !want)
313
+ throw error;
314
+ // The last port is taken: any free one (share links name the port, so the daemon offers the same one first).
315
+ this.port = await listenOn(this.server, 0, host);
316
+ }
317
+ this.hosts = new Set([`127.0.0.1:${this.port}`, `localhost:${this.port}`, `[::1]:${this.port}`]);
318
+ this.timer = setInterval(() => this.tick(), 60_000);
319
+ this.timer.unref();
320
+ return this;
321
+ }
322
+ /** The line the daemon waits for, with the protocol version and type for logs. */
323
+ readyLine() {
324
+ return { openArtifact: 'ready', url: `${this.origin}/`, protocol: PROTOCOL, type: this.type };
325
+ }
326
+ /** Prints the ready line to `out` (default stdout). */
327
+ ready(out = process.stdout) {
328
+ out.write(`${JSON.stringify(this.readyLine())}\n`);
329
+ }
330
+ tick() {
331
+ if (this.idleMs <= 0)
332
+ return;
333
+ const now = Date.now();
334
+ // Sites nobody asked anything of for a while, with no stream open and not shared, go.
335
+ for (const entry of [...this.byId.values()]) {
336
+ if (entry.streams <= 0 && now - entry.lastUsed > this.idleMs && !this.sharing(entry))
337
+ this.unmount(entry.id);
338
+ }
339
+ if (!this.byId.size && now - this.lastActivity > this.idleMs) {
340
+ this.log('idle: exiting');
341
+ if (this.options.onIdle)
342
+ this.options.onIdle();
343
+ else {
344
+ this.close();
345
+ process.exit(0);
346
+ }
347
+ }
348
+ }
349
+ sharing(entry) {
350
+ return !!entry.site.share?.listening;
351
+ }
352
+ anySharing() {
353
+ return [...this.byId.values()].some((entry) => this.sharing(entry));
354
+ }
355
+ hostAllowed(req) {
356
+ const host = String(req.headers.host ?? '');
357
+ return this.hosts.has(host) || this.lan.hostAllowed(host) || this.contentIdOf(req) !== null;
358
+ }
359
+ /** The artifact id of a request on an artifact's own origin, or null. */
360
+ contentIdOf(req) {
361
+ if (!this.options.contentHosts || !this.port)
362
+ return null;
363
+ const match = CONTENT_HOST.exec(String(req.headers.host ?? '').toLowerCase());
364
+ if (!match || Number(match[2]) !== this.port || !isLoopback(req.socket.remoteAddress))
365
+ return null;
366
+ return match[1];
367
+ }
368
+ /** The mounted site whose own origin a request is on, or null when it is not on one. */
369
+ contentEntry(req) {
370
+ const id = this.contentIdOf(req);
371
+ if (id === null)
372
+ return null;
373
+ return { entry: this.byId.get(id) ?? null };
374
+ }
375
+ // ---- artifacts -----------------------------------------------------------------------------------------------------
376
+ /** Mounts an artifact (or finds it mounted); idempotent. */
377
+ async open(request) {
378
+ const { id, root, title } = request;
379
+ if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(id))
380
+ throw new OpenArtifactError('invalid_argument', 'open needs an artifact id.', { status: 400 });
381
+ if (typeof root !== 'string' || !isAbsolute(root)) {
382
+ throw new OpenArtifactError('invalid_argument', 'open needs the artifact root (an absolute path).', { status: 400 });
383
+ }
384
+ const have = this.byId.get(id);
385
+ if (have && have.root === resolve(root)) {
386
+ have.lastUsed = Date.now();
387
+ if (title)
388
+ have.title = title;
389
+ return have;
390
+ }
391
+ if (have)
392
+ this.unmount(id);
393
+ const busy = this.mounting.get(id);
394
+ if (busy)
395
+ return busy;
396
+ const work = this.mount(id, resolve(root), title).finally(() => this.mounting.delete(id));
397
+ this.mounting.set(id, work);
398
+ return work;
399
+ }
400
+ async mount(id, root, title) {
401
+ if (!existsSync(root))
402
+ throw new OpenArtifactError('not_found', `The folder ${root} is gone.`, { status: 404 });
403
+ const logFile = join(root, LOG_FILE);
404
+ const log = (line) => {
405
+ try {
406
+ appendFileSync(logFile, `[${new Date().toISOString()}] ${line}\n`);
407
+ }
408
+ catch {
409
+ // A read-only or vanished folder.
410
+ }
411
+ };
412
+ let agentName;
413
+ try {
414
+ agentName = (await this.daemon.artifact(id)).agentName || undefined;
415
+ }
416
+ catch {
417
+ agentName = undefined;
418
+ }
419
+ let agentWakesIdle;
420
+ try {
421
+ agentWakesIdle = (await this.daemon.presence(id)).wakesIdle;
422
+ }
423
+ catch {
424
+ agentWakesIdle = undefined;
425
+ }
426
+ const wake = async (body) => {
427
+ const out = await this.daemon.wake(id, body);
428
+ if (out.status === 'failed')
429
+ throw new OpenArtifactError('daemon_failed', 'The agent could not be reached.');
430
+ return out;
431
+ };
432
+ const site = await this.options.mountSite(root, {
433
+ id,
434
+ title: title ?? '',
435
+ daemon: this.daemon,
436
+ log,
437
+ network: this.lan.network,
438
+ local: (req) => isLoopback(req.socket.remoteAddress),
439
+ agentHook: { thread: (view) => wake({ threads: [view] }), request: (request) => wake({ requests: [request] }) },
440
+ ...(agentName ? { agentName } : {}),
441
+ ...(agentWakesIdle === false ? { agentWakesIdle } : {}),
442
+ contentOrigin: this.options.contentHosts && CONTENT_HOST.test(`${id}.frame.localhost:${this.port}`) ? `http://${id}.frame.localhost:${this.port}` : null,
443
+ open: async () => {
444
+ throw new OpenArtifactError('unsupported', 'Opening another folder from a page is not supported here.');
445
+ },
446
+ });
447
+ const other = this.byPage.get(site.page);
448
+ if (other) {
449
+ site.close();
450
+ throw new OpenArtifactError('conflict', `${other.root} is already open at ${site.page}.`, { status: 409 });
451
+ }
452
+ const entry = { id, root, title: title ?? '', site, page: site.page, streams: 0, lastUsed: Date.now() };
453
+ this.byId.set(id, entry);
454
+ this.byPage.set(site.page, entry);
455
+ try {
456
+ await site.share?.start?.(false);
457
+ }
458
+ catch (error) {
459
+ this.unmount(id);
460
+ throw error;
461
+ }
462
+ try {
463
+ const record = {
464
+ pid: process.pid,
465
+ url: `${this.origin}${site.page}`,
466
+ port: this.port,
467
+ root,
468
+ kind: site.page.split('/')[1] ?? '',
469
+ startedAt: new Date().toISOString(),
470
+ openArtifact: id,
471
+ };
472
+ writeFileSync(join(root, STATE_FILE), `${JSON.stringify(record, null, 2)}\n`);
473
+ }
474
+ catch {
475
+ // Tools looking for this server will not find it; the page still works.
476
+ }
477
+ this.log(`mounted ${id} at ${site.page}`);
478
+ log(`serving ${root} at ${this.origin}${site.page} (open-artifact type server ${this.type})`);
479
+ return entry;
480
+ }
481
+ /** Unmounts an artifact; false when it was not mounted. */
482
+ unmount(id) {
483
+ const entry = this.byId.get(id);
484
+ if (!entry)
485
+ return false;
486
+ this.byId.delete(id);
487
+ this.byPage.delete(entry.page);
488
+ try {
489
+ const file = join(entry.root, STATE_FILE);
490
+ const state = JSON.parse(readFileSync(file, 'utf8'));
491
+ if (state.pid === process.pid)
492
+ rmSync(file, { force: true });
493
+ }
494
+ catch {
495
+ // Nothing written, or someone else's.
496
+ }
497
+ try {
498
+ entry.site.close();
499
+ }
500
+ catch (error) {
501
+ this.log(`closing ${id}: ${error instanceof Error ? error.message : String(error)}`);
502
+ }
503
+ return true;
504
+ }
505
+ /** The site whose address `pathname` is under, with the path below it. */
506
+ under(pathname) {
507
+ const [, first, second] = pathname.split('/');
508
+ const entry = first && second ? this.byPage.get(`/${first}/${second}/`) : undefined;
509
+ if (entry)
510
+ return { entry, rest: pathname.slice(entry.page.length - 1) };
511
+ for (const e of this.byPage.values())
512
+ if (e.site.claims?.(pathname))
513
+ return { entry: e, rest: pathname };
514
+ return null;
515
+ }
516
+ /** The site of the page that referred this request (same host only). */
517
+ referred(req) {
518
+ const referer = req.headers.referer;
519
+ if (typeof referer !== 'string')
520
+ return null;
521
+ try {
522
+ const at = new URL(referer);
523
+ return at.host === req.headers.host ? (this.under(at.pathname)?.entry ?? null) : null;
524
+ }
525
+ catch {
526
+ return null;
527
+ }
528
+ }
529
+ /** The site that answers a path outside every site's address: share links, uploads, common paths, the referrer. */
530
+ async answering(req, pathname) {
531
+ const link = /^\/s\/([A-Za-z0-9_-]{16,64})$/.exec(pathname);
532
+ if (link)
533
+ return [...this.byPage.values()].find((e) => e.site.share?.sharing?.linkRole?.(link[1])) ?? null;
534
+ const blob = /^\/_blob\/([0-9a-f]{32})$/.exec(pathname);
535
+ if (blob) {
536
+ const referred = this.referred(req);
537
+ const all = [...this.byPage.values()];
538
+ for (const e of referred ? [referred, ...all.filter((x) => x !== referred)] : all)
539
+ if (await e.site.hasBlob?.(blob[1]))
540
+ return e;
541
+ return null;
542
+ }
543
+ for (const e of this.byPage.values())
544
+ if (e.site.common?.(pathname))
545
+ return e;
546
+ return this.referred(req);
547
+ }
548
+ // ---- requests ------------------------------------------------------------------------------------------------------
549
+ async onRequest(req, res) {
550
+ this.lastActivity = Date.now();
551
+ if (!this.hostAllowed(req)) {
552
+ req.resume();
553
+ res.writeHead(421, { 'Content-Type': 'text/plain; charset=utf-8' }).end('Misdirected request');
554
+ return;
555
+ }
556
+ const content = this.contentEntry(req);
557
+ if (content) {
558
+ const site = content.entry?.site;
559
+ if (!content.entry || !site?.content) {
560
+ req.resume();
561
+ return notFound(res);
562
+ }
563
+ content.entry.lastUsed = Date.now();
564
+ await site.content(req, res);
565
+ return;
566
+ }
567
+ const url = new URL(req.url ?? '/', 'http://local');
568
+ if (url.pathname.startsWith('/__open-artifact/'))
569
+ return this.openArtifactRoute(req, res, url);
570
+ return this.siteRequest(req, res, url);
571
+ }
572
+ async siteRequest(req, res, url) {
573
+ const at = this.under(url.pathname);
574
+ if (at) {
575
+ at.entry.lastUsed = Date.now();
576
+ if (at.rest === '') {
577
+ req.resume();
578
+ res.writeHead(308, { Location: `${url.pathname}/${url.search}`, 'Cache-Control': 'no-store' }).end();
579
+ return;
580
+ }
581
+ req.url = `${at.rest}${url.search}`;
582
+ await at.entry.site.handle(req, res);
583
+ return;
584
+ }
585
+ const entry = await this.answering(req, url.pathname);
586
+ if (entry) {
587
+ entry.lastUsed = Date.now();
588
+ await entry.site.handle(req, res);
589
+ return;
590
+ }
591
+ req.resume();
592
+ notFound(res);
593
+ }
594
+ /** The daemon's routes: from this computer, with the secret, never from a page. */
595
+ async openArtifactRoute(req, res, url) {
596
+ const granted = isLoopback(req.socket.remoteAddress) &&
597
+ (!this.secret || req.headers.authorization === `Bearer ${this.secret}`) &&
598
+ req.headers.origin === undefined;
599
+ if (!granted) {
600
+ req.resume();
601
+ return sendJson(res, 401, { code: 'unauthorized', message: "The /__open-artifact/* routes are the Open Artifact daemon's." });
602
+ }
603
+ const path = url.pathname;
604
+ const get = req.method === 'GET';
605
+ const body = get ? {} : await readJsonBody(req);
606
+ const artifact = (id) => {
607
+ const entry = this.byId.get(String(id ?? ''));
608
+ if (!entry)
609
+ throw new OpenArtifactError('not_found', `${String(id)} is not open here.`, { status: 404, fix: 'Open it first (/__open-artifact/open).' });
610
+ entry.lastUsed = Date.now();
611
+ return entry;
612
+ };
613
+ if (path === TYPE_SERVER_ROUTES.health) {
614
+ const health = { openArtifact: 1, type: this.type, version: this.version, open: this.byId.size };
615
+ return sendJson(res, 200, health);
616
+ }
617
+ if (path === TYPE_SERVER_ROUTES.open && !get) {
618
+ const entry = await this.open(body);
619
+ const page = `${this.origin}${entry.page}`;
620
+ const result = { url: page, page_url: page };
621
+ return sendJson(res, 200, result);
622
+ }
623
+ if (path === TYPE_SERVER_ROUTES.close && !get) {
624
+ const { id } = body;
625
+ return sendJson(res, 200, { closed: this.unmount(String(id ?? '')) });
626
+ }
627
+ if (path === TYPE_SERVER_ROUTES.share) {
628
+ const entry = artifact(get ? url.searchParams.get('id') : body.id);
629
+ const share = entry.site.share;
630
+ if (!share || typeof share.shareView !== 'function' || typeof share.share !== 'function') {
631
+ throw new OpenArtifactError('unsupported', `${this.type} pages cannot be shared.`, { status: 409 });
632
+ }
633
+ if (get)
634
+ return sendJson(res, 200, await share.shareView());
635
+ const { id: _id, ...action } = body;
636
+ return sendJson(res, 200, await share.share(action));
637
+ }
638
+ if (path === TYPE_SERVER_ROUTES.actions.slice(0, -1) && get) {
639
+ const actions = Object.entries(this.options.actions ?? {})
640
+ .filter(([, a]) => !a.hidden)
641
+ .map(([name, a]) => ({
642
+ name,
643
+ title: a.title ?? name,
644
+ ...(a.description ? { description: a.description } : {}),
645
+ ...(a.effect ? { effect: a.effect } : {}),
646
+ ...(a.schema ? { schema: a.schema } : {}),
647
+ ...(a.long ? { long: true } : {}),
648
+ }));
649
+ return sendJson(res, 200, { actions });
650
+ }
651
+ if (path.startsWith(TYPE_SERVER_ROUTES.actions) && !get) {
652
+ const name = decodeURIComponent(path.slice(TYPE_SERVER_ROUTES.actions.length));
653
+ const action = Object.hasOwn(this.options.actions ?? {}, name) ? this.options.actions[name] : undefined;
654
+ if (!action)
655
+ throw new OpenArtifactError('unknown_action', `${this.type} has no action ${name}.`, { status: 404 });
656
+ const entry = artifact(body.id);
657
+ const args = body.args && typeof body.args === 'object' && !Array.isArray(body.args) ? body.args : {};
658
+ const ref = { id: entry.id, root: entry.root, title: entry.title, site: entry.site };
659
+ if (action.long && this.daemon.available)
660
+ return sendJson(res, 200, this.runLong(name, action, ref, args));
661
+ return sendJson(res, 200, await action.run(ref, args));
662
+ }
663
+ if (path === TYPE_SERVER_ROUTES.summary && get && this.options.summary) {
664
+ const entry = artifact(url.searchParams.get('id'));
665
+ return sendJson(res, 200, await this.options.summary({ id: entry.id, root: entry.root }));
666
+ }
667
+ req.resume();
668
+ return sendJson(res, 404, { code: 'not_found', message: `No route ${path}.` });
669
+ }
670
+ /** Starts a long action and answers with its task; the end goes to the daemon (`open-artifact.type.task`). */
671
+ runLong(name, action, ref, args) {
672
+ const task = `task_${randomBytes(8).toString('hex')}`;
673
+ const report = (body) => this.daemon.task(task, body).then(() => undefined, (error) => this.log(`task ${task} (${name}): reporting failed: ${error instanceof Error ? error.message : String(error)}`));
674
+ const progress = (fraction) => {
675
+ if (Number.isFinite(fraction))
676
+ void report({ progress: Math.max(0, Math.min(1, fraction)) });
677
+ };
678
+ void (async () => {
679
+ try {
680
+ const result = await action.run(ref, args, { id: task, progress });
681
+ await report({ done: true, result: result ?? null });
682
+ }
683
+ catch (error) {
684
+ await report({ done: true, error: errorBody(error) });
685
+ }
686
+ })();
687
+ return { task, pending: true, note: LONG_ACTION_NOTE };
688
+ }
689
+ onUpgrade(req, socket, head) {
690
+ socket.on('error', () => { });
691
+ this.lastActivity = Date.now();
692
+ if (!this.hostAllowed(req)) {
693
+ socket.end('HTTP/1.1 403 Forbidden\r\n\r\n');
694
+ return;
695
+ }
696
+ const content = this.contentEntry(req);
697
+ if (content) {
698
+ const site = content.entry?.site;
699
+ if (!content.entry || !site?.contentUpgrade) {
700
+ socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
701
+ return;
702
+ }
703
+ content.entry.lastUsed = Date.now();
704
+ site.contentUpgrade(req, socket, head);
705
+ return;
706
+ }
707
+ const url = new URL(req.url ?? '/', 'http://local');
708
+ const at = this.under(url.pathname);
709
+ if (!at) {
710
+ socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
711
+ return;
712
+ }
713
+ at.entry.lastUsed = Date.now();
714
+ req.url = `${at.rest}${url.search}`;
715
+ const asked = String(req.headers['sec-websocket-protocol'] ?? '')
716
+ .split(',')
717
+ .map((s) => s.trim());
718
+ if (asked.includes(STREAM_PROTOCOL))
719
+ return this.stream(at.entry, req, socket, head, url);
720
+ if (at.entry.site.upgrade)
721
+ return at.entry.site.upgrade(req, socket, head);
722
+ socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
723
+ }
724
+ /** A site's event stream (SSE) carried over a WebSocket ({@link STREAM_PROTOCOL}). */
725
+ stream(entry, req, socket, head, url) {
726
+ const ws = acceptWebSocket(req, socket, head, STREAM_PROTOCOL);
727
+ if (!ws)
728
+ return;
729
+ const last = url.searchParams.get('__lastEventId');
730
+ if (last !== null) {
731
+ req.headers['last-event-id'] = last;
732
+ url.searchParams.delete('__lastEventId');
733
+ req.url = `${(req.url ?? '').split('?')[0]}${url.search}`;
734
+ }
735
+ req.method = 'GET';
736
+ const response = new StreamResponse(ws);
737
+ entry.streams += 1;
738
+ ws.handlers = {
739
+ close: () => {
740
+ entry.streams -= 1;
741
+ entry.lastUsed = Date.now();
742
+ this.lastActivity = Date.now();
743
+ response.closed();
744
+ req.emit('close');
745
+ },
746
+ };
747
+ Promise.resolve()
748
+ .then(() => entry.site.handle(req, response))
749
+ .catch(() => ws.close(STREAM_REFUSED + 500));
750
+ }
751
+ /** Unmounts everything and stops listening. */
752
+ close() {
753
+ if (this.timer)
754
+ clearInterval(this.timer);
755
+ this.timer = null;
756
+ for (const id of [...this.byId.keys()])
757
+ this.unmount(id);
758
+ this.lan.close();
759
+ this.server.close();
760
+ this.server.closeAllConnections();
761
+ }
762
+ }
763
+ /**
764
+ * Runs a type server: listens, prints the ready line, and closes everything
765
+ * on SIGTERM / SIGINT. Resolves with the {@link TypeServer}.
766
+ */
767
+ export async function serve(options) {
768
+ const server = new TypeServer(options);
769
+ await server.listen();
770
+ const stop = () => {
771
+ server.close();
772
+ process.exit(0);
773
+ };
774
+ process.once('SIGTERM', stop);
775
+ process.once('SIGINT', stop);
776
+ server.ready();
777
+ server.log(`${server.type} type server at ${server.origin}/ (pid ${process.pid}, ${hostname()})`);
778
+ return server;
779
+ }