askrobots / dbbasic-browser
Public
A desktop browser with x402 built in: when a page asks for payment, it pays in stablecoins and shows the content.
danq9
toolbar: Back and Forward are greyed out when there's nowhere to go
cc08c7a
1 week, 2 days ago
History
dbb.mjs · 1.9 KB · 60 lines
| 1 | #!/usr/bin/env node |
| 2 | /** |
| 3 | * Tiny client for the dbbasic-browser automation API. |
| 4 | * |
| 5 | * import { connect } from "./dbb.mjs"; |
| 6 | * const b = await connect(); // reads ~/.dbbasic/control.json (or DBB_URL + DBB_TOKEN) |
| 7 | * await b.call("page.goto", { url: "https://askrobots.com" }); |
| 8 | * |
| 9 | * node dbb.mjs <method> ['{"json":"params"}'] // one-off from a shell |
| 10 | */ |
| 11 | import { readFileSync } from "node:fs"; |
| 12 | import { homedir } from "node:os"; |
| 13 | import { join } from "node:path"; |
| 14 | |
| 15 | export class DbbError extends Error { |
| 16 | constructor(code, message) { |
| 17 | super(`${code}: ${message}`); |
| 18 | this.code = code; |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | export async function connect({ url, token } = {}) { |
| 23 | if (!url || !token) { |
| 24 | if (process.env.DBB_URL && process.env.DBB_TOKEN) { |
| 25 | ({ DBB_URL: url, DBB_TOKEN: token } = process.env); |
| 26 | } else { |
| 27 | try { |
| 28 | ({ url, token } = JSON.parse(readFileSync(join(homedir(), ".dbbasic", "control.json"), "utf8"))); |
| 29 | } catch { |
| 30 | throw new Error("no control.json — is the browser running with DBB_CONTROL=1?"); |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | let n = 0; |
| 35 | const call = async (method, params = {}) => { |
| 36 | const res = await fetch(url, { |
| 37 | method: "POST", |
| 38 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, |
| 39 | body: JSON.stringify({ id: ++n, method, params }), |
| 40 | }); |
| 41 | const body = await res.json(); |
| 42 | if (!body.ok) throw new DbbError(body.error?.code ?? "error", body.error?.message ?? "request failed"); |
| 43 | return body.result; |
| 44 | }; |
| 45 | return { call }; |
| 46 | } |
| 47 | |
| 48 | if (import.meta.url === `file://${process.argv[1]}`) { |
| 49 | const [method, json] = process.argv.slice(2); |
| 50 | if (!method) { |
| 51 | console.error("usage: dbb.mjs <method> ['{...params}']"); |
| 52 | process.exit(2); |
| 53 | } |
| 54 | try { |
| 55 | console.log(JSON.stringify(await (await connect()).call(method, json ? JSON.parse(json) : {}), null, 2)); |
| 56 | } catch (e) { |
| 57 | console.error(e.message); |
| 58 | process.exit(1); |
| 59 | } |
| 60 | } |