pinwright 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +245 -2
- package/dist/agent.d.ts +16 -0
- package/dist/agent.js +292 -0
- package/dist/astro.d.ts +16 -0
- package/dist/astro.js +29 -0
- package/dist/bus.d.ts +16 -0
- package/dist/bus.js +13 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +125 -0
- package/dist/cloudflared.d.ts +10 -0
- package/dist/cloudflared.js +98 -0
- package/dist/collab.d.ts +56 -0
- package/dist/collab.js +183 -0
- package/dist/config.d.ts +53 -0
- package/dist/config.js +59 -0
- package/dist/context.d.ts +18 -0
- package/dist/context.js +11 -0
- package/dist/db.d.ts +2 -0
- package/dist/db.js +74 -0
- package/dist/guard.d.ts +26 -0
- package/dist/guard.js +137 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +70 -0
- package/dist/inject.d.ts +7 -0
- package/dist/inject.js +82 -0
- package/dist/locks.d.ts +14 -0
- package/dist/locks.js +51 -0
- package/dist/next-script.d.ts +6 -0
- package/dist/next-script.js +12 -0
- package/dist/next.d.ts +10 -0
- package/dist/next.js +28 -0
- package/dist/nuxt.d.ts +18 -0
- package/dist/nuxt.js +17 -0
- package/dist/ops.d.ts +39 -0
- package/dist/ops.js +146 -0
- package/dist/planner.d.ts +10 -0
- package/dist/planner.js +65 -0
- package/dist/plugin.d.ts +13 -0
- package/dist/plugin.js +58 -0
- package/dist/rebuild.d.ts +23 -0
- package/dist/rebuild.js +67 -0
- package/dist/scheduler.d.ts +26 -0
- package/dist/scheduler.js +150 -0
- package/dist/server.d.ts +7 -0
- package/dist/server.js +355 -0
- package/dist/shots.d.ts +25 -0
- package/dist/shots.js +86 -0
- package/dist/store.d.ts +76 -0
- package/dist/store.js +159 -0
- package/dist/tools.d.ts +11 -0
- package/dist/tools.js +27 -0
- package/dist/vite.d.ts +33 -0
- package/dist/vite.js +37 -0
- package/dist/webpack.d.ts +36 -0
- package/dist/webpack.js +58 -0
- package/dist/ws.d.ts +25 -0
- package/dist/ws.js +115 -0
- package/overlay/overlay.js +1379 -0
- package/package.json +59 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { createReadStream, existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import { basename, dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { isRemote, LINK_KINDS } from './collab.js';
|
|
7
|
+
import { acceptWs } from './ws.js';
|
|
8
|
+
import { OpError } from './ops.js';
|
|
9
|
+
const OVERLAY = join(dirname(fileURLToPath(import.meta.url)), '..', 'overlay', 'overlay.js');
|
|
10
|
+
export const SCRIPT_PATH = '/__pw/overlay.js';
|
|
11
|
+
const isLocal = (origin) => {
|
|
12
|
+
if (!origin)
|
|
13
|
+
return true;
|
|
14
|
+
try {
|
|
15
|
+
return ['localhost', '127.0.0.1', '[::1]'].includes(new URL(origin).hostname);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
/** The list view: no html, styles or diff, which only the panel needs. */
|
|
22
|
+
const light = (n) => ({ ...n, html: undefined, styles: undefined, diff: undefined, hasDiff: Boolean(n.diff) });
|
|
23
|
+
function readBody(req, limit = 256_000) {
|
|
24
|
+
return new Promise((ok, fail) => {
|
|
25
|
+
let s = '';
|
|
26
|
+
req.setEncoding('utf8');
|
|
27
|
+
req.on('data', (c) => {
|
|
28
|
+
s += c;
|
|
29
|
+
if (s.length > limit) {
|
|
30
|
+
fail(new OpError('body too large', 413));
|
|
31
|
+
req.destroy();
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
req.on('end', () => {
|
|
35
|
+
try {
|
|
36
|
+
ok(s ? JSON.parse(s) : {});
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
fail(new OpError('bad json'));
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
req.on('error', fail);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
export function createServer(ctx, ops, scheduler, collab) {
|
|
46
|
+
const { cfg, store, bus } = ctx;
|
|
47
|
+
/** Open live channels (WebSocket), with the person each belongs to and whether it comes from outside. */
|
|
48
|
+
const clients = new Map();
|
|
49
|
+
const send = (event, data, only) => {
|
|
50
|
+
const msg = JSON.stringify({ event, data });
|
|
51
|
+
for (const [conn, c] of clients)
|
|
52
|
+
if (!only || only(c))
|
|
53
|
+
conn.send(msg);
|
|
54
|
+
};
|
|
55
|
+
/** The two links, once shared: `auto` runs every note, `review` waits for the host's approval. */
|
|
56
|
+
let links = null;
|
|
57
|
+
const sharePayload = () => ({ links: collab.sharing ? links : null });
|
|
58
|
+
bus.on('note', (n) => send('note', light(n)));
|
|
59
|
+
bus.on('activity', (a) => send('activity', a));
|
|
60
|
+
bus.on('reload', () => send('reload', {}));
|
|
61
|
+
const ping = setInterval(() => {
|
|
62
|
+
for (const c of clients.keys())
|
|
63
|
+
c.ping();
|
|
64
|
+
}, 25_000);
|
|
65
|
+
const json = (res, data, code = 200) => {
|
|
66
|
+
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
67
|
+
res.end(JSON.stringify(data));
|
|
68
|
+
};
|
|
69
|
+
async function api(req, res, url) {
|
|
70
|
+
const path = url.pathname.slice('/__pw'.length);
|
|
71
|
+
const m = req.method ?? 'GET';
|
|
72
|
+
const access = collab.access(req) ?? 'review';
|
|
73
|
+
/** What a guest of the review link writes waits for the host. */
|
|
74
|
+
const approved = access !== 'review';
|
|
75
|
+
if (path === '/overlay.js') {
|
|
76
|
+
const cfgJs = `window.__pinwright=${JSON.stringify({ lang: cfg.lang })};\n`;
|
|
77
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
78
|
+
return void res.end(cfgJs + readFileSync(OVERLAY, 'utf8'));
|
|
79
|
+
}
|
|
80
|
+
if (path === '/share') {
|
|
81
|
+
if (isRemote(req))
|
|
82
|
+
throw new OpError('only the host can share', 403);
|
|
83
|
+
if (m === 'POST') {
|
|
84
|
+
const b = await readBody(req);
|
|
85
|
+
const { url: base, tokens } = await collab.share();
|
|
86
|
+
const page = typeof b.page === 'string' && b.page.startsWith('/') ? b.page : '/';
|
|
87
|
+
const link = (t) => `${base}${page}${page.includes('?') ? '&' : '?'}pw=${t}`;
|
|
88
|
+
links = Object.fromEntries(LINK_KINDS.map((k) => [k, link(tokens[k])]));
|
|
89
|
+
send('share', sharePayload(), (c) => !c.guest);
|
|
90
|
+
return json(res, sharePayload());
|
|
91
|
+
}
|
|
92
|
+
if (m === 'DELETE') {
|
|
93
|
+
collab.unshare();
|
|
94
|
+
links = null;
|
|
95
|
+
send('share', sharePayload(), (c) => !c.guest);
|
|
96
|
+
// Guests lose access: their streams close and the old link stops working.
|
|
97
|
+
for (const [conn, c] of clients)
|
|
98
|
+
if (c.guest)
|
|
99
|
+
conn.close();
|
|
100
|
+
return json(res, { ok: true });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (path.startsWith('/shots/')) {
|
|
104
|
+
const file = join(ctx.shooter.dir, basename(path));
|
|
105
|
+
if (!existsSync(file))
|
|
106
|
+
return json(res, { error: 'not found' }, 404);
|
|
107
|
+
res.writeHead(200, { 'content-type': 'image/jpeg', 'cache-control': 'max-age=31536000, immutable' });
|
|
108
|
+
return void createReadStream(file).pipe(res);
|
|
109
|
+
}
|
|
110
|
+
if (path === '/status') {
|
|
111
|
+
if (isRemote(req))
|
|
112
|
+
throw new OpError('forbidden', 403);
|
|
113
|
+
return json(res, { busy: scheduler.busy, locks: ctx.locks.snapshot(), activity: Object.fromEntries(bus.activity), root: cfg.root });
|
|
114
|
+
}
|
|
115
|
+
if (path === '/notes' && m === 'GET') {
|
|
116
|
+
const all = url.searchParams.get('all');
|
|
117
|
+
return json(res, (all ? store.list(['queued', 'planning', 'working', 'done', 'asking', 'handoff', 'failed', 'archived', 'undone', 'taken']) : store.list()).map(light));
|
|
118
|
+
}
|
|
119
|
+
if (path === '/notes' && m === 'POST') {
|
|
120
|
+
const b = await readBody(req);
|
|
121
|
+
if (typeof b.text !== 'string' || !b.text.trim() || typeof b.page !== 'string')
|
|
122
|
+
throw new OpError('text and page are required');
|
|
123
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
|
124
|
+
const str = (v) => (typeof v === 'string' ? v : null);
|
|
125
|
+
const styles = b.styles && typeof b.styles === 'object' ? b.styles : null;
|
|
126
|
+
const note = store.create({
|
|
127
|
+
page: b.page,
|
|
128
|
+
text: b.text.trim(),
|
|
129
|
+
url: str(b.url),
|
|
130
|
+
selector: str(b.selector),
|
|
131
|
+
element: str(b.element),
|
|
132
|
+
html: str(b.html),
|
|
133
|
+
styles,
|
|
134
|
+
fx: num(b.fx),
|
|
135
|
+
fy: num(b.fy),
|
|
136
|
+
pageX: num(b.pageX),
|
|
137
|
+
pageY: num(b.pageY),
|
|
138
|
+
viewport: str(b.viewport),
|
|
139
|
+
author: str(b.author),
|
|
140
|
+
approved,
|
|
141
|
+
guest: access !== 'host',
|
|
142
|
+
});
|
|
143
|
+
cfg.log(`${note.id}: new note on ${note.page}${approved ? '' : ' (waiting for approval)'}: “${note.text.split('\n')[0].slice(0, 70)}”`);
|
|
144
|
+
return json(res, light(note), 201);
|
|
145
|
+
}
|
|
146
|
+
const nm = path.match(/^\/notes\/([\w-]+)(?:\/(\w+))?$/);
|
|
147
|
+
if (nm) {
|
|
148
|
+
const [, id, action] = nm;
|
|
149
|
+
if (!action && m === 'GET') {
|
|
150
|
+
const note = store.get(id);
|
|
151
|
+
if (!note || note.status === 'deleted')
|
|
152
|
+
throw new OpError('note not found', 404);
|
|
153
|
+
return json(res, { ...note, messages: store.messages(id), files: store.changes(id).map((c) => c.file), activity: bus.activity.get(id) ?? null });
|
|
154
|
+
}
|
|
155
|
+
if (!action && m === 'DELETE') {
|
|
156
|
+
ops.delete(id);
|
|
157
|
+
return json(res, { ok: true });
|
|
158
|
+
}
|
|
159
|
+
if (m === 'POST') {
|
|
160
|
+
const b = await readBody(req);
|
|
161
|
+
switch (action) {
|
|
162
|
+
case 'reply':
|
|
163
|
+
return json(res, light(ops.reply(id, String(b.text ?? ''), typeof b.author === 'string' ? b.author.slice(0, 60) : null, approved, access !== 'host')));
|
|
164
|
+
case 'approve':
|
|
165
|
+
if (access !== 'host')
|
|
166
|
+
throw new OpError('only the host can approve a note', 403);
|
|
167
|
+
return json(res, light(ops.approve(id)));
|
|
168
|
+
case 'archive':
|
|
169
|
+
return json(res, light(ops.archive(id)));
|
|
170
|
+
case 'retry':
|
|
171
|
+
return json(res, light(ops.retry(id, approved)));
|
|
172
|
+
case 'handoff':
|
|
173
|
+
return json(res, light(ops.handoff(id)));
|
|
174
|
+
case 'undo':
|
|
175
|
+
return json(res, light(await ops.undo(id)));
|
|
176
|
+
case 'take':
|
|
177
|
+
if (isRemote(req))
|
|
178
|
+
throw new OpError('only the host can take a note', 403);
|
|
179
|
+
return json(res, ops.take(id));
|
|
180
|
+
case 'done':
|
|
181
|
+
return json(res, light(ops.markDone(id, typeof b.summary === 'string' ? b.summary : undefined)));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
json(res, { error: 'not found' }, 404);
|
|
186
|
+
}
|
|
187
|
+
function proxy(req, res) {
|
|
188
|
+
const target = cfg.target ?? cfg.siteUrl;
|
|
189
|
+
if (!target) {
|
|
190
|
+
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
|
|
191
|
+
return void res.end(`pinwright is running on ${cfg.root}.\nNo --target: the overlay is served at ${SCRIPT_PATH}.\n`);
|
|
192
|
+
}
|
|
193
|
+
const t = new URL(target);
|
|
194
|
+
const headers = { ...req.headers, host: t.host, 'accept-encoding': 'identity' };
|
|
195
|
+
// The share token is ours, not the site's.
|
|
196
|
+
const site = (req.headers.cookie ?? '').split(';').filter((c) => !c.trim().startsWith('pw_t=')).join(';').trim();
|
|
197
|
+
if (site)
|
|
198
|
+
headers.cookie = site;
|
|
199
|
+
else
|
|
200
|
+
delete headers.cookie;
|
|
201
|
+
delete headers['if-none-match'];
|
|
202
|
+
delete headers['if-modified-since'];
|
|
203
|
+
const up = http.request({ host: t.hostname, port: t.port || 80, path: req.url, method: req.method, headers }, (r) => {
|
|
204
|
+
const h = { ...r.headers };
|
|
205
|
+
if (typeof h.location === 'string' && h.location.startsWith(t.origin))
|
|
206
|
+
h.location = h.location.slice(t.origin.length) || '/';
|
|
207
|
+
const html = (r.headers['content-type'] ?? '').includes('text/html');
|
|
208
|
+
if (!html || req.method === 'HEAD') {
|
|
209
|
+
res.writeHead(r.statusCode ?? 502, h);
|
|
210
|
+
return void r.pipe(res);
|
|
211
|
+
}
|
|
212
|
+
const chunks = [];
|
|
213
|
+
r.on('data', (c) => chunks.push(c));
|
|
214
|
+
r.on('end', () => {
|
|
215
|
+
let s = Buffer.concat(chunks).toString('utf8');
|
|
216
|
+
const tag = `<script src="${SCRIPT_PATH}" defer></script>`;
|
|
217
|
+
const i = s.lastIndexOf('</body>');
|
|
218
|
+
s = i >= 0 ? s.slice(0, i) + tag + s.slice(i) : s + tag;
|
|
219
|
+
// The overlay changes without the page changing: never let the browser reuse an old copy.
|
|
220
|
+
h['cache-control'] = 'no-store';
|
|
221
|
+
delete h['content-length'];
|
|
222
|
+
delete h.etag;
|
|
223
|
+
delete h['last-modified'];
|
|
224
|
+
res.writeHead(r.statusCode ?? 200, h);
|
|
225
|
+
res.end(s);
|
|
226
|
+
});
|
|
227
|
+
r.on('error', () => res.destroy());
|
|
228
|
+
});
|
|
229
|
+
up.on('error', () => {
|
|
230
|
+
if (res.headersSent)
|
|
231
|
+
return void res.destroy();
|
|
232
|
+
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
233
|
+
res.end(`pinwright: ${target} is not reachable. Start the site there, then reload.`);
|
|
234
|
+
});
|
|
235
|
+
req.pipe(up);
|
|
236
|
+
}
|
|
237
|
+
const server = http.createServer((req, res) => {
|
|
238
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
239
|
+
// Remote visitors (the shared link) need the token: from the link once, then from its cookie.
|
|
240
|
+
const auth = collab.authorized(req, url.searchParams);
|
|
241
|
+
if (auth === 'denied') {
|
|
242
|
+
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8' });
|
|
243
|
+
return void res.end('pinwright: this link is not valid anymore. Ask for a new one.');
|
|
244
|
+
}
|
|
245
|
+
if (auth === 'set-cookie') {
|
|
246
|
+
const token = url.searchParams.get('pw');
|
|
247
|
+
url.searchParams.delete('pw');
|
|
248
|
+
res.writeHead(302, { 'set-cookie': collab.cookie(req, token), location: url.pathname + url.search, 'cache-control': 'no-store' });
|
|
249
|
+
return void res.end();
|
|
250
|
+
}
|
|
251
|
+
if (!url.pathname.startsWith('/__pw/'))
|
|
252
|
+
return proxy(req, res);
|
|
253
|
+
const origin = req.headers.origin;
|
|
254
|
+
// Local pages must come from localhost; remote ones already proved the token (SameSite cookie).
|
|
255
|
+
if (!isRemote(req) && !isLocal(origin))
|
|
256
|
+
return json(res, { error: 'forbidden origin' }, 403);
|
|
257
|
+
if (origin) {
|
|
258
|
+
res.setHeader('access-control-allow-origin', origin);
|
|
259
|
+
res.setHeader('vary', 'origin');
|
|
260
|
+
}
|
|
261
|
+
if (req.method === 'OPTIONS') {
|
|
262
|
+
res.writeHead(204, { 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS', 'access-control-allow-headers': 'content-type', 'access-control-max-age': '600' });
|
|
263
|
+
return void res.end();
|
|
264
|
+
}
|
|
265
|
+
api(req, res, url).catch((e) => {
|
|
266
|
+
const err = e instanceof OpError ? e : new OpError(e?.message ?? String(e), 500);
|
|
267
|
+
if (err.code >= 500)
|
|
268
|
+
cfg.log(`api ${req.method} ${url.pathname}: ${e?.stack ?? e}`);
|
|
269
|
+
if (!res.headersSent)
|
|
270
|
+
json(res, { error: err.message, ...(err.data ? { data: err.data } : {}) }, err.code);
|
|
271
|
+
else
|
|
272
|
+
res.destroy();
|
|
273
|
+
});
|
|
274
|
+
});
|
|
275
|
+
/** The live channel: note events out, cursors both ways, presence. One per open page. */
|
|
276
|
+
function live(req, socket, url) {
|
|
277
|
+
const guest = isRemote(req);
|
|
278
|
+
if (!guest && !isLocal(req.headers.origin))
|
|
279
|
+
return void socket.destroy();
|
|
280
|
+
const conn = acceptWs(req, socket);
|
|
281
|
+
if (!conn)
|
|
282
|
+
return void socket.destroy();
|
|
283
|
+
const pid = url.searchParams.get('pid')?.slice(0, 40) || null;
|
|
284
|
+
const me = pid ? collab.join(pid, guest, url.searchParams.get('page'), url.searchParams.get('name')) : null;
|
|
285
|
+
if (pid && !me) {
|
|
286
|
+
conn.send(JSON.stringify({ event: 'full', data: {} }));
|
|
287
|
+
return void conn.close();
|
|
288
|
+
}
|
|
289
|
+
const hello = { activity: Object.fromEntries(bus.activity), me, peers: collab.list(), access: collab.access(req), share: guest ? null : sharePayload() };
|
|
290
|
+
conn.send(JSON.stringify({ event: 'hello', data: hello }));
|
|
291
|
+
clients.set(conn, { pid, guest });
|
|
292
|
+
send('peers', collab.list());
|
|
293
|
+
conn.on('message', (raw) => {
|
|
294
|
+
let m;
|
|
295
|
+
try {
|
|
296
|
+
m = JSON.parse(raw);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const peer = pid ? collab.peers.get(pid) : undefined;
|
|
302
|
+
if (m.t === 'name' && peer && typeof m.name === 'string') {
|
|
303
|
+
if (collab.rename(peer.id, m.name))
|
|
304
|
+
send('peers', collab.list());
|
|
305
|
+
else
|
|
306
|
+
conn.send(JSON.stringify({ event: 'peers', data: collab.list() }));
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
if (m.t === 'cursor' && peer) {
|
|
310
|
+
if (typeof m.page === 'string')
|
|
311
|
+
peer.page = m.page;
|
|
312
|
+
const { t: _t, ...rest } = m;
|
|
313
|
+
send('cursor', { ...rest, pid, name: peer.name, color: peer.color }, (c) => c.pid !== pid);
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
conn.on('close', () => {
|
|
317
|
+
clients.delete(conn);
|
|
318
|
+
// Another channel of the same tab may still be open (a reload overlaps the old one).
|
|
319
|
+
if (pid && ![...clients.values()].some((c) => c.pid === pid))
|
|
320
|
+
collab.leave(pid, () => send('peers', collab.list()));
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
server.on('upgrade', (req, socket, head) => {
|
|
324
|
+
const url = new URL(req.url ?? '/', 'http://x');
|
|
325
|
+
if (collab.authorized(req, url.searchParams) !== 'ok')
|
|
326
|
+
return void socket.destroy();
|
|
327
|
+
if (url.pathname === '/__pw/ws')
|
|
328
|
+
return live(req, socket, url);
|
|
329
|
+
// HMR and other websockets go straight through to the target.
|
|
330
|
+
const target = cfg.target ?? cfg.siteUrl;
|
|
331
|
+
if (!target)
|
|
332
|
+
return void socket.destroy();
|
|
333
|
+
const t = new URL(target);
|
|
334
|
+
const up = net.connect(Number(t.port || 80), t.hostname, () => {
|
|
335
|
+
const lines = [`${req.method} ${req.url} HTTP/1.1`];
|
|
336
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) {
|
|
337
|
+
const k = req.rawHeaders[i];
|
|
338
|
+
lines.push(`${k}: ${k.toLowerCase() === 'host' ? t.host : req.rawHeaders[i + 1]}`);
|
|
339
|
+
}
|
|
340
|
+
up.write(`${lines.join('\r\n')}\r\n\r\n`);
|
|
341
|
+
if (head.length)
|
|
342
|
+
up.write(head);
|
|
343
|
+
up.pipe(socket);
|
|
344
|
+
socket.pipe(up);
|
|
345
|
+
});
|
|
346
|
+
up.on('error', () => socket.destroy());
|
|
347
|
+
socket.on('error', () => up.destroy());
|
|
348
|
+
});
|
|
349
|
+
server.on('close', () => {
|
|
350
|
+
clearInterval(ping);
|
|
351
|
+
for (const c of clients.keys())
|
|
352
|
+
c.close();
|
|
353
|
+
});
|
|
354
|
+
return server;
|
|
355
|
+
}
|
package/dist/shots.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Config, Viewport } from './config.js';
|
|
2
|
+
export interface Shot {
|
|
3
|
+
file: string;
|
|
4
|
+
data: Buffer;
|
|
5
|
+
viewport: Viewport;
|
|
6
|
+
}
|
|
7
|
+
/** Parses "390x844" from the overlay. */
|
|
8
|
+
export declare function parseViewport(v: string | null | undefined, name?: string): Viewport | null;
|
|
9
|
+
/** One shared headless Chrome, launched on first use and closed with the daemon. */
|
|
10
|
+
export declare class Shooter {
|
|
11
|
+
private cfg;
|
|
12
|
+
private browser;
|
|
13
|
+
private warned;
|
|
14
|
+
constructor(cfg: Config);
|
|
15
|
+
get dir(): string;
|
|
16
|
+
private launch;
|
|
17
|
+
/** The site URL for a page, without the overlay (screenshots load the target directly). */
|
|
18
|
+
urlFor(page: string, fallback?: string | null): string | null;
|
|
19
|
+
capture(url: string, viewport: Viewport, opts: {
|
|
20
|
+
selector?: string | null;
|
|
21
|
+
tag: string;
|
|
22
|
+
noteId: string;
|
|
23
|
+
}): Promise<Shot | null>;
|
|
24
|
+
close(): Promise<void>;
|
|
25
|
+
}
|
package/dist/shots.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
/** Parses "390x844" from the overlay. */
|
|
4
|
+
export function parseViewport(v, name = 'note') {
|
|
5
|
+
const m = v?.match(/^(\d+)x(\d+)$/);
|
|
6
|
+
return m ? { name, width: Number(m[1]), height: Number(m[2]) } : null;
|
|
7
|
+
}
|
|
8
|
+
/** One shared headless Chrome, launched on first use and closed with the daemon. */
|
|
9
|
+
export class Shooter {
|
|
10
|
+
cfg;
|
|
11
|
+
browser = null;
|
|
12
|
+
warned = false;
|
|
13
|
+
constructor(cfg) {
|
|
14
|
+
this.cfg = cfg;
|
|
15
|
+
}
|
|
16
|
+
get dir() {
|
|
17
|
+
return join(this.cfg.root, '.pinwright', 'shots');
|
|
18
|
+
}
|
|
19
|
+
launch() {
|
|
20
|
+
if (!this.browser) {
|
|
21
|
+
this.browser = (async () => {
|
|
22
|
+
try {
|
|
23
|
+
const pw = (await import('playwright-core'));
|
|
24
|
+
return await pw.chromium.launch({ channel: 'chrome', headless: true });
|
|
25
|
+
}
|
|
26
|
+
catch (e) {
|
|
27
|
+
if (!this.warned)
|
|
28
|
+
this.cfg.log(`screenshots off: ${e.message.split('\n')[0]}`);
|
|
29
|
+
this.warned = true;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
})();
|
|
33
|
+
}
|
|
34
|
+
return this.browser.then(async (b) => {
|
|
35
|
+
if (b && !b.isConnected()) {
|
|
36
|
+
this.browser = null;
|
|
37
|
+
return this.launch();
|
|
38
|
+
}
|
|
39
|
+
return b;
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** The site URL for a page, without the overlay (screenshots load the target directly). */
|
|
43
|
+
urlFor(page, fallback) {
|
|
44
|
+
if (this.cfg.siteUrl)
|
|
45
|
+
return this.cfg.siteUrl + (page.startsWith('/') ? page : `/${page}`);
|
|
46
|
+
return fallback ?? null;
|
|
47
|
+
}
|
|
48
|
+
async capture(url, viewport, opts) {
|
|
49
|
+
if (!this.cfg.shots)
|
|
50
|
+
return null;
|
|
51
|
+
const browser = await this.launch();
|
|
52
|
+
if (!browser)
|
|
53
|
+
return null;
|
|
54
|
+
// Wide viewports render at a lower device scale so the image stays around 800px wide.
|
|
55
|
+
const scale = Math.min(1, 800 / viewport.width);
|
|
56
|
+
const ctx = await browser.newContext({ viewport: { width: viewport.width, height: viewport.height }, deviceScaleFactor: scale });
|
|
57
|
+
try {
|
|
58
|
+
const page = await ctx.newPage();
|
|
59
|
+
try {
|
|
60
|
+
await page.goto(url, { waitUntil: 'networkidle', timeout: 30_000 });
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
await page.goto(url, { waitUntil: 'load', timeout: 30_000 });
|
|
64
|
+
}
|
|
65
|
+
if (opts.selector) {
|
|
66
|
+
try {
|
|
67
|
+
await page.locator(opts.selector).first().scrollIntoViewIfNeeded({ timeout: 3000 });
|
|
68
|
+
}
|
|
69
|
+
catch { }
|
|
70
|
+
}
|
|
71
|
+
await page.waitForTimeout(400);
|
|
72
|
+
const data = await page.screenshot({ type: 'jpeg', quality: 60 });
|
|
73
|
+
const file = `${opts.noteId}-${opts.tag}-${viewport.name}-${Date.now().toString(36)}.jpg`;
|
|
74
|
+
writeFileSync(join(this.dir, file), data);
|
|
75
|
+
return { file, data, viewport };
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await ctx.close().catch(() => { });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async close() {
|
|
82
|
+
const b = await this.browser?.catch(() => null);
|
|
83
|
+
this.browser = null;
|
|
84
|
+
await b?.close().catch(() => { });
|
|
85
|
+
}
|
|
86
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
import type { Bus } from './bus.js';
|
|
3
|
+
export type Status = 'queued' | 'planning' | 'working' | 'done' | 'asking' | 'handoff' | 'failed' | 'archived' | 'undone' | 'taken' | 'deleted';
|
|
4
|
+
/** Statuses the overlay still shows as pins. */
|
|
5
|
+
export declare const VISIBLE: Status[];
|
|
6
|
+
export interface Shots {
|
|
7
|
+
before: string[];
|
|
8
|
+
after: string[];
|
|
9
|
+
}
|
|
10
|
+
export interface Note {
|
|
11
|
+
id: string;
|
|
12
|
+
page: string;
|
|
13
|
+
url: string | null;
|
|
14
|
+
selector: string | null;
|
|
15
|
+
element: string | null;
|
|
16
|
+
html: string | null;
|
|
17
|
+
styles: Record<string, string> | null;
|
|
18
|
+
fx: number | null;
|
|
19
|
+
fy: number | null;
|
|
20
|
+
pageX: number | null;
|
|
21
|
+
pageY: number | null;
|
|
22
|
+
viewport: string | null;
|
|
23
|
+
text: string;
|
|
24
|
+
author: string | null;
|
|
25
|
+
approved: boolean;
|
|
26
|
+
/** Someone on a shared link wrote it, or replied to it: the agent works under the guest rules. */
|
|
27
|
+
guest: boolean;
|
|
28
|
+
status: Status;
|
|
29
|
+
area: string[] | null;
|
|
30
|
+
sessionId: string | null;
|
|
31
|
+
attempts: number;
|
|
32
|
+
summary: string | null;
|
|
33
|
+
diff: string | null;
|
|
34
|
+
shots: Shots;
|
|
35
|
+
costUsd: number;
|
|
36
|
+
/** All tokens of the note's session: input, output, cache reads and writes. */
|
|
37
|
+
tokens: number;
|
|
38
|
+
createdAt: string;
|
|
39
|
+
updatedAt: string;
|
|
40
|
+
startedAt: string | null;
|
|
41
|
+
}
|
|
42
|
+
export interface Message {
|
|
43
|
+
id: number;
|
|
44
|
+
noteId: string;
|
|
45
|
+
role: 'user' | 'agent' | 'system';
|
|
46
|
+
text: string;
|
|
47
|
+
/** Who wrote it, for user messages in a live session (the made-up name). */
|
|
48
|
+
author: string | null;
|
|
49
|
+
at: string;
|
|
50
|
+
}
|
|
51
|
+
export interface Change {
|
|
52
|
+
noteId: string;
|
|
53
|
+
file: string;
|
|
54
|
+
original: string | null;
|
|
55
|
+
final: string | null;
|
|
56
|
+
}
|
|
57
|
+
export type NewNote = Pick<Note, 'page' | 'text'> & Partial<Pick<Note, 'url' | 'selector' | 'element' | 'html' | 'styles' | 'fx' | 'fy' | 'pageX' | 'pageY' | 'viewport' | 'author' | 'approved' | 'guest'>>;
|
|
58
|
+
export type Patch = Partial<Pick<Note, 'status' | 'area' | 'sessionId' | 'attempts' | 'summary' | 'diff' | 'shots' | 'costUsd' | 'tokens' | 'startedAt' | 'approved' | 'guest' | 'text'>>;
|
|
59
|
+
export declare class Store {
|
|
60
|
+
private db;
|
|
61
|
+
private bus;
|
|
62
|
+
constructor(db: DatabaseSync, bus: Bus);
|
|
63
|
+
create(n: NewNote): Note;
|
|
64
|
+
get(id: string): Note | undefined;
|
|
65
|
+
/** Visible notes by default; pass statuses to filter otherwise. */
|
|
66
|
+
list(statuses?: Status[]): Note[];
|
|
67
|
+
update(id: string, patch: Patch): Note | undefined;
|
|
68
|
+
message(noteId: string, role: Message['role'], text: string, author?: string | null): void;
|
|
69
|
+
messages(noteId: string): Message[];
|
|
70
|
+
change(noteId: string, file: string): Change | undefined;
|
|
71
|
+
changes(noteId: string): Change[];
|
|
72
|
+
/** Remembers the file as it was before the note first touched it. Later calls keep the first original. */
|
|
73
|
+
recordOriginal(noteId: string, file: string, original: string | null): void;
|
|
74
|
+
setFinal(noteId: string, file: string, final: string | null): void;
|
|
75
|
+
dropChange(noteId: string, file: string): void;
|
|
76
|
+
}
|