brsh 2.5.6 → 2.7.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.
@@ -0,0 +1,590 @@
1
+ 'use strict';
2
+
3
+ const Command = require('../../Command');
4
+ const ReplCommand = require('../../ReplCommand');
5
+ const { formatTable, formatPipeList, formatCsv, loadModule } = require('../utils');
6
+ const { daemonManager } = require('../daemon');
7
+
8
+ // Shared in-memory PGlite instances keyed by virtual dataDir path so state persists across invocations
9
+ const pgliteInstances = new Map();
10
+
11
+ /**
12
+ * Helper to initialize or retrieve a PGlite instance for a given dataDir and filesystem.
13
+ */
14
+ async function getOrInitPgliteInstance(rawDir, fs, pkgMeta, wbtConfig = {}) {
15
+ const mod = await loadModule('@electric-sql/pglite', pkgMeta.cdnUrl, wbtConfig.moduleLoader);
16
+ const PGlite = mod.PGlite || mod.default || mod;
17
+
18
+ if (!rawDir || rawDir === 'memory://' || rawDir === ':memory:') {
19
+ const pg = typeof PGlite.create === 'function' ? await PGlite.create() : new PGlite();
20
+ if (pg.waitReady) await pg.waitReady;
21
+ return { pg, isEphemeral: true, absDir: null };
22
+ }
23
+
24
+ const absDir = fs.absolutePath(rawDir);
25
+ if (pgliteInstances.has(absDir)) {
26
+ return { pg: pgliteInstances.get(absDir), isEphemeral: false, absDir };
27
+ }
28
+
29
+ if (fs.isRealFilesystem) {
30
+ const nodeFs = require('fs');
31
+ nodeFs.mkdirSync(absDir, { recursive: true });
32
+ const pg = typeof PGlite.create === 'function' ? await PGlite.create(absDir) : new PGlite(absDir);
33
+ if (pg.waitReady) await pg.waitReady;
34
+ pgliteInstances.set(absDir, pg);
35
+ return { pg, isEphemeral: false, absDir };
36
+ }
37
+
38
+ // Virtual filesystem: create directory marker + replay journal if present
39
+ if (!fs.exists(absDir)) {
40
+ fs.setFileByPath(absDir, {}, true);
41
+ }
42
+ const journalPath = `${absDir}/wal.sql`;
43
+ const pg = typeof PGlite.create === 'function' ? await PGlite.create() : new PGlite();
44
+ if (pg.waitReady) await pg.waitReady;
45
+
46
+ const existingWal = fs.getFileByPath(journalPath);
47
+ if (typeof existingWal === 'string' && existingWal.trim()) {
48
+ try {
49
+ await pg.exec(existingWal);
50
+ } catch {
51
+ // ignore replay errors
52
+ }
53
+ }
54
+ pgliteInstances.set(absDir, pg);
55
+ return { pg, isEphemeral: false, absDir };
56
+ }
57
+
58
+ function appendVirtualWal(fs, absDir, isEphemeral, sqlText) {
59
+ if (isEphemeral || !absDir || !fs || fs.isRealFilesystem) return;
60
+ if (!/\b(CREATE|INSERT|UPDATE|DELETE|ALTER|DROP|TRUNCATE)\b/i.test(sqlText)) return;
61
+ try {
62
+ const journalPath = `${absDir}/wal.sql`;
63
+ const existing = fs.getFileByPath(journalPath);
64
+ const normalized = sqlText.trim().endsWith(';') ? sqlText.trim() : sqlText.trim() + ';';
65
+ const updated = typeof existing === 'string' && existing.length > 0
66
+ ? `${existing}\n${normalized}`
67
+ : normalized;
68
+ fs.setFileByPath(journalPath, updated, true);
69
+ } catch {
70
+ // ignore
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Starts a PGlite background server daemon on `port` (default 5432) via DaemonManager.
76
+ * Exposes HTTP endpoints (`GET /status`, `POST /query`, `POST /sql`, `GET /query?sql=...`)
77
+ * so `curl http://localhost:5432/query -d "SELECT 1"`, `psql -h localhost -p 5432`, and browser `fetch()`
78
+ * all talk to the live PGlite daemon!
79
+ */
80
+ async function startPgliteDaemon({ dataDir = '/var/lib/postgresql/data', port = 5432, host = '127.0.0.1', fs, pkgMeta, wbtConfig }) {
81
+ const { pg, isEphemeral, absDir } = await getOrInitPgliteInstance(dataDir, fs, pkgMeta, wbtConfig);
82
+ const pidFile = `${absDir || '/var/run'}/postmaster.pid`;
83
+
84
+ const daemon = await daemonManager.startDaemon({
85
+ name: 'pglite',
86
+ port: Number(port),
87
+ host,
88
+ dataDir: absDir || dataDir,
89
+ instance: pg,
90
+ fs,
91
+ pidFile,
92
+ handler: async (req) => {
93
+ if (req.path === '/status' || req.path === '/health') {
94
+ return {
95
+ status: 200,
96
+ body: {
97
+ status: 'ready',
98
+ engine: 'pglite',
99
+ version: pkgMeta.version,
100
+ port: Number(port),
101
+ dataDir: absDir || dataDir
102
+ }
103
+ };
104
+ }
105
+
106
+ let sql = req.searchParams ? req.searchParams.get('sql') : null;
107
+ if (!sql && req.body) {
108
+ const trimmedBody = req.body.trim();
109
+ if (trimmedBody.startsWith('{')) {
110
+ try {
111
+ const parsed = JSON.parse(trimmedBody);
112
+ sql = parsed.query || parsed.sql || '';
113
+ } catch {
114
+ sql = trimmedBody;
115
+ }
116
+ } else {
117
+ sql = trimmedBody;
118
+ }
119
+ }
120
+
121
+ if (!sql) {
122
+ return {
123
+ status: 400,
124
+ body: { error: 'No SQL query provided. Pass SQL in POST body or ?sql= query param.' }
125
+ };
126
+ }
127
+
128
+ try {
129
+ const rawRes = typeof pg.exec === 'function' ? await pg.exec(sql) : [await pg.query(sql)];
130
+ appendVirtualWal(fs, absDir, isEphemeral, sql);
131
+ const resList = Array.isArray(rawRes) ? rawRes : [rawRes];
132
+ const last = resList[resList.length - 1] || { fields: [], rows: [] };
133
+ return {
134
+ status: 200,
135
+ body: {
136
+ fields: (last.fields || []).map(f => typeof f === 'string' ? f : f.name),
137
+ rows: last.rows || [],
138
+ affectedRows: last.affectedRows ?? 0,
139
+ results: resList
140
+ }
141
+ };
142
+ } catch (err) {
143
+ return {
144
+ status: 400,
145
+ body: { error: err.message || String(err) }
146
+ };
147
+ }
148
+ }
149
+ });
150
+
151
+ return daemon;
152
+ }
153
+
154
+ function createPgliteCommand(pkgMeta, wbtConfig = {}, binName = 'pglite') {
155
+ class PgliteCommand extends ReplCommand {
156
+ static get name() { return binName; }
157
+ get name() { return binName; }
158
+
159
+ constructor(args, context) {
160
+ super(args, context);
161
+ this._parsed = this._parseArgs(args || []);
162
+ this._pg = null;
163
+ this._mode = this._parsed.mode || 'table';
164
+ }
165
+
166
+ _parseArgs(args) {
167
+ let dataDir = null;
168
+ let sql = null;
169
+ let file = null;
170
+ let mode = 'table';
171
+ let tuplesOnly = false;
172
+ let help = false;
173
+ let version = false;
174
+ let daemonAction = null; // 'start' | 'stop' | 'status'
175
+ let host = null;
176
+ let port = 5432;
177
+
178
+ const positional = [];
179
+ for (let i = 0; i < args.length; i++) {
180
+ const arg = args[i];
181
+ if (arg === '--help' || arg === '-h' && i + 1 >= args.length || arg === '-?') {
182
+ help = true;
183
+ } else if (arg === '--version' || arg === '-V' || arg === '-v') {
184
+ version = true;
185
+ } else if (arg === '--serve' || arg === '--daemon') {
186
+ daemonAction = 'start';
187
+ } else if ((arg === '-p' || arg === '--port') && i + 1 < args.length) {
188
+ port = Number(args[++i]) || 5432;
189
+ } else if (arg.startsWith('--port=')) {
190
+ port = Number(arg.slice('--port='.length)) || 5432;
191
+ } else if ((arg === '-h' || arg === '--host') && i + 1 < args.length) {
192
+ host = args[++i];
193
+ } else if ((arg === '-c' || arg === '--command') && i + 1 < args.length) {
194
+ sql = args[++i];
195
+ } else if ((arg === '-f' || arg === '--file') && i + 1 < args.length) {
196
+ file = args[++i];
197
+ } else if ((arg === '-d' || arg === '--dbname' || arg === '-D' || arg === '--pgdata') && i + 1 < args.length) {
198
+ dataDir = args[++i];
199
+ } else if (arg === '-t' || arg === '--tuples-only' || arg === '-A' || arg === '--no-align') {
200
+ tuplesOnly = true;
201
+ mode = 'list';
202
+ } else if (arg === '--csv') {
203
+ mode = 'csv';
204
+ } else if (arg === '--json') {
205
+ mode = 'json';
206
+ } else if (!arg.startsWith('-')) {
207
+ positional.push(arg);
208
+ }
209
+ }
210
+
211
+ // Support subcommands: `pglite serve`, `pglite start`, `pglite stop`, `pglite status`
212
+ if (positional.length > 0 && ['serve', 'start', 'stop', 'status'].includes(positional[0].toLowerCase())) {
213
+ const sub = positional.shift().toLowerCase();
214
+ daemonAction = sub === 'serve' ? 'start' : sub;
215
+ }
216
+
217
+ if (positional.length === 1) {
218
+ if (/^\s*(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|WITH|BEGIN|SHOW|SET|EXPLAIN|VALUES|\\)\b/i.test(positional[0])) {
219
+ sql = positional[0];
220
+ } else {
221
+ dataDir = positional[0];
222
+ }
223
+ } else if (positional.length >= 2) {
224
+ dataDir = positional[0];
225
+ sql = positional.slice(1).join(' ');
226
+ }
227
+
228
+ // Check if a PGlite daemon is already running on `port` when no explicit dataDir was given
229
+ const runningDaemon = daemonManager.getDaemon(port);
230
+ const useDaemon = Boolean(host || (runningDaemon && !dataDir));
231
+
232
+ return {
233
+ dataDir: dataDir || (runningDaemon ? runningDaemon.dataDir : 'memory://'),
234
+ sql,
235
+ file,
236
+ mode,
237
+ tuplesOnly,
238
+ help,
239
+ version,
240
+ daemonAction,
241
+ host: host || '127.0.0.1',
242
+ port,
243
+ useDaemon
244
+ };
245
+ }
246
+
247
+ shouldBeInteractive() {
248
+ if (this._parsed.help || this._parsed.version || this._parsed.daemonAction) return false;
249
+ if (this._parsed.sql !== null || this._parsed.file !== null) return false;
250
+ if (this.stdin !== undefined && this.stdin !== null && String(this.stdin).trim().length > 0) return false;
251
+ return true;
252
+ }
253
+
254
+ getReplTitle() {
255
+ const daemon = daemonManager.getDaemon(this._parsed.port);
256
+ const target = daemon
257
+ ? `daemon://${daemon.host}:${daemon.port} (${daemon.dataDir})`
258
+ : this._parsed.dataDir;
259
+ return `PGlite PostgreSQL WASM (${pkgMeta.version}) — ${target}`;
260
+ }
261
+
262
+ getReplPrompt() {
263
+ return 'postgres=# ';
264
+ }
265
+
266
+ getReplWelcome() {
267
+ const daemon = daemonManager.getDaemon(this._parsed.port);
268
+ return [
269
+ `psql (PGlite ${pkgMeta.version}, PostgreSQL 16.4 WASM)`,
270
+ daemon
271
+ ? `Connected to running PGlite daemon on ${daemon.host}:${daemon.port} (PID ${daemon.pid})`
272
+ : `Data directory: ${this._parsed.dataDir}`,
273
+ `Type "\\?" for help, "\\dt" to list tables, "\\q" or ".exit" to quit.`
274
+ ];
275
+ }
276
+
277
+ async _initPg() {
278
+ const daemon = daemonManager.getDaemon(this._parsed.port);
279
+ if (daemon && (this._parsed.useDaemon || daemon.dataDir === this.fs.absolutePath(this._parsed.dataDir))) {
280
+ this._pg = daemon.instance;
281
+ this._absDataDir = daemon.dataDir;
282
+ this._isEphemeral = false;
283
+ return;
284
+ }
285
+
286
+ const { pg, isEphemeral, absDir } = await getOrInitPgliteInstance(
287
+ this._parsed.dataDir,
288
+ this.fs,
289
+ pkgMeta,
290
+ wbtConfig
291
+ );
292
+ this._pg = pg;
293
+ this._isEphemeral = isEphemeral;
294
+ this._absDataDir = absDir;
295
+ }
296
+
297
+ async _executeQuery(sqlText) {
298
+ const outLines = [];
299
+ const trimmed = sqlText.trim();
300
+ if (!trimmed) return outLines;
301
+
302
+ if (trimmed.startsWith('\\')) {
303
+ const parts = trimmed.split(/\s+/);
304
+ const cmd = parts[0];
305
+ if (cmd === '\\?' || cmd === '\\help') {
306
+ return [
307
+ 'General:',
308
+ ' \\dt list tables in public schema',
309
+ ' \\d [NAME] describe table, view, or index',
310
+ ' \\l list databases',
311
+ ' \\i FILE execute commands from file',
312
+ ' \\q quit pglite'
313
+ ];
314
+ }
315
+ if (cmd === '\\dt') {
316
+ return this._executeQuery(
317
+ "SELECT schemaname AS schema, tablename AS name, tableowner AS owner FROM pg_catalog.pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema') ORDER BY 1, 2;"
318
+ );
319
+ }
320
+ if (cmd === '\\l') {
321
+ return this._executeQuery(
322
+ "SELECT datname AS name, pg_catalog.pg_encoding_to_char(encoding) AS encoding FROM pg_catalog.pg_database;"
323
+ );
324
+ }
325
+ if (cmd === '\\d') {
326
+ if (!parts[1]) {
327
+ return this._executeQuery(
328
+ "SELECT table_schema AS schema, table_name AS name, table_type AS type FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema') ORDER BY 1, 2;"
329
+ );
330
+ }
331
+ const tbl = parts[1].replace(/'/g, "''");
332
+ return this._executeQuery(
333
+ `SELECT column_name AS column, data_type AS type, is_nullable AS nullable, column_default AS default FROM information_schema.columns WHERE table_name = '${tbl}' ORDER BY ordinal_position;`
334
+ );
335
+ }
336
+ if (cmd === '\\i' && parts[1]) {
337
+ const fileContent = this.fs.getFileByPath(parts[1]);
338
+ if (fileContent == null) {
339
+ throw new Error(`${parts[1]}: No such file or directory`);
340
+ }
341
+ return this._executeQuery(String(fileContent));
342
+ }
343
+ throw new Error(`invalid command ${cmd}. Try \\? for help.`);
344
+ }
345
+
346
+ const results = typeof this._pg.exec === 'function'
347
+ ? await this._pg.exec(sqlText)
348
+ : [await this._pg.query(sqlText)];
349
+
350
+ appendVirtualWal(this.fs, this._absDataDir, this._isEphemeral, sqlText);
351
+
352
+ const resArray = Array.isArray(results) ? results : [results];
353
+ for (const res of resArray) {
354
+ if (!res) continue;
355
+ const fields = (res.fields || []).map(f => typeof f === 'string' ? f : f.name);
356
+ const rows = res.rows || [];
357
+
358
+ if (fields.length === 0) {
359
+ if (typeof res.affectedRows === 'number') {
360
+ outLines.push(`OK (${res.affectedRows})`);
361
+ }
362
+ continue;
363
+ }
364
+
365
+ if (this._mode === 'list') {
366
+ outLines.push(...formatPipeList(fields, rows, false));
367
+ } else if (this._mode === 'csv') {
368
+ outLines.push(...formatCsv(fields, rows, true));
369
+ } else if (this._mode === 'json') {
370
+ outLines.push(JSON.stringify(rows));
371
+ } else {
372
+ outLines.push(...formatTable(fields, rows, { showRowCount: true }));
373
+ }
374
+ }
375
+ return outLines;
376
+ }
377
+
378
+ async initRepl() {
379
+ await this._initPg();
380
+ }
381
+
382
+ async evaluateReplLine(line) {
383
+ try {
384
+ const output = await this._executeQuery(line);
385
+ return { output };
386
+ } catch (err) {
387
+ return { error: `ERROR: ${err.message || err}` };
388
+ }
389
+ }
390
+
391
+ async cleanupRepl() {
392
+ if (this._isEphemeral && this._pg && typeof this._pg.close === 'function') {
393
+ try { await this._pg.close(); } catch { /* ignore */ }
394
+ }
395
+ }
396
+
397
+ async _handleDaemonAction() {
398
+ const action = this._parsed.daemonAction;
399
+ const port = this._parsed.port || 5432;
400
+ const dataDir = this._parsed.dataDir === 'memory://' ? '/var/lib/postgresql/data' : this._parsed.dataDir;
401
+
402
+ if (action === 'start') {
403
+ try {
404
+ const entry = await startPgliteDaemon({
405
+ dataDir,
406
+ port,
407
+ host: this._parsed.host,
408
+ fs: this.fs,
409
+ pkgMeta,
410
+ wbtConfig
411
+ });
412
+ this.stdOut = `waiting for server to start.... done`;
413
+ this.stdOut = `server started (PID ${entry.pid}) listening on http://${entry.host}:${entry.port} (dataDir: ${entry.dataDir})`;
414
+ } catch (err) {
415
+ this.stdErr = `pglite: could not start server: ${err.message || err}`;
416
+ this.exitCode = 1;
417
+ }
418
+ return;
419
+ }
420
+
421
+ if (action === 'stop') {
422
+ const stopped = await daemonManager.stopDaemon(port) || await daemonManager.stopDaemon('pglite');
423
+ if (!stopped) {
424
+ this.stdErr = `pglite: no server running on port ${port}`;
425
+ this.exitCode = 1;
426
+ return;
427
+ }
428
+ this.stdOut = `waiting for server to shut down.... done`;
429
+ this.stdOut = `server stopped (PID ${stopped.pid})`;
430
+ return;
431
+ }
432
+
433
+ if (action === 'status') {
434
+ const running = daemonManager.getDaemon(port) || daemonManager.getDaemon('pglite');
435
+ if (!running) {
436
+ this.stdOut = `pglite: no server running`;
437
+ this.exitCode = 3;
438
+ return;
439
+ }
440
+ this.stdOut = `pglite server is running (PID: ${running.pid}, port: ${running.port}, dataDir: ${running.dataDir})`;
441
+ }
442
+ }
443
+
444
+ async runNonInteractive() {
445
+ if (this._parsed.help) {
446
+ [
447
+ `${binName} (${pkgMeta.name} ${pkgMeta.version} wasm) — ${pkgMeta.description}`,
448
+ `Usage: ${binName} [OPTIONS] [DATADIR] [SQL]`,
449
+ ' pglite serve [-D DATADIR] [-p PORT] Start PGlite background daemon',
450
+ ' pglite status [-p PORT] Check daemon status',
451
+ ' pglite stop [-p PORT] Stop running daemon',
452
+ '',
453
+ 'Options:',
454
+ ' -c, --command=SQL Run only single command (SQL or internal) and exit',
455
+ ' -f, --file=FILENAME Execute commands from file, then exit',
456
+ ' -d, -D, --pgdata=DIR Database storage directory in filesystem',
457
+ ' --serve, --daemon Start PGlite server daemon in the background',
458
+ ' -h, --host=HOSTNAME Database server host (default: 127.0.0.1)',
459
+ ' -p, --port=PORT Database server port (default: 5432)',
460
+ ' -t, --tuples-only Print rows only (pipe-separated)',
461
+ ' --csv CSV output mode',
462
+ ' --json JSON output mode',
463
+ ' -h, --help Show this help message and exit',
464
+ ' -V, --version Show WebAssembly binary version and exit',
465
+ '',
466
+ 'Aliases: pglite, psql, pg_ctl',
467
+ `Source: ${pkgMeta.homepage || pkgMeta.cdnUrl}`
468
+ ].forEach(l => { this.stdOut = l; });
469
+ return;
470
+ }
471
+
472
+ if (this._parsed.version) {
473
+ this.stdOut = `${binName} (${pkgMeta.name} ${pkgMeta.version} wasm)`;
474
+ return;
475
+ }
476
+
477
+ if (this._parsed.daemonAction) {
478
+ await this._handleDaemonAction();
479
+ return;
480
+ }
481
+
482
+ try {
483
+ await this._initPg();
484
+
485
+ const scripts = [];
486
+ if (this._parsed.file) {
487
+ const content = this.fs.getFileByPath(this._parsed.file);
488
+ if (content == null) {
489
+ this.stdErr = `${binName}: error: ${this._parsed.file}: No such file or directory`;
490
+ this.exitCode = 1;
491
+ return;
492
+ }
493
+ scripts.push(String(content));
494
+ }
495
+ if (this._parsed.sql !== null) {
496
+ scripts.push(this._parsed.sql);
497
+ }
498
+ if (this.stdin !== undefined && this.stdin !== null && String(this.stdin).trim().length > 0) {
499
+ scripts.push(String(this.stdin));
500
+ }
501
+
502
+ for (const sql of scripts) {
503
+ const out = await this._executeQuery(sql);
504
+ out.forEach(l => { this.stdOut = l; });
505
+ }
506
+ } catch (err) {
507
+ this.stdErr = `ERROR: ${err.message || err}`;
508
+ this.exitCode = 1;
509
+ } finally {
510
+ await this.cleanupRepl();
511
+ }
512
+ }
513
+ }
514
+
515
+ return PgliteCommand;
516
+ }
517
+
518
+ /**
519
+ * Creates the standard PostgreSQL `pg_ctl` utility command (`pg_ctl start|stop|status|restart -D <dir> -p <port>`).
520
+ */
521
+ function createPgCtlCommand(pkgMeta, wbtConfig = {}) {
522
+ class PgCtlCommand extends Command {
523
+ static get name() { return 'pg_ctl'; }
524
+ get name() { return 'pg_ctl'; }
525
+ get requiresFilesystem() { return true; }
526
+
527
+ async run() {
528
+ const args = [...(this.arguments || [])];
529
+ if (args.includes('--version') || args.includes('-V') || args.includes('-v')) {
530
+ this.stdOut = `pg_ctl (${pkgMeta.name} ${pkgMeta.version} wasm)`;
531
+ return;
532
+ }
533
+ if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
534
+ [
535
+ `pg_ctl (${pkgMeta.name} ${pkgMeta.version} wasm) — Initialize, start, stop, or control a PGlite PostgreSQL server daemon`,
536
+ 'Usage: pg_ctl <start|stop|restart|status> [-D DATADIR] [-p PORT]',
537
+ '',
538
+ 'Options:',
539
+ ' -D, --pgdata=DATADIR Database storage directory (default: /var/lib/postgresql/data)',
540
+ ' -p, --port=PORT Database server port (default: 5432)',
541
+ ' -h, --help Show this help message and exit',
542
+ ' -V, --version Show WebAssembly binary version and exit'
543
+ ].forEach(l => { this.stdOut = l; });
544
+ return;
545
+ }
546
+
547
+ let action = null;
548
+ let dataDir = '/var/lib/postgresql/data';
549
+ let port = 5432;
550
+
551
+ for (let i = 0; i < args.length; i++) {
552
+ const a = args[i];
553
+ if ((a === '-D' || a === '--pgdata') && i + 1 < args.length) {
554
+ dataDir = args[++i];
555
+ } else if ((a === '-p' || a === '--port') && i + 1 < args.length) {
556
+ port = Number(args[++i]) || 5432;
557
+ } else if (a === '-o' && i + 1 < args.length) {
558
+ // Parse `-o "-p 5433"` style postgres options
559
+ const optStr = args[++i];
560
+ const pMatch = optStr.match(/-p\s*(\d+)/);
561
+ if (pMatch) port = Number(pMatch[1]);
562
+ } else if (!a.startsWith('-') && !action) {
563
+ action = a.toLowerCase();
564
+ }
565
+ }
566
+
567
+ if (action === 'restart') {
568
+ await daemonManager.stopDaemon(port);
569
+ action = 'start';
570
+ }
571
+
572
+ const PgliteCmd = createPgliteCommand(pkgMeta, wbtConfig, 'pg_ctl');
573
+ const cmd = new PgliteCmd([action || 'status', '-D', dataDir, '-p', String(port)], this.context);
574
+ cmd.fs = this.fs;
575
+ const res = await cmd.runCommand();
576
+ for (const line of res.getStdOutput()) {
577
+ if (line.type === 'out') this.stdOut = line.string;
578
+ else if (line.type === 'err') this.stdErr = line.string;
579
+ }
580
+ this.exitCode = res.getExitCode();
581
+ }
582
+ }
583
+
584
+ return PgCtlCommand;
585
+ }
586
+
587
+ module.exports = createPgliteCommand;
588
+ module.exports.createPgliteCommand = createPgliteCommand;
589
+ module.exports.createPgCtlCommand = createPgCtlCommand;
590
+ module.exports.pgliteInstances = pgliteInstances;