brsh 2.7.0 → 2.8.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/vitest.config.js CHANGED
@@ -1,6 +1,12 @@
1
1
  import { defineConfig } from 'vitest/config';
2
+ import path from 'path';
2
3
 
3
4
  export default defineConfig({
5
+ resolve: {
6
+ alias: {
7
+ 'brsh': path.resolve(import.meta.dirname, 'index.js')
8
+ }
9
+ },
4
10
  test: {
5
11
  environment: 'node',
6
12
  globals: false,
package/lib/wbt/daemon.js DELETED
@@ -1,264 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Daemon & Virtual Localhost Server Registry for WBT / brsh.
5
- *
6
- * Allows WASM packages (such as `pglite` / `pg_ctl` or custom WASM servers) to:
7
- * 1. Register background daemon processes on a virtual localhost port (e.g. 5432)
8
- * 2. Optionally bind a real Node `http.Server` or `net.Server` when running in Node
9
- * 3. Intercept `fetch('http://localhost:<port>/...')` or `fetch('http://127.0.0.1:<port>/...')`
10
- * in the browser or Node so `curl http://localhost:5432/query -d "SELECT 1"` and web app
11
- * `fetch()` calls hit the running WASM daemon directly!
12
- */
13
- class DaemonManager {
14
- constructor() {
15
- this._daemons = new Map(); // id/port -> daemon entry
16
- this._nextPid = 1001;
17
- this._fetchPatched = false;
18
- this._originalFetch = null;
19
- }
20
-
21
- /**
22
- * Registers and starts a background daemon.
23
- *
24
- * @param {Object} opts
25
- * @param {string} opts.name - Daemon name (e.g. 'pglite')
26
- * @param {number} opts.port - Port number (e.g. 5432)
27
- * @param {string} [opts.host='127.0.0.1'] - Bind address
28
- * @param {string} [opts.dataDir] - Associated data directory or target
29
- * @param {Function} opts.handler - async ({ method, url, path, headers, body }) => { status, statusText, headers, body }
30
- * @param {Function} [opts.onStop] - async cleanup callback when daemon is stopped
31
- * @param {Object} [opts.instance] - Underlying WASM instance (e.g. PGlite db)
32
- * @param {Object} [opts.fs] - Optional brsh filesystem to write PID file
33
- * @param {string} [opts.pidFile] - Optional path to PID file (e.g. `/var/run/pglite.pid`)
34
- */
35
- async startDaemon(opts) {
36
- const {
37
- name,
38
- port = 5432,
39
- host = '127.0.0.1',
40
- dataDir = 'memory://',
41
- handler,
42
- onStop,
43
- instance,
44
- fs,
45
- pidFile
46
- } = opts;
47
-
48
- const numericPort = Number(port);
49
- if (this._daemons.has(numericPort)) {
50
- throw new Error(`Port ${numericPort} is already in use by daemon '${this._daemons.get(numericPort).name}' (PID ${this._daemons.get(numericPort).pid})`);
51
- }
52
-
53
- const pid = this._nextPid++;
54
- let nodeHttpServer = null;
55
-
56
- // Ensure global fetch intercepts http://localhost:<port> and http://127.0.0.1:<port>
57
- this._ensureFetchInterceptor();
58
-
59
- // Also optionally bind a real Node http server if requested and in Node
60
- if (opts.bindNodeServer && typeof process !== 'undefined' && process.versions && process.versions.node) {
61
- try {
62
- const http = require('http');
63
- nodeHttpServer = http.createServer(async (req, res) => {
64
- try {
65
- const chunks = [];
66
- for await (const chunk of req) chunks.push(chunk);
67
- const rawBody = Buffer.concat(chunks).toString('utf8');
68
- const urlObj = new URL(req.url || '/', `http://${host}:${numericPort}`);
69
- const resp = await handler({
70
- method: req.method || 'GET',
71
- url: urlObj.toString(),
72
- path: urlObj.pathname,
73
- searchParams: urlObj.searchParams,
74
- headers: req.headers || {},
75
- body: rawBody
76
- });
77
- const status = (resp && resp.status) || 200;
78
- const respHeaders = Object.assign({
79
- 'content-type': 'application/json',
80
- 'access-control-allow-origin': '*'
81
- }, (resp && resp.headers) || {});
82
- res.writeHead(status, respHeaders);
83
- res.end(typeof resp.body === 'string' ? resp.body : JSON.stringify(resp.body ?? {}));
84
- } catch (err) {
85
- res.writeHead(500, { 'content-type': 'application/json' });
86
- res.end(JSON.stringify({ error: err.message || String(err) }));
87
- }
88
- });
89
- await new Promise((resolve) => {
90
- nodeHttpServer.once('error', () => {
91
- nodeHttpServer = null;
92
- resolve();
93
- });
94
- nodeHttpServer.listen(numericPort, host, () => resolve());
95
- });
96
- } catch {
97
- nodeHttpServer = null;
98
- }
99
- }
100
-
101
- const entry = {
102
- pid,
103
- name,
104
- port: numericPort,
105
- host,
106
- dataDir,
107
- startedAt: new Date().toISOString(),
108
- handler,
109
- onStop,
110
- instance,
111
- nodeHttpServer,
112
- pidFile,
113
- fs
114
- };
115
-
116
- this._daemons.set(numericPort, entry);
117
-
118
- if (fs && pidFile) {
119
- try {
120
- fs.setFileByPath(pidFile, JSON.stringify({
121
- pid,
122
- name,
123
- port: numericPort,
124
- host,
125
- dataDir,
126
- startedAt: entry.startedAt
127
- }, null, 2), true);
128
- } catch { /* ignore */ }
129
- }
130
-
131
- return entry;
132
- }
133
-
134
- async stopDaemon(portOrNameOrPid) {
135
- const entry = this.getDaemon(portOrNameOrPid);
136
- if (!entry) return null;
137
-
138
- this._daemons.delete(entry.port);
139
-
140
- if (entry.nodeHttpServer) {
141
- await new Promise(resolve => entry.nodeHttpServer.close(() => resolve()));
142
- }
143
-
144
- if (typeof entry.onStop === 'function') {
145
- try { await entry.onStop(entry); } catch { /* ignore */ }
146
- }
147
-
148
- if (entry.fs && entry.pidFile) {
149
- try { entry.fs.deleteFileByPath(entry.pidFile); } catch { /* ignore */ }
150
- }
151
-
152
- return entry;
153
- }
154
-
155
- async stopAll() {
156
- const ports = Array.from(this._daemons.keys());
157
- for (const p of ports) {
158
- await this.stopDaemon(p);
159
- }
160
- }
161
-
162
- getDaemon(portOrNameOrPid) {
163
- if (portOrNameOrPid === undefined || portOrNameOrPid === null) {
164
- // Return first daemon if only one is running
165
- if (this._daemons.size === 1) {
166
- return this._daemons.values().next().value;
167
- }
168
- return null;
169
- }
170
- const num = Number(portOrNameOrPid);
171
- if (!Number.isNaN(num) && this._daemons.has(num)) {
172
- return this._daemons.get(num);
173
- }
174
- for (const entry of this._daemons.values()) {
175
- if (entry.pid === num || entry.name === String(portOrNameOrPid).toLowerCase() || entry.dataDir === portOrNameOrPid) {
176
- return entry;
177
- }
178
- }
179
- return null;
180
- }
181
-
182
- listDaemons() {
183
- return Array.from(this._daemons.values());
184
- }
185
-
186
- _ensureFetchInterceptor() {
187
- if (this._fetchPatched || typeof globalThis.fetch !== 'function') return;
188
- const originalFetch = globalThis.fetch.bind(globalThis);
189
- this._originalFetch = originalFetch;
190
- const self = this;
191
-
192
- const patchedFetch = async function wbtDaemonFetch(input, init = {}) {
193
- const urlStr = typeof input === 'string'
194
- ? input
195
- : (input && typeof input.url === 'string' ? input.url : String(input));
196
-
197
- const match = urlStr.match(/^https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):(\d+)(\/.*)?$/i);
198
- if (match) {
199
- const port = Number(match[1]);
200
- const daemon = self._daemons.get(port);
201
- if (daemon && typeof daemon.handler === 'function') {
202
- const urlObj = new URL(urlStr);
203
- const method = (init.method || (input && input.method) || 'GET').toUpperCase();
204
- const headers = {};
205
- if (init.headers) {
206
- if (typeof init.headers.forEach === 'function') {
207
- init.headers.forEach((v, k) => { headers[k.toLowerCase()] = v; });
208
- } else if (typeof init.headers === 'object') {
209
- for (const [k, v] of Object.entries(init.headers)) {
210
- headers[k.toLowerCase()] = v;
211
- }
212
- }
213
- }
214
- const body = init.body !== undefined && init.body !== null ? String(init.body) : null;
215
-
216
- const resp = await daemon.handler({
217
- method,
218
- url: urlStr,
219
- path: urlObj.pathname,
220
- searchParams: urlObj.searchParams,
221
- headers,
222
- body
223
- });
224
-
225
- const status = (resp && resp.status) || 200;
226
- const statusText = (resp && resp.statusText) || (status === 200 ? 'OK' : 'Error');
227
- const respBody = typeof resp?.body === 'string'
228
- ? resp.body
229
- : JSON.stringify(resp?.body ?? {});
230
- const respHeaders = new Map(Object.entries(Object.assign({
231
- 'content-type': 'application/json',
232
- 'x-powered-by': `${daemon.name}-wasm-daemon`
233
- }, (resp && resp.headers) || {})));
234
-
235
- return {
236
- ok: status >= 200 && status < 300,
237
- status,
238
- statusText,
239
- headers: {
240
- get: (k) => respHeaders.get(String(k).toLowerCase()) || null,
241
- forEach: (cb) => respHeaders.forEach((v, k) => cb(v, k))
242
- },
243
- text: async () => respBody,
244
- json: async () => JSON.parse(respBody),
245
- arrayBuffer: async () => new TextEncoder().encode(respBody).buffer
246
- };
247
- }
248
- }
249
-
250
- return originalFetch(input, init);
251
- };
252
-
253
- patchedFetch.__isWbtDaemonFetch = true;
254
- globalThis.fetch = patchedFetch;
255
- this._fetchPatched = true;
256
- }
257
- }
258
-
259
- const daemonManager = new DaemonManager();
260
-
261
- module.exports = {
262
- DaemonManager,
263
- daemonManager
264
- };