blankthing 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 kamonsarthak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/bin/blan.js ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js';
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => { process.exitCode = code; },
6
+ (err) => { console.error(`❌ ${err.message}`); process.exitCode = 1; },
7
+ );
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "blankthing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Blankthing CLI: a remote control for the blan_db service",
5
+ "keywords": [
6
+ "blankthing",
7
+ "blan",
8
+ "cli",
9
+ "database",
10
+ "database-migration",
11
+ "migration",
12
+ "zero-downtime",
13
+ "live-migration",
14
+ "postgres",
15
+ "mysql",
16
+ "mongodb",
17
+ "sqlserver",
18
+ "markdown",
19
+ "web-scraping",
20
+ "agents",
21
+ "llm"
22
+ ],
23
+ "author": "kamonsarthak",
24
+ "type": "module",
25
+ "bin": {
26
+ "blan": "bin/blan.js",
27
+ "bthing": "bin/blan.js"
28
+ },
29
+ "files": [
30
+ "bin/",
31
+ "src/"
32
+ ],
33
+ "engines": {
34
+ "node": ">=18"
35
+ },
36
+ "scripts": {
37
+ "test": "node --test",
38
+ "postinstall": "node src/postinstall.js"
39
+ },
40
+ "license": "MIT"
41
+ }
package/src/cli.js ADDED
@@ -0,0 +1,410 @@
1
+ // blan: a thin remote control for blan_db. It parses arguments, makes one
2
+ // API call and prints the reply.
3
+
4
+ import { parseArgs } from 'node:util';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { createInterface } from 'node:readline/promises';
7
+ import { createRequire } from 'node:module';
8
+ import { makeClient, ApiError, DEFAULT_SERVER, DEFAULT_BARE_SERVER } from './client.js';
9
+ import { makeStyle, icons } from './style.js';
10
+
11
+ const { version } = createRequire(import.meta.url)('../package.json');
12
+
13
+ // Help screens, gh-style: a header with the version, a one-line intro,
14
+ // then bold sections. s is a style from makeStyle (plain text when piped).
15
+ const header = (s, name, intro) => `${name} v${version}\n${intro}`;
16
+
17
+ function mainHelp(s) {
18
+ return `${header(s, 'blan', 'Blankthing from the command line: move live databases, fetch the web as Markdown.')}
19
+
20
+ ${s.bold('USAGE')}
21
+ blan <command> <subcommand> [flags]
22
+ blan db <command> [flags]
23
+ blan bare <command> [flags]
24
+
25
+ ${s.bold('DB COMMANDS')}
26
+ db init: Register your database
27
+ db demo: Free test migration
28
+ db migrate: Migrate a live database
29
+ db status: Show databases and migrations
30
+ db retire: Retire the old database
31
+ db log: Show your audit log
32
+
33
+ ${s.bold('BARE COMMANDS')}
34
+ bare fetch: Fetch a page as Markdown
35
+ bare log: Show your audit log
36
+
37
+ ${s.bold('FLAGS')}
38
+ --server URL Use another server
39
+ --token T Your API token
40
+ --json Print the raw reply
41
+ -h, --help Show help for command
42
+ -v, --version Show blan version
43
+
44
+ ${s.bold('ENVIRONMENT')}
45
+ BLAN_DB_TOKEN Your API token, for db and bare
46
+ BLAN_DB_URL blan_db address (default ${DEFAULT_SERVER})
47
+ BLAN_BARE_URL Bare address (default ${DEFAULT_BARE_SERVER})
48
+
49
+ ${s.bold('LEARN MORE')}
50
+ Use \`blan db --help\` or \`blan bare --help\` for more about a command.
51
+ bthing is an alias for blan.`;
52
+ }
53
+
54
+ function bareHelp(s) {
55
+ return `${header(s, 'blan bare', 'Web pages as clean Markdown, for agents.')}
56
+
57
+ ${s.bold('USAGE')}
58
+ blan bare <command> [flags]
59
+
60
+ ${s.bold('COMMANDS')}
61
+ fetch: Fetch a page as Markdown
62
+ log: Show your audit log
63
+
64
+ ${s.bold('DETAILS')}
65
+ blan bare fetch URL
66
+ Fetch URL through Bare and print it as Markdown, its links numbered
67
+ [n] and listed at the end. Sites that opted out of Bare, or whose
68
+ robots.txt disallows it, are refused.
69
+
70
+ blan bare log [--limit N]
71
+ Your audit log on Bare, newest first (default 50, at most 1000): every
72
+ fetch, search and opt-out made with your token, and how it ended. Only
73
+ your own actions; never page content or search queries.
74
+
75
+ ${s.bold('FLAGS')}
76
+ --server URL Bare address (env BLAN_BARE_URL)
77
+ --token T Your API token (env BLAN_DB_TOKEN, same as blan db)
78
+ --json Print the raw reply`;
79
+ }
80
+
81
+ function dbHelp(s) {
82
+ return `${header(s, 'blan db', 'Move a database without stopping it.')}
83
+
84
+ ${s.bold('USAGE')}
85
+ blan db <command> [flags]
86
+
87
+ ${s.bold('COMMANDS')}
88
+ init: Register your database
89
+ demo: Free test migration
90
+ migrate: Migrate a live database
91
+ status: Show databases and migrations
92
+ retire: Retire the old database
93
+ log: Show your audit log
94
+
95
+ ${s.bold('DETAILS')}
96
+ blan db init postgres --name NAME --url postgres://USER:PASSWORD@HOST:PORT/DB
97
+ blan db init mysql --name NAME --url mysql://USER:PASSWORD@HOST:PORT/DB
98
+ blan db init mongodb --name NAME --url mongodb://USER:PASSWORD@HOST:PORT/DB
99
+ blan db init sqlserver --name NAME --url sqlserver://USER:PASSWORD@HOST:PORT?database=DB
100
+ Register an outside Postgres, MySQL, MongoDB or SQL Server database as
101
+ NAME. blan_db tests the connection first. The password stays in
102
+ blan_db's memory only, never on disk; after a server restart, run init
103
+ again. --url can come from BLAN_PG_URL / BLAN_MYSQL_URL /
104
+ BLAN_MONGODB_URL / BLAN_SQLSERVER_URL instead, to keep it out of your
105
+ shell history. Migrations run between two databases of the same engine.
106
+
107
+ blan db demo [--direction to-blankthing|from-blankthing] [--file ROWS.jsonl]
108
+ A free test migration on blan_db, start to finish, in a throwaway sandbox.
109
+ to-blankthing your test rows move into Blankthing (--file, one JSON
110
+ object per line, or piped on stdin)
111
+ from-blankthing Blankthing's sample rows move out to your side
112
+ Without --direction you are asked which way.
113
+
114
+ blan db migrate --from NAME --to NAME [--finish-now] [--settle 10s]
115
+ blan db migrate SOURCE [--into DEST] [--finish-now] [--settle 10s]
116
+ Real migration: blueprint, clone, link, herepoint, live copy, verify.
117
+ SOURCE keeps serving and forwards to DEST (default SOURCE-new).
118
+ Between two registered Postgres databases, the data is read from the
119
+ first, moved, written into the second in one transaction, and both
120
+ databases are compared table by table. Re-running continues.
121
+
122
+ blan db status [STORE]
123
+ Every database, or one in detail.
124
+
125
+ blan db retire SOURCE [--yes]
126
+ Once your service points at the new database: verify once more, then
127
+ retire SOURCE for good. Asks first unless --yes.
128
+
129
+ blan db log [--limit N]
130
+ Your audit log on blan_db, newest first (default 50, at most 1000):
131
+ every init, migrate, status, retire, demo and payment check made with
132
+ your token, each step, and how it ended. Only your own actions; never
133
+ passwords, connection strings or data.
134
+
135
+ ${s.bold('FLAGS')}
136
+ --server URL blan_db address (env BLAN_DB_URL)
137
+ --token T Your API token (env BLAN_DB_TOKEN)
138
+ --json Print the raw reply`;
139
+ }
140
+
141
+ const OPTIONS = {
142
+ server: { type: 'string' },
143
+ token: { type: 'string' },
144
+ json: { type: 'boolean' },
145
+ help: { type: 'boolean', short: 'h' },
146
+ version: { type: 'boolean', short: 'v' },
147
+ direction: { type: 'string', short: 'd' },
148
+ file: { type: 'string', short: 'f' },
149
+ into: { type: 'string' },
150
+ from: { type: 'string' },
151
+ to: { type: 'string' },
152
+ name: { type: 'string', short: 'n' },
153
+ url: { type: 'string' },
154
+ 'finish-now': { type: 'boolean' },
155
+ settle: { type: 'string' },
156
+ yes: { type: 'boolean', short: 'y' },
157
+ limit: { type: 'string', short: 'l' },
158
+ };
159
+
160
+ class UsageError extends Error {}
161
+
162
+ export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, env: process.env }) {
163
+ const out = (s = '') => io.stdout.write(s + '\n');
164
+ const err = (s) => io.stderr.write(s + '\n');
165
+ const so = makeStyle(io.stdout, io.env), se = makeStyle(io.stderr, io.env);
166
+ const fail = (m) => err(`${icons.fail} ${m}`);
167
+ const warn = (m) => err(`${icons.warn} ${m}`);
168
+ // Help on request goes to stdout (exit 0); help after a mistake to stderr (exit 2).
169
+ const help = (screen, asked) => { asked ? out(screen(so)) : err(screen(se)); return asked ? 0 : 2; };
170
+ let parsed;
171
+ try {
172
+ parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
173
+ } catch (e) {
174
+ warn(e.message);
175
+ return 2;
176
+ }
177
+ const { values: o, positionals: pos } = parsed;
178
+
179
+ if (o.version) { out(`blan v${version}`); return 0; }
180
+ if (pos.length === 0) return help(mainHelp, o.help);
181
+ if (pos[0] === 'bare') return bareMain({ o, pos, io, out, help, warn, fail });
182
+ if (pos[0] !== 'db') { warn(`unknown command "${pos[0]}"\n`); return help(mainHelp, false); }
183
+ if (o.help || pos.length === 1) return help(dbHelp, o.help);
184
+
185
+ const client = makeClient({
186
+ server: o.server || io.env.BLAN_DB_URL || DEFAULT_SERVER,
187
+ token: o.token || io.env.BLAN_DB_TOKEN,
188
+ });
189
+ const [, cmd, ...args] = pos;
190
+ try {
191
+ const commands = { init, demo, migrate, status, retire, log };
192
+ if (!commands[cmd]) throw new UsageError(`unknown db command "${cmd}" (blan db --help)`);
193
+ const reply = await commands[cmd]({ client, o, args, io, out });
194
+ if (o.json && reply) out(JSON.stringify(reply, null, 2));
195
+ return 0;
196
+ } catch (e) {
197
+ if (e instanceof UsageError) { warn(e.message); return 2; }
198
+ if (e instanceof ApiError) {
199
+ for (const s of e.body?.steps || []) err(` ${s.step.padEnd(10)} ${s.detail}`);
200
+ if (e.body?.compare) printCompare(err, e.body.compare);
201
+ fail(e.message);
202
+ return 1;
203
+ }
204
+ throw e;
205
+ }
206
+ }
207
+
208
+ // blan bare: the same token and error handling as blan db, against Bare.
209
+ async function bareMain({ o, pos, io, out, help, warn, fail }) {
210
+ if (o.help || pos.length === 1) return help(bareHelp, o.help);
211
+ const client = makeClient({
212
+ server: o.server || io.env.BLAN_BARE_URL || DEFAULT_BARE_SERVER,
213
+ token: o.token || io.env.BLAN_DB_TOKEN,
214
+ service: 'Bare',
215
+ });
216
+ const [, cmd, ...args] = pos;
217
+ try {
218
+ const commands = { fetch: bareFetch, log: bareLog };
219
+ if (!Object.hasOwn(commands, cmd)) throw new UsageError(`unknown bare command "${cmd}" (blan bare --help)`);
220
+ const reply = await commands[cmd]({ client, o, args, out });
221
+ if (o.json && reply) out(JSON.stringify(reply, null, 2));
222
+ return 0;
223
+ } catch (e) {
224
+ if (e instanceof UsageError) { warn(e.message); return 2; }
225
+ if (e instanceof ApiError) { fail(e.message); return 1; }
226
+ throw e;
227
+ }
228
+ }
229
+
230
+ async function bareFetch({ client, o, args, out }) {
231
+ if (args.length !== 1) throw new UsageError('usage: blan bare fetch URL');
232
+ const r = await client.bareFetch(args[0]);
233
+ if (o.json) return r;
234
+ if (r.title) out(`# ${r.title}\n`);
235
+ out(`Source: <${r.url}>\n`);
236
+ out(r.markdown);
237
+ if (r.links?.length) out('\n' + r.links.map((l) => `[${l.id}]: <${l.url}>`).join('\n'));
238
+ }
239
+
240
+ async function bareLog({ client, o, args, out }) {
241
+ if (args.length) throw new UsageError('usage: blan bare log [--limit N]');
242
+ let limit;
243
+ if (o.limit !== undefined) {
244
+ limit = Number(o.limit);
245
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new UsageError('--limit must be a whole number from 1 to 1000');
246
+ }
247
+ const r = await client.bareLog(limit);
248
+ if (o.json) return r;
249
+ if (!r.entries.length) { out(`no actions recorded for ${r.actor} yet`); return; }
250
+ out(`audit log for ${r.actor}, newest first:`);
251
+ for (const e of r.entries) {
252
+ const when = e.time.replace('T', ' ').replace(/\.\d+Z$|Z$/, 'Z');
253
+ const what = e.url || e.domain || '-';
254
+ out(`${when} ${e.action.padEnd(13)} ${what.padEnd(30)} ${e.outcome.padEnd(10)} ${e.detail || ''}`.trimEnd());
255
+ }
256
+ }
257
+
258
+ async function ask(io, question) {
259
+ const rl = createInterface({ input: io.stdin, output: io.stderr });
260
+ try { return (await rl.question(question)).trim(); } finally { rl.close(); }
261
+ }
262
+
263
+ function printSteps(out, steps) {
264
+ for (const s of steps || []) out(` ${s.step.padEnd(10)} ${s.detail}`);
265
+ }
266
+
267
+ async function readRows(o, io) {
268
+ let text;
269
+ if (o.file) text = await readFile(o.file, 'utf8');
270
+ else if (!io.stdin.isTTY) {
271
+ const chunks = [];
272
+ for await (const c of io.stdin) chunks.push(Buffer.from(c));
273
+ text = Buffer.concat(chunks).toString('utf8');
274
+ } else {
275
+ throw new UsageError('to-blankthing needs your test rows: --file ROWS.jsonl, or pipe them on stdin');
276
+ }
277
+ const rows = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
278
+ if (rows.length === 0) throw new UsageError('no rows found (one JSON object per line)');
279
+ return rows;
280
+ }
281
+
282
+ // ---- commands: each is one API call
283
+
284
+ async function demo({ client, o, args, io, out }) {
285
+ if (args.length) throw new UsageError('usage: blan db demo [--direction to-blankthing|from-blankthing] [--file ROWS.jsonl]');
286
+ let dir = o.direction;
287
+ if (!dir) {
288
+ if (!io.stdin.isTTY) throw new UsageError('--direction to-blankthing|from-blankthing is required when not in a terminal');
289
+ const a = await ask(io, 'Which way?\n 1) your test data -> Blankthing\n 2) Blankthing -> your side\nChoose 1 or 2: ');
290
+ dir = { 1: 'to-blankthing', 2: 'from-blankthing' }[a];
291
+ if (!dir) throw new UsageError(`"${a}" isn't 1 or 2`);
292
+ }
293
+ if (dir !== 'to-blankthing' && dir !== 'from-blankthing') {
294
+ throw new UsageError('--direction must be to-blankthing or from-blankthing');
295
+ }
296
+ const rows = dir === 'to-blankthing' ? await readRows(o, io) : undefined;
297
+ const r = await client.demo(dir, rows);
298
+ if (o.json) return r;
299
+ out(`${icons.ok} demo ${r.direction}: ${r.source} -> ${r.destination}`);
300
+ printSteps(out, r.steps);
301
+ out(`\n${r.destination} now holds ${r.rows.length} row(s):`);
302
+ for (const row of r.rows) out(` ${row}`);
303
+ out('\nThat was a free test run in a sandbox; nothing was kept. Real moves: blan db migrate');
304
+ }
305
+
306
+ async function init({ client, o, args, io, out }) {
307
+ const usage = 'usage: blan db init postgres|mysql|mongodb|sqlserver --name NAME --url postgres://... | mysql://... | mongodb://... | sqlserver://USER:PASSWORD@HOST:PORT?database=DB';
308
+ const envVar = { postgres: 'BLAN_PG_URL', mysql: 'BLAN_MYSQL_URL', mongodb: 'BLAN_MONGODB_URL', sqlserver: 'BLAN_SQLSERVER_URL' };
309
+ if (args.length !== 1) throw new UsageError(usage);
310
+ const engine = args[0];
311
+ if (!envVar[engine]) throw new UsageError(`"${engine}" isn't supported yet (supported: postgres, mysql, mongodb, sqlserver)`);
312
+ const url = o.url || io.env[envVar[engine]];
313
+ if (!o.name || !url) throw new UsageError(usage);
314
+ const r = await client.init(engine, o.name, url);
315
+ if (o.json) return r;
316
+ out(`${icons.ok} ${r.already_registered ? 're-registered' : 'registered'} ${r.name}: ${engine} ${r.server_version} at ${r.target}`);
317
+ const tables = r.tables || [];
318
+ out(` ${tables.length} table(s)${tables.length ? ': ' + tables.join(', ') : ''}`);
319
+ out(' connection tested; the password is held in blan_db\'s memory only');
320
+ }
321
+
322
+ async function migrate({ client, o, args, out }) {
323
+ const usage = 'usage: blan db migrate --from NAME --to NAME | blan db migrate SOURCE [--into DEST] [--finish-now] [--settle 10s]';
324
+ let req;
325
+ if (o.from || o.to) {
326
+ if (!o.from || !o.to || args.length || o.into) throw new UsageError(usage);
327
+ req = { source: o.from, destination: o.to };
328
+ } else {
329
+ if (args.length !== 1) throw new UsageError(usage);
330
+ req = { source: args[0] };
331
+ if (o.into) req.destination = o.into;
332
+ }
333
+ if (o['finish-now']) req.finish_now = true;
334
+ if (o.settle) req.settle = o.settle;
335
+ const r = await client.migrate(req);
336
+ if (o.json) return r;
337
+ out(`migrate ${r.source} -> ${r.destination}: ${r.phase}`);
338
+ printSteps(out, r.steps);
339
+ if (r.compare) printCompare(out, r.compare);
340
+ if (r.verified_lsn) out(`\nverified at source position ${r.verified_lsn}; carried through ${r.carried_through_lsn}`);
341
+ if (r.note) out(`\n${r.note}.`);
342
+ out(`\nnext: ${r.next}`);
343
+ }
344
+
345
+ function printCompare(out, rows) {
346
+ out('\n' + ['TABLE'.padEnd(24), 'SOURCE ROWS'.padStart(12), 'DEST ROWS'.padStart(10), ' MD5 (source = dest)'].join(''));
347
+ for (const t of rows) {
348
+ const md5 = t.match ? `${t.source_md5} match` : `${t.source_md5 || '-'} != ${t.dest_md5 || '-'}`;
349
+ out([t.table.padEnd(24), String(t.source_rows).padStart(12), String(t.dest_rows).padStart(10), ` ${md5}`].join(''));
350
+ }
351
+ }
352
+
353
+ async function status({ client, o, args, out }) {
354
+ if (args.length > 1) throw new UsageError('usage: blan db status [STORE]');
355
+ const r = await client.status(args[0]);
356
+ if (o.json) return r;
357
+ const stores = r.store ? [r.store] : r.stores;
358
+ if (!stores.length) { out('no databases on blan_db yet'); return; }
359
+ out(['STORE'.padEnd(20), 'ROWS'.padStart(8), 'POINTERS'.padStart(9), ' STATE'].join(''));
360
+ for (const s of stores) {
361
+ let state = s.state;
362
+ if (s.link) state += ` (${s.link.role === 'source' ? '->' : '<-'} ${s.link.peer})`;
363
+ out([s.name.padEnd(20), String(s.rows).padStart(8), String(s.pointers).padStart(9), ` ${state}`].join(''));
364
+ }
365
+ const h = r.store?.herepoint;
366
+ if (h) out(`\nherepoint: next write lands on line ${h.Next}; ${h.Rows} row(s) above the gap; ${h.InFlight?.length || 0} in flight`);
367
+ const lc = r.store?.live_copy;
368
+ if (lc) out(`live copy: ${lc.phase}, ${lc.copied} change(s) copied`);
369
+ const feeds = new Map();
370
+ for (const a of Object.values(r.adapters || {})) if (a?.feed) feeds.set(a.feed.from, a.feed);
371
+ if (r.adapter?.feed) feeds.set(r.adapter.feed.from, r.adapter.feed);
372
+ for (const f of feeds.values()) {
373
+ let line = `\nfeed ${f.from} -> ${f.to}: ${f.state}`;
374
+ if (f.state === 'running') line += `, ${f.forwarded_txns} write(s) forwarded, backlog ${f.backlog_txns ?? '?'}; runs until blan db retire ${f.from}`;
375
+ out(line);
376
+ if (f.error) out(` ${f.error}`);
377
+ }
378
+ }
379
+
380
+ async function retire({ client, o, args, io, out }) {
381
+ if (args.length !== 1) throw new UsageError('usage: blan db retire SOURCE [--yes]');
382
+ const src = args[0];
383
+ if (!o.yes) {
384
+ if (!io.stdin.isTTY) throw new UsageError('retire is permanent: pass --yes to confirm when not in a terminal');
385
+ const a = await ask(io, `Retire ${src} for good? Your service must already point at its new database. Type "${src}" to confirm: `);
386
+ if (a !== src) { out(`${icons.warn} not retired`); return; }
387
+ }
388
+ const r = await client.retire(src);
389
+ if (o.json) return r;
390
+ printSteps(out, r.steps);
391
+ out(`${icons.ok} ${r.already ? `${src} was already retired` : `retired ${src}; ${r.destination} is the only database`}`);
392
+ }
393
+
394
+ async function log({ client, o, args, out }) {
395
+ if (args.length) throw new UsageError('usage: blan db log [--limit N]');
396
+ let limit;
397
+ if (o.limit !== undefined) {
398
+ limit = Number(o.limit);
399
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw new UsageError('--limit must be a whole number from 1 to 1000');
400
+ }
401
+ const r = await client.log(limit);
402
+ if (o.json) return r;
403
+ if (!r.entries.length) { out(`no actions recorded for ${r.actor} yet`); return; }
404
+ out(`audit log for ${r.actor}, newest first:`);
405
+ for (const e of r.entries) {
406
+ const when = e.time.replace('T', ' ').replace(/\.\d+Z$|Z$/, 'Z');
407
+ const dbs = (e.databases || []).join(', ') || '-';
408
+ out(`${when} ${e.action.padEnd(8)} ${dbs.padEnd(18)} ${e.outcome.padEnd(10)} ${e.detail || ''}`.trimEnd());
409
+ }
410
+ }
package/src/client.js ADDED
@@ -0,0 +1,75 @@
1
+ // The blan_db HTTP client. Every command is one call; no migration logic here.
2
+
3
+ import http from 'node:http';
4
+ import https from 'node:https';
5
+
6
+ export const DEFAULT_SERVER = 'https://db.blan.run';
7
+ export const DEFAULT_BARE_SERVER = 'https://bare.blan.run';
8
+
9
+ export class ApiError extends Error {
10
+ constructor(message, status, body) {
11
+ super(message);
12
+ this.status = status;
13
+ this.body = body;
14
+ }
15
+ }
16
+
17
+ function send(method, url, headers, body) {
18
+ return new Promise((resolve, reject) => {
19
+ const u = new URL(url);
20
+ const lib = u.protocol === 'https:' ? https : u.protocol === 'http:' ? http : null;
21
+ if (!lib) return reject(new Error(`unsupported protocol ${u.protocol}`));
22
+ if (body !== undefined) headers['Content-Length'] = Buffer.byteLength(body);
23
+ const req = lib.request(u, { method, headers }, (res) => {
24
+ let text = '';
25
+ res.setEncoding('utf8');
26
+ res.on('data', (c) => { text += c; });
27
+ res.on('end', () => resolve({ res, text }));
28
+ res.on('error', reject);
29
+ });
30
+ req.on('error', reject);
31
+ req.end(body);
32
+ });
33
+ }
34
+
35
+ export function makeClient({ server = DEFAULT_SERVER, token, service = 'blan_db' } = {}) {
36
+ const base = server.replace(/\/+$/, '');
37
+
38
+ async function request(method, path, body) {
39
+ const headers = { Accept: 'application/json' };
40
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
41
+ if (token) headers.Authorization = `Bearer ${token}`;
42
+ let res, text;
43
+ try {
44
+ // node:http rather than fetch: fetch gives up on a reply after 300s,
45
+ // and a live migration of a busy database can take longer than that.
46
+ ({ res, text } = await send(method, base + path, headers, body === undefined ? undefined : JSON.stringify(body)));
47
+ } catch (err) {
48
+ throw new ApiError(`can't reach ${service} at ${base} (${err.code || err.message})`, 0);
49
+ }
50
+ res.ok = res.statusCode >= 200 && res.statusCode < 300;
51
+ res.status = res.statusCode;
52
+ let data;
53
+ try {
54
+ data = JSON.parse(text);
55
+ } catch {
56
+ throw new ApiError(`${service} sent an unreadable reply (HTTP ${res.status})`, res.status, text);
57
+ }
58
+ if (!res.ok || data.ok === false) {
59
+ throw new ApiError(data.error || `HTTP ${res.status}`, res.status, data);
60
+ }
61
+ return data;
62
+ }
63
+
64
+ return {
65
+ init: (engine, name, url) => request('POST', '/v1/db/init', { engine, name, url }),
66
+ demo: (direction, rows) => request('POST', '/v1/db/demo', rows ? { direction, rows } : { direction }),
67
+ migrate: (req) => request('POST', '/v1/db/migrate', req),
68
+ status: (store) => request('GET', '/v1/db/status' + (store ? `?store=${encodeURIComponent(store)}` : '')),
69
+ retire: (source) => request('POST', '/v1/db/retire', { source }),
70
+ log: (limit) => request('GET', '/v1/db/log' + (limit ? `?limit=${limit}` : '')),
71
+ // Bare (made with service: 'Bare' and Bare's address)
72
+ bareFetch: (url) => request('GET', `/fetch?url=${encodeURIComponent(url)}`),
73
+ bareLog: (limit) => request('GET', '/log' + (limit ? `?limit=${limit}` : '')),
74
+ };
75
+ }
@@ -0,0 +1,53 @@
1
+ // Prints the install banner after `npm install -g blankthing`. Black and
2
+ // white: the version (read from package.json at run time, so it follows every
3
+ // bump) sits in grey right after the G on the banner's last line.
4
+ //
5
+ // npm 7+ hides lifecycle-script output unless a script fails, so the banner
6
+ // goes straight to the terminal (the console device on Windows, /dev/tty
7
+ // elsewhere). With no terminal (CI, Docker builds) it falls back to stdout,
8
+ // which npm discards. This script never fails the install.
9
+
10
+ import { openSync, writeSync, closeSync, readFileSync } from 'node:fs';
11
+
12
+ const LINES = String.raw`
13
+ ____ _ _ _ _ _ _______ _ _ ___ _ _ ____
14
+ | __ )| | / \ | \ | | |/ /_ _| | | |_ _| \ | |/ ___|
15
+ | _ \| | / _ \ | \| | ' / | | | |_| || || \| | | _
16
+ | |_) | |___ / ___ \| |\ | . \ | | | _ || || |\ | |_| |
17
+ |____/|_____/_/ \_\_| \_|_|\_\ |_| |_| |_|___|_| \_|\____|
18
+ `.slice(1, -1).split('\n');
19
+
20
+ function banner(tty) {
21
+ let version = '';
22
+ try {
23
+ version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
24
+ } catch {
25
+ // no version to show
26
+ }
27
+ const grey = (s) => (tty && !('NO_COLOR' in process.env) ? `\x1b[90m${s}\x1b[39m` : s);
28
+ const lines = [...LINES];
29
+ if (version) lines[lines.length - 1] += ` ${grey(`v${version}`)}`;
30
+ return `\n${lines.join('\n')}\n\nahead of the abyss\n\n`;
31
+ }
32
+
33
+ function show() {
34
+ // The device path, not a bare "CONOUT$", which Node would create as a file.
35
+ const device = process.platform === 'win32' ? '\\\\.\\CONOUT$' : '/dev/tty';
36
+ try {
37
+ const fd = openSync(device, 'w');
38
+ try {
39
+ const text = banner(true);
40
+ writeSync(fd, process.platform === 'win32' ? text.replace(/\n/g, '\r\n') : text);
41
+ } finally {
42
+ closeSync(fd);
43
+ }
44
+ } catch {
45
+ process.stdout.write(banner(Boolean(process.stdout.isTTY)));
46
+ }
47
+ }
48
+
49
+ try {
50
+ show();
51
+ } catch {
52
+ // never fail the install over a banner
53
+ }
package/src/style.js ADDED
@@ -0,0 +1,10 @@
1
+ // Black and white only: the terminal's own (white) text, with bold for
2
+ // section headers. No colour. Escapes are written only to a terminal, and
3
+ // never with NO_COLOR set, so piped output and tests stay plain text.
4
+
5
+ export const icons = { ok: '✅', fail: '❌', warn: '⚠️ ' };
6
+
7
+ export function makeStyle(stream, env = process.env) {
8
+ const on = Boolean(stream?.isTTY) && !('NO_COLOR' in env) && env.TERM !== 'dumb';
9
+ return { bold: (s) => (on ? `\x1b[1m${s}\x1b[22m` : String(s)) };
10
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.