mirrorbook 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/SKILL.md ADDED
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: mirrorbook
3
+ description: Publish a static HTML page, folder, or zip to a public URL on mirrorbook.store with the `mirrorbook` CLI. Use when the user wants to share, host, or deploy an HTML file or a built static site.
4
+ ---
5
+
6
+ # Publishing HTML with mirrorbook
7
+
8
+ Sign in once with `npx mirrorbook login https://mirrorbook.store`. It prints a URL and a code, opens the browser, and waits until the user approves. Ask the user to approve it; don't try to approve it yourself. In CI, set `MIRRORBOOK_TOKEN` (and `MIRRORBOOK_API_URL` for a non-default server) instead.
9
+
10
+ Several servers can be saved: `mirrorbook servers` lists them, `mirrorbook use <name>` switches, `--server <name>` picks one for a single command.
11
+
12
+ ```bash
13
+ npx mirrorbook deploy ./dist --slug my-demo --wait --json
14
+ ```
15
+
16
+ - `<path>` can be a directory (with `index.html`, or `index.md` / `README.md`, at its root), a `.zip`, `.html`, `.md`, or `.txt` file, or `-` for stdin.
17
+ - Markdown (GitHub-flavored) and plain text are rendered into a readable web page. For stdin the format is auto-detected; pass `--format html|markdown|text` to be explicit. The quickest way to publish something you just wrote: `echo "$CONTENT" | npx mirrorbook deploy - --format markdown --slug my-notes --json`.
18
+ - Re-deploying the same `--slug` publishes a new version; it's safe to retry.
19
+ - If the slug is taken by someone else, a 4-character suffix is added (`demo` → `demo-k3x9`) and `slugAdjusted` is `true`. Always read the final `url`/`slug` from the output. Re-deploying with the original `--slug demo` keeps updating that same `demo-k3x9` site. Pass `--strict-slug` to fail (exit 2, `slug_taken`) instead.
20
+ - Output (with `--json`): `{"url","previewUrl","slug","deploymentId","status","error","errorCode","errorParams","number","created","requestedSlug","slugAdjusted"}`.
21
+ - When `status` is `failed`, `errorCode` says why: `missing_index` (no index.html at the zip root), `zip_invalid`, `zip_path_invalid`, `zip_encrypted`, `file_too_large`, `unzipped_too_large`, `too_many_files`, `quota_exceeded`, `upload_missing`, `file_read_failed`, `owner_missing`, `processing_failed`.
22
+ - Sites go live as soon as processing finishes (`status: "approved"`); admins review afterwards and may take a version down (`rejected`). A new account needs admin approval once before it can publish (exit 3, `pending_approval`).
23
+ - Each account has a site limit (default 10) and a storage quota (default 100 MB); going over exits with 4 (`quota_exceeded`).
24
+
25
+ Exit codes: 0 ok · 2 usage (bad path or slug) · 3 auth (missing token, account pending) · 4 quota · 5 failed or rejected.
26
+
27
+ Versions: every deploy gets a number (`#1`, `#2`, …, in the `number` field). The site URL shows the default version; every published version also has its own `previewUrl` that keeps working.
28
+
29
+ Password protection: `--password <pw> [--expires 7d|12h|2026-12-31|never]` on `deploy` (or `access <slug> --password … --expires …` later) makes the site unlisted and asks visitors for the password. After the expiry the site can't be opened until a new expiry or password is set. `access <slug> --remove-password` drops it, `access <slug> --public` makes the site public again. Prefer the `MIRRORBOOK_SITE_PASSWORD` env var over `--password` to keep it out of shell history.
30
+
31
+ Other commands: `access <slug>`, `ls`, `status <slug>` (lists versions), `rollback <slug> <version>` (alias `set-default`; version is `3`, `#3`, or a deployment id), `rm-version <slug> <version> --yes`, `rm <slug> --yes`, `whoami`. Add `--json` to any of them.
package/dist/cli.js ADDED
@@ -0,0 +1,511 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { spawn } from "child_process";
5
+ import { hostname, platform } from "os";
6
+ import { createInterface } from "readline/promises";
7
+ import { Command, Option } from "commander";
8
+
9
+ // ../shared/src/limits.ts
10
+ var LIMITS = {
11
+ uploadBytes: 50 * 1024 * 1024,
12
+ unzippedBytes: 200 * 1024 * 1024,
13
+ fileBytes: 50 * 1024 * 1024,
14
+ fileCount: 2e3,
15
+ defaultQuotaBytes: 100 * 1024 * 1024,
16
+ defaultMaxSites: 10
17
+ };
18
+
19
+ // ../shared/src/types.ts
20
+ var EXIT = {
21
+ ok: 0,
22
+ error: 1,
23
+ usage: 2,
24
+ auth: 3,
25
+ quota: 4,
26
+ rejected: 5
27
+ };
28
+
29
+ // ../shared/src/formats.ts
30
+ function formatFromFilename(name) {
31
+ const n = name.toLowerCase();
32
+ if (n.endsWith(".zip")) return "zip";
33
+ if (/\.html?$/.test(n)) return "html";
34
+ if (/\.(md|markdown|mdown|mkd)$/.test(n)) return "markdown";
35
+ if (n.endsWith(".txt")) return "text";
36
+ return null;
37
+ }
38
+ var FORMAT_EXTENSION = { html: "html", markdown: "md", text: "txt" };
39
+ function detectTextFormat(text) {
40
+ const head = text.trimStart().slice(0, 4096);
41
+ if (/^<!doctype html/i.test(head) || /<(html|head|body)[\s>]/i.test(head)) return "html";
42
+ if (/^<([a-z][a-z0-9-]*)[\s>]/i.test(head) && /<\/[a-z][a-z0-9-]*>/i.test(head)) return "html";
43
+ const sample = text.slice(0, 2e4);
44
+ const signals = [
45
+ /^#{1,6}\s+\S/m,
46
+ // # 标题
47
+ /^\s*[-*+]\s+\S/m,
48
+ // - 列表
49
+ /^\s*\d+\.\s+\S/m,
50
+ // 1. 列表
51
+ /^```/m,
52
+ // 代码块
53
+ /\[[^\]\n]+\]\([^)\s]+\)/,
54
+ // [链接](url)
55
+ /^\s*>\s+\S/m,
56
+ // > 引用
57
+ /^\|.+\|\s*$\n^\|?\s*:?-{3,}/m,
58
+ // | 表格 |
59
+ /\*\*[^*\n]+\*\*/,
60
+ // **加粗**
61
+ /^\s*[-*]\s+\[[ xX]\]\s/m
62
+ // - [ ] 任务
63
+ ];
64
+ return signals.filter((re) => re.test(sample)).length >= 2 ? "markdown" : "text";
65
+ }
66
+
67
+ // ../shared/src/packing.ts
68
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".svn", ".hg", ".next", ".cache", "__MACOSX"]);
69
+ var SKIP_FILES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", ".env"]);
70
+ var isSkippedFile = (name) => SKIP_FILES.has(name) || name.startsWith(".env.");
71
+
72
+ // src/api.ts
73
+ var CliError = class extends Error {
74
+ constructor(code, message, exitCode, status) {
75
+ super(message);
76
+ this.code = code;
77
+ this.exitCode = exitCode;
78
+ this.status = status;
79
+ }
80
+ code;
81
+ exitCode;
82
+ status;
83
+ };
84
+ var exitFor = (status, code) => status === 401 || code === "pending_approval" || code === "banned" || code === "account_rejected" ? 3 : code === "quota_exceeded" || code === "payload_too_large" ? 4 : code === "access_denied" || code === "expired_token" ? 3 : status === 400 || code === "invalid_slug" || code === "slug_taken" ? 2 : 1;
85
+ function createClient(apiUrl, token) {
86
+ async function call(method, p, body) {
87
+ const headers = { "user-agent": "mirrorbook-cli/0.1" };
88
+ if (token) headers.authorization = `Bearer ${token}`;
89
+ let payload;
90
+ if (body instanceof FormData) payload = body;
91
+ else if (body !== void 0) {
92
+ headers["content-type"] = "application/json";
93
+ payload = JSON.stringify(body);
94
+ }
95
+ let res;
96
+ try {
97
+ res = await fetch(`${apiUrl}/api${p}`, { method, headers, body: payload });
98
+ } catch (e) {
99
+ throw new CliError("network", `Can't reach ${apiUrl}: ${e.message}`, 1);
100
+ }
101
+ const json = await res.json().catch(() => ({}));
102
+ if (!res.ok) {
103
+ const code = json.error?.code ?? "http_error";
104
+ throw new CliError(code, json.error?.message ?? `HTTP ${res.status}`, exitFor(res.status, code), res.status);
105
+ }
106
+ return json;
107
+ }
108
+ return {
109
+ me: () => call("GET", "/me"),
110
+ deviceStart: (clientName) => call(
111
+ "POST",
112
+ "/cli/device",
113
+ { clientName }
114
+ ),
115
+ deviceToken: (deviceCode) => call("POST", "/cli/device/token", { deviceCode }),
116
+ deploy: (form) => call("POST", "/deploy", form),
117
+ sites: () => call("GET", "/sites"),
118
+ site: (slug) => call("GET", `/sites/${encodeURIComponent(slug)}`),
119
+ deployment: (id) => call("GET", `/deployments/${encodeURIComponent(id)}`),
120
+ updateSite: (slug, body) => call("PATCH", `/sites/${encodeURIComponent(slug)}`, body),
121
+ rollback: (slug, deploymentId) => call("POST", `/sites/${encodeURIComponent(slug)}/rollback`, { deploymentId }),
122
+ remove: (slug) => call("DELETE", `/sites/${encodeURIComponent(slug)}`),
123
+ removeDeployment: (slug, id) => call("DELETE", `/sites/${encodeURIComponent(slug)}/deployments/${encodeURIComponent(id)}`)
124
+ };
125
+ }
126
+
127
+ // src/config.ts
128
+ import { mkdir, readFile, rm, writeFile } from "fs/promises";
129
+ import { homedir } from "os";
130
+ import path from "path";
131
+ var DIR = path.join(process.env.XDG_CONFIG_HOME ?? path.join(homedir(), ".config"), "mirrorbook");
132
+ var FILE = path.join(DIR, "config.json");
133
+ var DEFAULT_API_URL = "https://mirrorbook.store";
134
+ var configPath = FILE;
135
+ function serverNameFromUrl(url) {
136
+ const u = new URL(url);
137
+ return u.port ? `${u.hostname}-${u.port}` : u.hostname;
138
+ }
139
+ var normalizeUrl = (url) => {
140
+ const withScheme = /^https?:\/\//.test(url) ? url : `https://${url}`;
141
+ return new URL(withScheme).origin;
142
+ };
143
+ async function loadConfig() {
144
+ let raw;
145
+ try {
146
+ raw = JSON.parse(await readFile(FILE, "utf8"));
147
+ } catch {
148
+ return { servers: {} };
149
+ }
150
+ if (!raw.servers && (raw.token || raw.apiUrl)) {
151
+ const url = normalizeUrl(raw.apiUrl ?? DEFAULT_API_URL);
152
+ const name = serverNameFromUrl(url);
153
+ return { current: name, servers: { [name]: { url, token: raw.token } } };
154
+ }
155
+ return { current: raw.current, servers: raw.servers ?? {} };
156
+ }
157
+ async function saveConfig(c) {
158
+ await mkdir(DIR, { recursive: true, mode: 448 });
159
+ await writeFile(FILE, JSON.stringify(c, null, 2), { mode: 384 });
160
+ }
161
+ async function resolveAuth(flags) {
162
+ const c = await loadConfig();
163
+ const name = flags.server ?? process.env.MIRRORBOOK_SERVER ?? c.current;
164
+ if ((flags.server || process.env.MIRRORBOOK_SERVER) && name && !c.servers[name]) {
165
+ throw new Error(`No server named ${name}. Run \`mirrorbook servers\` to see them`);
166
+ }
167
+ const saved = name ? c.servers[name] : void 0;
168
+ const explicitUrl = flags.apiUrl ?? process.env.MIRRORBOOK_API_URL;
169
+ const apiUrl = normalizeUrl(explicitUrl ?? saved?.url ?? DEFAULT_API_URL);
170
+ const sameServer = !explicitUrl || saved && normalizeUrl(saved.url) === apiUrl;
171
+ return {
172
+ name: sameServer ? name : serverNameFromUrl(apiUrl),
173
+ apiUrl,
174
+ token: flags.token ?? process.env.MIRRORBOOK_TOKEN ?? (sameServer ? saved?.token : void 0)
175
+ };
176
+ }
177
+
178
+ // src/pack.ts
179
+ import { readdir, readFile as readFile2, stat } from "fs/promises";
180
+ import path2 from "path";
181
+ import { zipSync } from "fflate";
182
+ async function walk(root, rel = "", out2 = {}) {
183
+ for (const ent of await readdir(path2.join(root, rel), { withFileTypes: true })) {
184
+ const r = rel ? `${rel}/${ent.name}` : ent.name;
185
+ if (ent.isDirectory()) {
186
+ if (!SKIP_DIRS.has(ent.name)) await walk(root, r, out2);
187
+ } else if (ent.isFile() && !isSkippedFile(ent.name)) {
188
+ out2[r] = await readFile2(path2.join(root, r));
189
+ }
190
+ }
191
+ return out2;
192
+ }
193
+ var readStdin = async () => {
194
+ const chunks = [];
195
+ for await (const c of process.stdin) chunks.push(c);
196
+ return Buffer.concat(chunks);
197
+ };
198
+ async function pack(input, format) {
199
+ if (input === "-") {
200
+ const buf2 = await readStdin();
201
+ if (!buf2.length) throw new CliError("usage", "stdin was empty", 2);
202
+ const f2 = format ?? detectTextFormat(buf2.toString("utf8"));
203
+ return { blob: new Blob([buf2]), name: `index.${FORMAT_EXTENSION[f2]}`, format: f2 };
204
+ }
205
+ const st = await stat(input).catch(() => null);
206
+ if (!st) throw new CliError("usage", `No such file or directory: ${input}`, 2);
207
+ if (st.isDirectory()) {
208
+ const files = await walk(input);
209
+ const hasIndex = files["index.html"] || Object.keys(files).some((p) => /^(index|readme)\.(md|markdown)$/i.test(p));
210
+ if (!hasIndex) throw new CliError("usage", `${input} has no index.html (or index.md / README.md) at its root`, 2);
211
+ return { blob: new Blob([zipSync(files, { level: 6 })], { type: "application/zip" }), name: "site.zip", files: Object.keys(files).length };
212
+ }
213
+ const byName = formatFromFilename(input);
214
+ if (!byName) throw new CliError("usage", "Deploy a directory, or a .zip, .html, .md, or .txt file", 2);
215
+ const buf = await readFile2(input);
216
+ const f = byName === "zip" ? void 0 : format ?? byName;
217
+ return { blob: new Blob([buf]), name: path2.basename(input), format: f };
218
+ }
219
+
220
+ // package.json
221
+ var package_default = {
222
+ name: "mirrorbook",
223
+ version: "0.1.0",
224
+ description: "Publish HTML to a shareable URL. Agent-friendly: non-interactive, --json output, stable exit codes.",
225
+ type: "module",
226
+ bin: {
227
+ mirrorbook: "dist/cli.js",
228
+ mb: "dist/cli.js"
229
+ },
230
+ files: [
231
+ "dist",
232
+ "SKILL.md"
233
+ ],
234
+ engines: {
235
+ node: ">=20"
236
+ },
237
+ scripts: {
238
+ dev: "tsx src/cli.ts",
239
+ build: "tsup",
240
+ typecheck: "tsc -p ."
241
+ },
242
+ devDependencies: {
243
+ "@mirrorbook/shared": "workspace:*"
244
+ },
245
+ dependencies: {
246
+ commander: "^15.0.0",
247
+ fflate: "^0.8.3"
248
+ }
249
+ };
250
+
251
+ // src/cli.ts
252
+ var program = new Command().name("mirrorbook").description("Publish HTML to a shareable URL on mirrorbook.store").version(package_default.version).addOption(new Option("--json", "print one JSON object to stdout (also MIRRORBOOK_JSON=1)").default(process.env.MIRRORBOOK_JSON === "1")).option("-n, --server <name>", "use a saved server for this command (env MIRRORBOOK_SERVER); see `mirrorbook servers`").option("--api-url <url>", "server URL, overrides the saved one (env MIRRORBOOK_API_URL)").option("--token <token>", "API token, overrides the saved one (env MIRRORBOOK_TOKEN)").showHelpAfterError().addHelpText(
253
+ "after",
254
+ `
255
+ Exit codes: 0 ok \xB7 1 error \xB7 2 usage \xB7 3 auth \xB7 4 quota \xB7 5 deployment failed or rejected
256
+
257
+ Examples:
258
+ $ mirrorbook login https://mirrorbook.store # opens the browser to approve
259
+ $ mirrorbook deploy ./dist --slug my-demo --wait --json
260
+ $ cat page.html | mirrorbook deploy - --slug quick-note
261
+ $ mirrorbook deploy notes.md --slug my-notes # Markdown \u2192 web page
262
+ $ pbpaste | mirrorbook deploy - --format markdown
263
+ $ mirrorbook servers # saved servers; switch with \`mirrorbook use <name>\`
264
+ $ MIRRORBOOK_TOKEN=mb_xxx MIRRORBOOK_API_URL=https://mirrorbook.store mirrorbook ls --json`
265
+ );
266
+ var g = () => program.opts();
267
+ function out(human, data) {
268
+ if (g().json) process.stdout.write(`${JSON.stringify(data)}
269
+ `);
270
+ else console.log(human);
271
+ }
272
+ var info = (msg) => process.stderr.write(`${msg}
273
+ `);
274
+ async function auth() {
275
+ try {
276
+ return await resolveAuth(g());
277
+ } catch (e) {
278
+ throw new CliError("usage", e.message, EXIT.usage);
279
+ }
280
+ }
281
+ async function client(requireToken = true) {
282
+ const { apiUrl, token, name } = await auth();
283
+ if (requireToken && !token) {
284
+ throw new CliError("unauthorized", `Not logged in to ${name ?? apiUrl}. Run \`mirrorbook login ${apiUrl}\` or set MIRRORBOOK_TOKEN`, EXIT.auth);
285
+ }
286
+ return createClient(apiUrl, token);
287
+ }
288
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
289
+ async function waitFor(api, id, timeoutSec) {
290
+ const deadline = Date.now() + timeoutSec * 1e3;
291
+ const pending = /* @__PURE__ */ new Set(["processing"]);
292
+ for (; ; ) {
293
+ const r = await api.deployment(id);
294
+ if (!pending.has(r.deployment.status)) return r;
295
+ if (Date.now() > deadline) throw new CliError("timeout", `Still ${r.deployment.status} after ${timeoutSec}s`, EXIT.error);
296
+ await sleep(2e3);
297
+ }
298
+ }
299
+ var describe = (d, isDefault) => ({
300
+ processing: "processing",
301
+ failed: `failed${d.errorCode ? ` [${d.errorCode}]` : ""}: ${d.error ?? "unknown error"}`,
302
+ pending_review: "live",
303
+ approved: isDefault === false ? "published" : "live",
304
+ rejected: `rejected${d.reviewNote ? `: ${d.reviewNote}` : ""}`
305
+ })[d.status];
306
+ var deploymentExit = (d) => d.status === "failed" || d.status === "rejected" ? EXIT.rejected : EXIT.ok;
307
+ function openBrowser(url) {
308
+ const [cmd, args] = platform() === "darwin" ? ["open", [url]] : platform() === "win32" ? ["cmd", ["/c", "start", "", url]] : ["xdg-open", [url]];
309
+ try {
310
+ spawn(cmd, args, { stdio: "ignore", detached: true }).on("error", () => {
311
+ }).unref();
312
+ } catch {
313
+ }
314
+ }
315
+ async function readStdin2() {
316
+ const chunks = [];
317
+ for await (const c of process.stdin) chunks.push(c);
318
+ return Buffer.concat(chunks).toString().trim();
319
+ }
320
+ async function deviceLogin(apiUrl, openIt) {
321
+ const api = createClient(apiUrl);
322
+ const start = await api.deviceStart(`${hostname()} (${platform()})`);
323
+ info(`
324
+ To sign in, open this page and approve the request:
325
+
326
+ ${start.verificationUrlComplete}
327
+
328
+ Make sure it shows this code: ${start.userCode}
329
+ `);
330
+ if (openIt) openBrowser(start.verificationUrlComplete);
331
+ info("Waiting for approval\u2026 (Ctrl+C to cancel)");
332
+ const deadline = Date.now() + start.expiresIn * 1e3;
333
+ while (Date.now() < deadline) {
334
+ await sleep(start.interval * 1e3);
335
+ try {
336
+ return await api.deviceToken(start.deviceCode);
337
+ } catch (e) {
338
+ if (e instanceof CliError && e.code === "authorization_pending") continue;
339
+ if (e instanceof CliError && e.code === "access_denied") throw new CliError("access_denied", "The login request was denied in the browser", EXIT.auth);
340
+ if (e instanceof CliError && e.code === "expired_token") throw new CliError("expired_token", "The login request expired. Run login again", EXIT.auth);
341
+ throw e;
342
+ }
343
+ }
344
+ throw new CliError("expired_token", "The login request expired. Run login again", EXIT.auth);
345
+ }
346
+ program.command("login").description("Sign in to a server. Opens the browser to approve (like `caprover login`); saves the server so you can switch later.").argument("[url]", `server URL (default: the current server, or ${DEFAULT_API_URL})`).option("--name <alias>", "name to save this server as (default: its hostname)").option("--with-token", "read an API token from stdin instead of opening the browser (for CI)").option("--no-browser", "don't open the browser automatically; just print the URL").action(async (urlArg, o) => {
347
+ const current = await auth();
348
+ const apiUrl = urlArg ? normalizeUrl(urlArg) : current.apiUrl;
349
+ const name = o.name ?? serverNameFromUrl(apiUrl);
350
+ let token = g().token ?? process.env.MIRRORBOOK_TOKEN;
351
+ if (!token && o.withToken) token = await readStdin2();
352
+ let user;
353
+ if (token) {
354
+ ({ user } = await createClient(apiUrl, token).me());
355
+ } else {
356
+ ({ token, user } = await deviceLogin(apiUrl, o.browser && !process.env.CI));
357
+ }
358
+ const cfg = await loadConfig();
359
+ cfg.servers[name] = { url: apiUrl, token, email: user.email, handle: user.handle };
360
+ cfg.current = name;
361
+ await saveConfig(cfg);
362
+ out(`Logged in to ${name} (${apiUrl}) as ${user.email}. It's now the current server.`, { ok: true, server: name, url: apiUrl, user, configPath });
363
+ });
364
+ program.command("logout").description("Forget a saved server and its token (default: the current one)").argument("[name]").action(async (nameArg) => {
365
+ const cfg = await loadConfig();
366
+ const name = nameArg ?? g().server ?? cfg.current;
367
+ if (!name || !cfg.servers[name]) throw new CliError("usage", nameArg ? `No server named ${nameArg}` : "Not logged in", EXIT.usage);
368
+ delete cfg.servers[name];
369
+ if (cfg.current === name) cfg.current = Object.keys(cfg.servers)[0];
370
+ await saveConfig(cfg);
371
+ out(`Logged out of ${name}${cfg.current ? `. Current server: ${cfg.current}` : ""}`, { ok: true, server: name, current: cfg.current ?? null });
372
+ });
373
+ program.command("servers").description("List saved servers (* marks the current one)").action(async () => {
374
+ const cfg = await loadConfig();
375
+ const rows = Object.entries(cfg.servers).map(([name, s]) => ({ name, url: s.url, email: s.email ?? null, current: name === cfg.current, loggedIn: !!s.token }));
376
+ out(
377
+ rows.length ? rows.map((r) => `${r.current ? "*" : " "} ${r.name.padEnd(24)} ${r.url.padEnd(32)} ${r.email ?? (r.loggedIn ? "(signed in)" : "(not signed in)")}`).join("\n") : "No servers yet. Run `mirrorbook login <url>`",
378
+ { servers: rows }
379
+ );
380
+ });
381
+ program.command("use").description("Switch the current server").argument("<name>", "a name from `mirrorbook servers`").action(async (name) => {
382
+ const cfg = await loadConfig();
383
+ if (!cfg.servers[name]) throw new CliError("usage", `No server named ${name}. Run \`mirrorbook servers\``, EXIT.usage);
384
+ cfg.current = name;
385
+ await saveConfig(cfg);
386
+ out(`Now using ${name} (${cfg.servers[name].url})`, { ok: true, server: name, url: cfg.servers[name].url });
387
+ });
388
+ program.command("whoami").description("Show the current server and account").action(async () => {
389
+ const { name, apiUrl } = await auth();
390
+ const { user } = await (await client()).me();
391
+ out(`${user.email} (@${user.handle}, ${user.role}, ${user.status}) on ${name ?? apiUrl} \xB7 ${apiUrl}`, { server: name ?? null, url: apiUrl, user });
392
+ });
393
+ function parseExpiry(v, now = Date.now()) {
394
+ const rel = /^(\d+)\s*([mhdw])$/i.exec(v.trim());
395
+ if (rel) return new Date(now + Number(rel[1]) * { m: 6e4, h: 36e5, d: 864e5, w: 6048e5 }[rel[2].toLowerCase()]).toISOString();
396
+ const at = new Date(v);
397
+ if (Number.isNaN(at.getTime())) throw new CliError("usage", `Can't read expiry "${v}". Use 7d, 12h, 30m, or a date like 2026-12-31`, EXIT.usage);
398
+ return at.toISOString();
399
+ }
400
+ async function applyAccess(api, slug, o) {
401
+ const password = o.password ?? process.env.MIRRORBOOK_SITE_PASSWORD;
402
+ const body = {};
403
+ if (o.public) body.visibility = "public";
404
+ else if (o.removePassword) body.password = null;
405
+ else if (password || o.expires) {
406
+ body.visibility = "unlisted";
407
+ if (password) body.password = password;
408
+ }
409
+ if (o.expires && !o.public && !o.removePassword) body.passwordExpiresAt = o.expires === "never" ? null : parseExpiry(o.expires);
410
+ if (!Object.keys(body).length) return null;
411
+ return (await api.updateSite(slug, body)).site;
412
+ }
413
+ var accessLine = (s) => s.passwordProtected ? `password-protected${s.passwordExpiresAt ? `, expires ${s.passwordExpiresAt.slice(0, 16).replace("T", " ")} UTC` : ", no expiry"}` : s.visibility === "unlisted" ? "unlisted" : "public";
414
+ program.command("deploy").description("Publish a directory, .zip, .html, .md, or .txt file. Markdown and text are turned into a web page. Re-deploying the same slug publishes a new version.").argument("<path>", "directory (with index.html or README.md), a .zip/.html/.md/.txt file, or - for stdin").option("-s, --slug <slug>", "subdomain: <slug>.mirrorbook.store (random if omitted; a suffix is added if it's taken)").option("--strict-slug", "fail with exit code 2 instead of adding a suffix when the slug is taken").option("-t, --title <title>", "site title").addOption(new Option("-f, --format <format>", "treat the input as html, markdown, or text (default: from the file extension; stdin is auto-detected)").choices(["html", "markdown", "text"])).option("-w, --wait", "wait until processing finishes").option("--timeout <sec>", "max seconds to wait", "300").option("--password <password>", "protect the site with a password (makes it unlisted; env MIRRORBOOK_SITE_PASSWORD avoids shell history)").option("--expires <when>", "how long the password stays valid: 7d, 12h, a date like 2026-12-31, or never").action(async (input, o) => {
415
+ const api = await client();
416
+ const { blob, name, files, format } = await pack(input, o.format);
417
+ const form = new FormData();
418
+ form.set("file", blob, name);
419
+ if (format) form.set("format", format);
420
+ if (o.slug) form.set("slug", o.slug);
421
+ if (o.title) form.set("title", o.title);
422
+ if (o.strictSlug) form.set("onConflict", "error");
423
+ const res = await api.deploy(form);
424
+ const { created, requestedSlug, slugAdjusted } = res;
425
+ let { site, deployment } = res;
426
+ site = await applyAccess(api, site.slug, o) ?? site;
427
+ if (o.wait) ({ site, deployment } = await waitFor(api, deployment.id, Number(o.timeout)));
428
+ out(
429
+ [
430
+ `${created ? "Created" : "Updated"} ${site.slug} #${deployment.number} (${files ?? 1} file${(files ?? 1) === 1 ? "" : "s"})`,
431
+ ...slugAdjusted && requestedSlug ? [` note: ${requestedSlug} is taken, using ${site.slug}. Re-deploying with --slug ${requestedSlug} updates this same site.`] : [],
432
+ ` url: ${site.url}`,
433
+ ...site.passwordProtected ? [` access: ${accessLine(site)}`] : [],
434
+ ` preview: ${deployment.previewUrl}`,
435
+ ` status: ${describe(deployment)}`
436
+ ].join("\n"),
437
+ { url: site.url, visibility: site.visibility, passwordProtected: site.passwordProtected, passwordExpiresAt: site.passwordExpiresAt, previewUrl: deployment.previewUrl, slug: site.slug, siteId: site.id, deploymentId: deployment.id, status: deployment.status, error: deployment.error, errorCode: deployment.errorCode, errorParams: deployment.errorParams, number: deployment.number, created, requestedSlug, slugAdjusted }
438
+ );
439
+ process.exitCode = deploymentExit(deployment);
440
+ });
441
+ program.command("access").description("Set or change who can open a site: a password (with an expiry), or back to public").argument("<slug>").option("--password <password>", "set or change the password (makes the site unlisted; env MIRRORBOOK_SITE_PASSWORD avoids shell history)").option("--expires <when>", "password validity: 7d, 12h, a date like 2026-12-31, or never. After it, the site can't be opened until you set a new one").option("--remove-password", "remove the password (the site stays unlisted)").option("--public", "make the site public again (also removes the password)").action(async (slug, o) => {
442
+ const api = await client();
443
+ const site = await applyAccess(api, slug, o);
444
+ if (!site) throw new CliError("usage", "Nothing to change. Pass --password, --expires, --remove-password, or --public", EXIT.usage);
445
+ out(`${site.slug}: ${accessLine(site)}`, { slug: site.slug, visibility: site.visibility, passwordProtected: site.passwordProtected, passwordExpiresAt: site.passwordExpiresAt });
446
+ });
447
+ program.command("ls").description("List your sites").action(async () => {
448
+ const { sites } = await (await client()).sites();
449
+ out(sites.length ? sites.map((s) => `${s.slug.padEnd(28)} ${(s.activeDeploymentId ? "live" : "not live").padEnd(9)} ${s.url}${s.passwordProtected ? " \u{1F512}" : ""}`).join("\n") : "No sites yet", { sites });
450
+ });
451
+ program.command("status").description("Show a site and its recent versions").argument("<slug>").action(async (slug) => {
452
+ const { site, deployments } = await (await client()).site(slug);
453
+ const lines = [`${site.slug} ${site.url} (${site.status}, ${site.views} views, ${accessLine(site)})`];
454
+ if (site.requestedSlug && site.requestedSlug !== site.slug) lines.push(` requested as: ${site.requestedSlug}`);
455
+ for (const d of deployments.slice(0, 20)) {
456
+ const mark = d.id === site.activeDeploymentId ? "\u25CF" : " ";
457
+ lines.push(` ${mark} #${String(d.number).padEnd(4)} ${d.createdAt.slice(0, 16).replace("T", " ")} ${describe(d, d.id === site.activeDeploymentId).padEnd(26)} ${d.previewUrl}`);
458
+ }
459
+ out(lines.join("\n"), { site, deployments });
460
+ });
461
+ program.command("wait").description("Block until a deployment finishes processing").argument("<deploymentId>").option("--timeout <sec>", "max seconds to wait", "300").action(async (id, o) => {
462
+ const { site, deployment } = await waitFor(await client(), id, Number(o.timeout));
463
+ out(`${site.slug}: ${describe(deployment)}`, { url: site.url, deploymentId: deployment.id, status: deployment.status, error: deployment.error, errorCode: deployment.errorCode, errorParams: deployment.errorParams });
464
+ process.exitCode = deploymentExit(deployment);
465
+ });
466
+ async function resolveVersion(api, slug, ref) {
467
+ const { deployments } = await api.site(slug);
468
+ const n = /^#?(\d+)$/.exec(ref)?.[1];
469
+ const d = n ? deployments.find((x) => x.number === Number(n)) : deployments.find((x) => x.id === ref);
470
+ if (!d) throw new CliError("not_found", `${slug} has no version ${ref}`, EXIT.usage);
471
+ return d;
472
+ }
473
+ program.command("rollback").alias("set-default").description("Make an approved version the default (what the site URL shows)").argument("<slug>").argument("<version>", "version number (3 or #3) or deployment id").action(async (slug, ref) => {
474
+ const api = await client();
475
+ const d = await resolveVersion(api, slug, ref);
476
+ await api.rollback(slug, d.id);
477
+ out(`${slug} now serves #${d.number}`, { ok: true, slug, deploymentId: d.id, number: d.number });
478
+ });
479
+ program.command("rm-version").description("Delete one version (not the default one)").argument("<slug>").argument("<version>", "version number (3 or #3) or deployment id").option("-y, --yes", "skip the confirmation (required when not a TTY)").action(async (slug, ref, o) => {
480
+ const api = await client();
481
+ const d = await resolveVersion(api, slug, ref);
482
+ if (!o.yes) {
483
+ if (!process.stdin.isTTY) throw new CliError("usage", "Refusing to delete without --yes", EXIT.usage);
484
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
485
+ const a = await rl.question(`Delete ${slug} version #${d.number}? [y/N] `);
486
+ rl.close();
487
+ if (a.trim().toLowerCase() !== "y") throw new CliError("usage", "Cancelled", EXIT.usage);
488
+ }
489
+ await api.removeDeployment(slug, d.id);
490
+ out(`Deleted ${slug} #${d.number}`, { ok: true, slug, deploymentId: d.id, number: d.number });
491
+ });
492
+ program.command("rm").description("Delete a site and all its versions").argument("<slug>").option("-y, --yes", "skip the confirmation (required when not a TTY)").action(async (slug, o) => {
493
+ if (!o.yes) {
494
+ if (!process.stdin.isTTY) throw new CliError("usage", "Refusing to delete without --yes", EXIT.usage);
495
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
496
+ const a = await rl.question(`Delete ${slug} and all its versions? Type the slug to confirm: `);
497
+ rl.close();
498
+ if (a.trim() !== slug) throw new CliError("usage", "Cancelled", EXIT.usage);
499
+ }
500
+ await (await client()).remove(slug);
501
+ out(`Deleted ${slug}`, { ok: true, slug });
502
+ });
503
+ try {
504
+ await program.parseAsync();
505
+ } catch (e) {
506
+ const err = e instanceof CliError ? e : new CliError("internal", e.message, EXIT.error);
507
+ if (g().json) process.stdout.write(`${JSON.stringify({ error: { code: err.code, message: err.message } })}
508
+ `);
509
+ else console.error(`error: ${err.message}`);
510
+ process.exitCode = err.exitCode;
511
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "mirrorbook",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Publish HTML to a shareable URL. Agent-friendly: non-interactive, --json output, stable exit codes.",
5
+ "type": "module",
6
+ "bin": {
7
+ "mirrorbook": "dist/cli.js",
8
+ "mb": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "SKILL.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=20"
16
+ },
17
+ "devDependencies": {
18
+ "@mirrorbook/shared": "0.0.0"
19
+ },
20
+ "dependencies": {
21
+ "commander": "^15.0.0",
22
+ "fflate": "^0.8.3"
23
+ },
24
+ "scripts": {
25
+ "dev": "tsx src/cli.ts",
26
+ "build": "tsup",
27
+ "typecheck": "tsc -p ."
28
+ }
6
29
  }
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.