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/store.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
/** Statuses the overlay still shows as pins. */
|
|
3
|
+
export const VISIBLE = ['queued', 'planning', 'working', 'done', 'asking', 'handoff', 'failed'];
|
|
4
|
+
const now = () => new Date().toISOString();
|
|
5
|
+
const id = () => Date.now().toString(36).slice(-5) + randomBytes(2).toString('hex');
|
|
6
|
+
const parse = (s, fallback) => {
|
|
7
|
+
if (typeof s !== 'string' || !s)
|
|
8
|
+
return fallback;
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(s);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return fallback;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
function toNote(r) {
|
|
17
|
+
return {
|
|
18
|
+
id: r.id,
|
|
19
|
+
page: r.page,
|
|
20
|
+
url: r.url ?? null,
|
|
21
|
+
selector: r.selector ?? null,
|
|
22
|
+
element: r.element ?? null,
|
|
23
|
+
html: r.html ?? null,
|
|
24
|
+
styles: parse(r.styles, null),
|
|
25
|
+
fx: r.fx ?? null,
|
|
26
|
+
fy: r.fy ?? null,
|
|
27
|
+
pageX: r.page_x ?? null,
|
|
28
|
+
pageY: r.page_y ?? null,
|
|
29
|
+
viewport: r.viewport ?? null,
|
|
30
|
+
text: r.text,
|
|
31
|
+
author: r.author ?? null,
|
|
32
|
+
approved: Boolean(r.approved),
|
|
33
|
+
guest: Boolean(r.guest),
|
|
34
|
+
status: r.status,
|
|
35
|
+
area: parse(r.area, null),
|
|
36
|
+
sessionId: r.session_id ?? null,
|
|
37
|
+
attempts: r.attempts,
|
|
38
|
+
summary: r.summary ?? null,
|
|
39
|
+
diff: r.diff ?? null,
|
|
40
|
+
shots: parse(r.shots, { before: [], after: [] }),
|
|
41
|
+
costUsd: r.cost_usd,
|
|
42
|
+
tokens: r.tokens ?? 0,
|
|
43
|
+
createdAt: r.created_at,
|
|
44
|
+
updatedAt: r.updated_at,
|
|
45
|
+
startedAt: r.started_at ?? null,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
const COLUMNS = {
|
|
49
|
+
status: 'status',
|
|
50
|
+
area: 'area',
|
|
51
|
+
sessionId: 'session_id',
|
|
52
|
+
attempts: 'attempts',
|
|
53
|
+
summary: 'summary',
|
|
54
|
+
diff: 'diff',
|
|
55
|
+
shots: 'shots',
|
|
56
|
+
costUsd: 'cost_usd',
|
|
57
|
+
tokens: 'tokens',
|
|
58
|
+
startedAt: 'started_at',
|
|
59
|
+
approved: 'approved',
|
|
60
|
+
guest: 'guest',
|
|
61
|
+
text: 'text',
|
|
62
|
+
};
|
|
63
|
+
const JSON_COLS = new Set(['area', 'shots']);
|
|
64
|
+
export class Store {
|
|
65
|
+
db;
|
|
66
|
+
bus;
|
|
67
|
+
constructor(db, bus) {
|
|
68
|
+
this.db = db;
|
|
69
|
+
this.bus = bus;
|
|
70
|
+
}
|
|
71
|
+
create(n) {
|
|
72
|
+
const t = now();
|
|
73
|
+
const note = {
|
|
74
|
+
id: id(),
|
|
75
|
+
page: n.page,
|
|
76
|
+
url: n.url ?? null,
|
|
77
|
+
selector: n.selector ?? null,
|
|
78
|
+
element: n.element?.slice(0, 300) ?? null,
|
|
79
|
+
html: n.html?.slice(0, 1500) ?? null,
|
|
80
|
+
styles: n.styles ? JSON.stringify(n.styles) : null,
|
|
81
|
+
fx: n.fx ?? null,
|
|
82
|
+
fy: n.fy ?? null,
|
|
83
|
+
page_x: n.pageX ?? null,
|
|
84
|
+
page_y: n.pageY ?? null,
|
|
85
|
+
viewport: n.viewport ?? null,
|
|
86
|
+
text: n.text,
|
|
87
|
+
author: n.author ?? null,
|
|
88
|
+
approved: n.approved === false ? 0 : 1,
|
|
89
|
+
guest: n.guest ? 1 : 0,
|
|
90
|
+
created_at: t,
|
|
91
|
+
updated_at: t,
|
|
92
|
+
};
|
|
93
|
+
const cols = Object.keys(note);
|
|
94
|
+
this.db.prepare(`INSERT INTO notes (${cols.join(',')}) VALUES (${cols.map((c) => `:${c}`).join(',')})`).run(note);
|
|
95
|
+
this.message(note.id, 'user', n.text, n.author ?? null);
|
|
96
|
+
const created = this.get(note.id);
|
|
97
|
+
this.bus.emit('note', created);
|
|
98
|
+
return created;
|
|
99
|
+
}
|
|
100
|
+
get(id) {
|
|
101
|
+
const r = this.db.prepare('SELECT * FROM notes WHERE id = ?').get(id);
|
|
102
|
+
return r && toNote(r);
|
|
103
|
+
}
|
|
104
|
+
/** Visible notes by default; pass statuses to filter otherwise. */
|
|
105
|
+
list(statuses = VISIBLE) {
|
|
106
|
+
const rows = this.db
|
|
107
|
+
.prepare(`SELECT * FROM notes WHERE status IN (${statuses.map(() => '?').join(',')}) ORDER BY created_at`)
|
|
108
|
+
.all(...statuses);
|
|
109
|
+
return rows.map(toNote);
|
|
110
|
+
}
|
|
111
|
+
update(id, patch) {
|
|
112
|
+
const sets = ['updated_at = :updated_at'];
|
|
113
|
+
const params = { id, updated_at: now() };
|
|
114
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
115
|
+
const col = COLUMNS[k];
|
|
116
|
+
if (!col || v === undefined)
|
|
117
|
+
continue;
|
|
118
|
+
sets.push(`${col} = :${col}`);
|
|
119
|
+
params[col] = JSON_COLS.has(k) ? (v === null ? null : JSON.stringify(v)) : typeof v === 'boolean' ? Number(v) : v;
|
|
120
|
+
}
|
|
121
|
+
this.db.prepare(`UPDATE notes SET ${sets.join(', ')} WHERE id = :id`).run(params);
|
|
122
|
+
const note = this.get(id);
|
|
123
|
+
if (note)
|
|
124
|
+
this.bus.emit('note', note);
|
|
125
|
+
return note;
|
|
126
|
+
}
|
|
127
|
+
message(noteId, role, text, author = null) {
|
|
128
|
+
this.db.prepare('INSERT INTO messages (note_id, role, text, author, at) VALUES (?, ?, ?, ?, ?)').run(noteId, role, text, author, now());
|
|
129
|
+
}
|
|
130
|
+
messages(noteId) {
|
|
131
|
+
const rows = this.db.prepare('SELECT * FROM messages WHERE note_id = ? ORDER BY id').all(noteId);
|
|
132
|
+
return rows.map((r) => ({
|
|
133
|
+
id: r.id,
|
|
134
|
+
noteId: r.note_id,
|
|
135
|
+
role: r.role,
|
|
136
|
+
text: r.text,
|
|
137
|
+
author: r.author ?? null,
|
|
138
|
+
at: r.at,
|
|
139
|
+
}));
|
|
140
|
+
}
|
|
141
|
+
change(noteId, file) {
|
|
142
|
+
const r = this.db.prepare('SELECT * FROM changes WHERE note_id = ? AND file = ?').get(noteId, file);
|
|
143
|
+
return r && { noteId, file, original: r.original ?? null, final: r.final ?? null };
|
|
144
|
+
}
|
|
145
|
+
changes(noteId) {
|
|
146
|
+
const rows = this.db.prepare('SELECT * FROM changes WHERE note_id = ? ORDER BY file').all(noteId);
|
|
147
|
+
return rows.map((r) => ({ noteId, file: r.file, original: r.original ?? null, final: r.final ?? null }));
|
|
148
|
+
}
|
|
149
|
+
/** Remembers the file as it was before the note first touched it. Later calls keep the first original. */
|
|
150
|
+
recordOriginal(noteId, file, original) {
|
|
151
|
+
this.db.prepare('INSERT OR IGNORE INTO changes (note_id, file, original, final) VALUES (?, ?, ?, ?)').run(noteId, file, original, original);
|
|
152
|
+
}
|
|
153
|
+
setFinal(noteId, file, final) {
|
|
154
|
+
this.db.prepare('UPDATE changes SET final = ? WHERE note_id = ? AND file = ?').run(final, noteId, file);
|
|
155
|
+
}
|
|
156
|
+
dropChange(noteId, file) {
|
|
157
|
+
this.db.prepare('DELETE FROM changes WHERE note_id = ? AND file = ?').run(noteId, file);
|
|
158
|
+
}
|
|
159
|
+
}
|
package/dist/tools.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Ctx } from './context.js';
|
|
2
|
+
import type { Note } from './store.js';
|
|
3
|
+
export interface Outcome {
|
|
4
|
+
kind: 'done' | 'ask' | 'handoff';
|
|
5
|
+
text: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const TOOL_NAMES: string[];
|
|
8
|
+
/** The in-process MCP server one note's agent talks through. `outcome` is set by the note_* tools. */
|
|
9
|
+
export declare function noteServer(ctx: Ctx, _note: Note, state: {
|
|
10
|
+
outcome: Outcome | null;
|
|
11
|
+
}): import("@anthropic-ai/claude-agent-sdk").McpSdkServerConfigWithInstance;
|
package/dist/tools.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
const text = (t) => ({ content: [{ type: 'text', text: t }] });
|
|
4
|
+
export const TOOL_NAMES = ['note_done', 'note_ask', 'note_handoff'].map((t) => `mcp__pinwright__${t}`);
|
|
5
|
+
const askTool = (state, lang) => tool('note_ask', 'Ask the reviewer ONE short question when the note is ambiguous. Then end your turn: you will be resumed with the answer.', { question: z.string().describe(`The question, in ${lang}.`) }, async ({ question }) => {
|
|
6
|
+
state.outcome = { kind: 'ask', text: question };
|
|
7
|
+
return text('Question sent. End your turn now and wait for the answer.');
|
|
8
|
+
});
|
|
9
|
+
/** The in-process MCP server one note's agent talks through. `outcome` is set by the note_* tools. */
|
|
10
|
+
export function noteServer(ctx, _note, state) {
|
|
11
|
+
const { cfg } = ctx;
|
|
12
|
+
return createSdkMcpServer({
|
|
13
|
+
name: 'pinwright',
|
|
14
|
+
version: '0.1.0',
|
|
15
|
+
tools: [
|
|
16
|
+
...(cfg.ask ? [askTool(state, cfg.lang)] : []),
|
|
17
|
+
tool('note_done', 'Call when the note is handled. Then end your turn.', { summary: z.string().describe(`One or two lines for the reviewer, in ${cfg.lang}: what you changed.`) }, async ({ summary }) => {
|
|
18
|
+
state.outcome = { kind: 'done', text: summary };
|
|
19
|
+
return text('Recorded. End your turn now.');
|
|
20
|
+
}),
|
|
21
|
+
tool('note_handoff', 'The note needs more than a small focused change (redesign, many pages, a new feature): hand it to a human-driven session. Then stop.', { reason: z.string().describe(`One line, in ${cfg.lang}: why and what it would take.`) }, async ({ reason }) => {
|
|
22
|
+
state.outcome = { kind: 'handoff', text: reason };
|
|
23
|
+
return text('Handed off. Stop now.');
|
|
24
|
+
}),
|
|
25
|
+
],
|
|
26
|
+
});
|
|
27
|
+
}
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { Options, Pinwright } from './index.js';
|
|
3
|
+
export { currentDaemon, ensureDaemon, releaseDaemon } from './plugin.js';
|
|
4
|
+
type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
|
|
5
|
+
interface DevServer {
|
|
6
|
+
httpServer: {
|
|
7
|
+
once(e: 'listening', f: () => void): void;
|
|
8
|
+
on(e: 'close', f: () => void): void;
|
|
9
|
+
} | null;
|
|
10
|
+
resolvedUrls?: {
|
|
11
|
+
local: string[];
|
|
12
|
+
} | null;
|
|
13
|
+
middlewares?: {
|
|
14
|
+
use(fn: Middleware): void;
|
|
15
|
+
};
|
|
16
|
+
config: {
|
|
17
|
+
server: {
|
|
18
|
+
port?: number;
|
|
19
|
+
https?: unknown;
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** Points screenshots at the dev server once it listens. */
|
|
24
|
+
export declare function trackSiteUrl(server: DevServer, pw: Pinwright, explicit?: string): void;
|
|
25
|
+
/**
|
|
26
|
+
* Vite plugin: starts pinwright with `vite dev` and puts the overlay in every HTML page the dev server sends:
|
|
27
|
+
* plain index.html apps and the SSR frameworks built on Vite (SvelteKit, React Router, SolidStart, Qwik…).
|
|
28
|
+
*/
|
|
29
|
+
export default function pinwright(opts?: Options): {
|
|
30
|
+
name: string;
|
|
31
|
+
apply: 'serve';
|
|
32
|
+
configureServer(server: DevServer): Promise<void>;
|
|
33
|
+
};
|
package/dist/vite.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { injectIntoHtml } from './inject.js';
|
|
2
|
+
import { releaseDaemon, scriptTag, tryDaemon } from './plugin.js';
|
|
3
|
+
export { currentDaemon, ensureDaemon, releaseDaemon } from './plugin.js';
|
|
4
|
+
/** Points screenshots at the dev server once it listens. */
|
|
5
|
+
export function trackSiteUrl(server, pw, explicit) {
|
|
6
|
+
if (explicit)
|
|
7
|
+
return;
|
|
8
|
+
server.httpServer?.once('listening', () => {
|
|
9
|
+
const u = server.resolvedUrls?.local[0];
|
|
10
|
+
if (u)
|
|
11
|
+
pw.setSiteUrl(u);
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Vite plugin: starts pinwright with `vite dev` and puts the overlay in every HTML page the dev server sends:
|
|
16
|
+
* plain index.html apps and the SSR frameworks built on Vite (SvelteKit, React Router, SolidStart, Qwik…).
|
|
17
|
+
*/
|
|
18
|
+
export default function pinwright(opts = {}) {
|
|
19
|
+
let pw = null;
|
|
20
|
+
return {
|
|
21
|
+
name: 'pinwright',
|
|
22
|
+
apply: 'serve',
|
|
23
|
+
async configureServer(server) {
|
|
24
|
+
pw = await tryDaemon(opts);
|
|
25
|
+
if (!pw)
|
|
26
|
+
return;
|
|
27
|
+
trackSiteUrl(server, pw, opts.siteUrl);
|
|
28
|
+
server.httpServer?.on('close', releaseDaemon);
|
|
29
|
+
// Registered now, so it runs before the framework's own SSR handler and wraps its response.
|
|
30
|
+
const tag = scriptTag(pw.scriptUrl);
|
|
31
|
+
server.middlewares?.use((req, res, next) => {
|
|
32
|
+
injectIntoHtml(req, res, tag);
|
|
33
|
+
next();
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Options } from './index.js';
|
|
2
|
+
interface Hook<T extends unknown[] = unknown[]> {
|
|
3
|
+
tap(name: string, fn: (...a: T) => void): void;
|
|
4
|
+
tapPromise(name: string, fn: (...a: T) => Promise<void>): void;
|
|
5
|
+
}
|
|
6
|
+
interface Compiler {
|
|
7
|
+
context: string;
|
|
8
|
+
options: {
|
|
9
|
+
mode?: string;
|
|
10
|
+
};
|
|
11
|
+
hooks: {
|
|
12
|
+
watchRun: Hook;
|
|
13
|
+
watchClose: Hook;
|
|
14
|
+
shutdown?: Hook;
|
|
15
|
+
};
|
|
16
|
+
webpack?: {
|
|
17
|
+
EntryPlugin: new (context: string, entry: string, opts: {
|
|
18
|
+
name: undefined;
|
|
19
|
+
}) => {
|
|
20
|
+
apply(c: Compiler): void;
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
rspack?: Compiler['webpack'];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Webpack 5 / Rspack / Rsbuild plugin: in watch mode (dev server, `--watch`) starts pinwright and adds a tiny
|
|
27
|
+
* entry that loads the overlay on every page. Production builds are left alone.
|
|
28
|
+
*
|
|
29
|
+
* plugins: [new PinwrightPlugin()]
|
|
30
|
+
*/
|
|
31
|
+
export declare class PinwrightPlugin {
|
|
32
|
+
private opts;
|
|
33
|
+
constructor(opts?: Options);
|
|
34
|
+
apply(compiler: Compiler): void;
|
|
35
|
+
}
|
|
36
|
+
export default PinwrightPlugin;
|
package/dist/webpack.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { loaderCode, releaseDaemon, tryDaemon } from './plugin.js';
|
|
4
|
+
/**
|
|
5
|
+
* Webpack 5 / Rspack / Rsbuild plugin: in watch mode (dev server, `--watch`) starts pinwright and adds a tiny
|
|
6
|
+
* entry that loads the overlay on every page. Production builds are left alone.
|
|
7
|
+
*
|
|
8
|
+
* plugins: [new PinwrightPlugin()]
|
|
9
|
+
*/
|
|
10
|
+
export class PinwrightPlugin {
|
|
11
|
+
opts;
|
|
12
|
+
constructor(opts = {}) {
|
|
13
|
+
this.opts = opts;
|
|
14
|
+
}
|
|
15
|
+
apply(compiler) {
|
|
16
|
+
if (compiler.options.mode === 'production')
|
|
17
|
+
return;
|
|
18
|
+
const EntryPlugin = (compiler.rspack ?? compiler.webpack)?.EntryPlugin;
|
|
19
|
+
if (!EntryPlugin)
|
|
20
|
+
return console.error('[pinwright] not started: this bundler has no EntryPlugin (webpack 5 or rspack needed)');
|
|
21
|
+
const root = resolve(this.opts.root ?? compiler.context);
|
|
22
|
+
const file = join(root, '.pinwright', 'loader.js');
|
|
23
|
+
// Empty until the daemon is up: a one-off build (no watch) bundles nothing of pinwright.
|
|
24
|
+
write(file, '');
|
|
25
|
+
new EntryPlugin(compiler.context, file, { name: undefined }).apply(compiler);
|
|
26
|
+
let started = false;
|
|
27
|
+
compiler.hooks.watchRun.tapPromise('pinwright', async () => {
|
|
28
|
+
if (started)
|
|
29
|
+
return;
|
|
30
|
+
started = true;
|
|
31
|
+
const pw = await tryDaemon({ ...this.opts, root });
|
|
32
|
+
if (pw)
|
|
33
|
+
write(file, loaderCode(pw.scriptUrl) + '\n');
|
|
34
|
+
});
|
|
35
|
+
let released = false;
|
|
36
|
+
const release = () => {
|
|
37
|
+
if (!started || released)
|
|
38
|
+
return;
|
|
39
|
+
released = true;
|
|
40
|
+
write(file, '');
|
|
41
|
+
releaseDaemon();
|
|
42
|
+
};
|
|
43
|
+
compiler.hooks.watchClose.tap('pinwright', release);
|
|
44
|
+
compiler.hooks.shutdown?.tap('pinwright', release);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Writes only on change, so the bundler's watcher doesn't rebuild for nothing. */
|
|
48
|
+
function write(file, text) {
|
|
49
|
+
try {
|
|
50
|
+
if (readFileSync(file, 'utf8') === text)
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
mkdirSync(join(file, '..'), { recursive: true });
|
|
55
|
+
}
|
|
56
|
+
writeFileSync(file, text);
|
|
57
|
+
}
|
|
58
|
+
export default PinwrightPlugin;
|
package/dist/ws.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import type { IncomingMessage } from 'node:http';
|
|
3
|
+
import type { Duplex } from 'node:stream';
|
|
4
|
+
/**
|
|
5
|
+
* A minimal WebSocket (RFC 6455) server side: text messages, ping/pong, close. Enough for the live
|
|
6
|
+
* channel, with no dependency. Tunnels like cloudflared buffer SSE but pass WebSockets through.
|
|
7
|
+
*/
|
|
8
|
+
export declare class WsConn extends EventEmitter<{
|
|
9
|
+
message: [string];
|
|
10
|
+
close: [];
|
|
11
|
+
}> {
|
|
12
|
+
private socket;
|
|
13
|
+
private buf;
|
|
14
|
+
private parts;
|
|
15
|
+
private closed;
|
|
16
|
+
constructor(socket: Duplex);
|
|
17
|
+
private read;
|
|
18
|
+
private frame;
|
|
19
|
+
send(text: string): void;
|
|
20
|
+
ping(): void;
|
|
21
|
+
close(): void;
|
|
22
|
+
private end;
|
|
23
|
+
}
|
|
24
|
+
/** Completes the handshake; null when the request isn't a WebSocket upgrade. */
|
|
25
|
+
export declare function acceptWs(req: IncomingMessage, socket: Duplex): WsConn | null;
|
package/dist/ws.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
4
|
+
const MAX = 1 << 20;
|
|
5
|
+
/**
|
|
6
|
+
* A minimal WebSocket (RFC 6455) server side: text messages, ping/pong, close. Enough for the live
|
|
7
|
+
* channel, with no dependency. Tunnels like cloudflared buffer SSE but pass WebSockets through.
|
|
8
|
+
*/
|
|
9
|
+
export class WsConn extends EventEmitter {
|
|
10
|
+
socket;
|
|
11
|
+
buf = Buffer.alloc(0);
|
|
12
|
+
parts = [];
|
|
13
|
+
closed = false;
|
|
14
|
+
constructor(socket) {
|
|
15
|
+
super();
|
|
16
|
+
this.socket = socket;
|
|
17
|
+
socket.on('data', (d) => this.read(d));
|
|
18
|
+
socket.on('close', () => this.end());
|
|
19
|
+
socket.on('error', () => this.end());
|
|
20
|
+
}
|
|
21
|
+
read(d) {
|
|
22
|
+
this.buf = Buffer.concat([this.buf, d]);
|
|
23
|
+
while (this.buf.length >= 2) {
|
|
24
|
+
const b0 = this.buf[0];
|
|
25
|
+
const b1 = this.buf[1];
|
|
26
|
+
let len = b1 & 0x7f;
|
|
27
|
+
let off = 2;
|
|
28
|
+
if (len === 126) {
|
|
29
|
+
if (this.buf.length < 4)
|
|
30
|
+
return;
|
|
31
|
+
len = this.buf.readUInt16BE(2);
|
|
32
|
+
off = 4;
|
|
33
|
+
}
|
|
34
|
+
else if (len === 127) {
|
|
35
|
+
if (this.buf.length < 10)
|
|
36
|
+
return;
|
|
37
|
+
len = Number(this.buf.readBigUInt64BE(2));
|
|
38
|
+
off = 10;
|
|
39
|
+
}
|
|
40
|
+
if (len > MAX)
|
|
41
|
+
return this.close();
|
|
42
|
+
const masked = (b1 & 0x80) !== 0;
|
|
43
|
+
const total = off + (masked ? 4 : 0) + len;
|
|
44
|
+
if (this.buf.length < total)
|
|
45
|
+
return;
|
|
46
|
+
const payload = Buffer.from(this.buf.subarray(off + (masked ? 4 : 0), total));
|
|
47
|
+
if (masked) {
|
|
48
|
+
const mask = this.buf.subarray(off, off + 4);
|
|
49
|
+
for (let i = 0; i < payload.length; i++)
|
|
50
|
+
payload[i] ^= mask[i & 3];
|
|
51
|
+
}
|
|
52
|
+
this.buf = this.buf.subarray(total);
|
|
53
|
+
const fin = (b0 & 0x80) !== 0;
|
|
54
|
+
const op = b0 & 0x0f;
|
|
55
|
+
if (op === 0x8)
|
|
56
|
+
return this.close();
|
|
57
|
+
if (op === 0x9)
|
|
58
|
+
this.frame(0xa, payload);
|
|
59
|
+
else if (op === 0x1 || op === 0x0) {
|
|
60
|
+
this.parts.push(payload);
|
|
61
|
+
if (fin) {
|
|
62
|
+
const msg = Buffer.concat(this.parts).toString('utf8');
|
|
63
|
+
this.parts = [];
|
|
64
|
+
this.emit('message', msg);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
frame(op, payload) {
|
|
70
|
+
if (this.closed)
|
|
71
|
+
return;
|
|
72
|
+
const n = payload.length;
|
|
73
|
+
const head = n < 126 ? Buffer.from([0x80 | op, n]) : n < 65536 ? Buffer.alloc(4) : Buffer.alloc(10);
|
|
74
|
+
if (n >= 126 && n < 65536) {
|
|
75
|
+
head[0] = 0x80 | op;
|
|
76
|
+
head[1] = 126;
|
|
77
|
+
head.writeUInt16BE(n, 2);
|
|
78
|
+
}
|
|
79
|
+
else if (n >= 65536) {
|
|
80
|
+
head[0] = 0x80 | op;
|
|
81
|
+
head[1] = 127;
|
|
82
|
+
head.writeBigUInt64BE(BigInt(n), 2);
|
|
83
|
+
}
|
|
84
|
+
this.socket.write(Buffer.concat([head, payload]));
|
|
85
|
+
}
|
|
86
|
+
send(text) {
|
|
87
|
+
this.frame(0x1, Buffer.from(text, 'utf8'));
|
|
88
|
+
}
|
|
89
|
+
ping() {
|
|
90
|
+
this.frame(0x9, Buffer.alloc(0));
|
|
91
|
+
}
|
|
92
|
+
close() {
|
|
93
|
+
if (this.closed)
|
|
94
|
+
return;
|
|
95
|
+
this.frame(0x8, Buffer.alloc(0));
|
|
96
|
+
this.socket.end();
|
|
97
|
+
this.end();
|
|
98
|
+
}
|
|
99
|
+
end() {
|
|
100
|
+
if (this.closed)
|
|
101
|
+
return;
|
|
102
|
+
this.closed = true;
|
|
103
|
+
this.socket.destroy();
|
|
104
|
+
this.emit('close');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Completes the handshake; null when the request isn't a WebSocket upgrade. */
|
|
108
|
+
export function acceptWs(req, socket) {
|
|
109
|
+
const key = req.headers['sec-websocket-key'];
|
|
110
|
+
if (typeof key !== 'string' || (req.headers.upgrade ?? '').toLowerCase() !== 'websocket')
|
|
111
|
+
return null;
|
|
112
|
+
const accept = createHash('sha1').update(key + GUID).digest('base64');
|
|
113
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
|
|
114
|
+
return new WsConn(socket);
|
|
115
|
+
}
|