@bangerpage/cli 0.2.1 → 0.2.3

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/dist/bin.js CHANGED
@@ -141,6 +141,7 @@ async function revokeToken(host, token, fetchImpl = fetch) {
141
141
  function storedToken(host, env = process.env) {
142
142
  return readCredentials(env).hosts[host]?.token ?? null;
143
143
  }
144
+ var API_TIMEOUT_MS = 6e4;
144
145
  var ApiError = class extends Error {
145
146
  constructor(status, code, message) {
146
147
  super(message);
@@ -158,6 +159,9 @@ var PlatformClient = class {
158
159
  me() {
159
160
  return this.call("GET", "/api/v1/me");
160
161
  }
162
+ deck(slug) {
163
+ return this.call("GET", `/api/v1/decks/${encodeURIComponent(slug)}`);
164
+ }
161
165
  beginUpload(files) {
162
166
  return this.call("POST", "/api/v1/uploads", { files });
163
167
  }
@@ -181,13 +185,18 @@ var PlatformClient = class {
181
185
  accept: "application/json",
182
186
  ...body === void 0 ? {} : { "content-type": "application/json" }
183
187
  },
184
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
188
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
189
+ signal: AbortSignal.timeout(API_TIMEOUT_MS)
185
190
  });
186
191
  } catch (error) {
187
192
  throw new ApiError(0, "network", `could not reach ${this.host}: ${error.message}`);
188
193
  }
189
194
  if (!response.ok) throw await apiError(response);
190
- return await response.json();
195
+ try {
196
+ return await response.json();
197
+ } catch (error) {
198
+ throw new ApiError(response.status, "invalid_response", `${this.host} sent a response that is not JSON: ${error.message}`);
199
+ }
191
200
  }
192
201
  };
193
202
  async function apiError(response) {
@@ -223,7 +232,7 @@ async function authorizeInBrowser(host, opts = {}) {
223
232
  const { verifier, challenge } = pkcePair();
224
233
  const state = base64url(randomBytes(16));
225
234
  let settle;
226
- const result = new Promise((resolve6, reject) => settle = { resolve: resolve6, reject });
235
+ const result = new Promise((resolve7, reject) => settle = { resolve: resolve7, reject });
227
236
  const server = createServer((req, res) => {
228
237
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
229
238
  if (url.pathname !== "/callback") {
@@ -244,9 +253,9 @@ async function authorizeInBrowser(host, opts = {}) {
244
253
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(PAGE("Logged in to Banger. You can close this tab and go back to the terminal."));
245
254
  settle?.resolve(code);
246
255
  });
247
- await new Promise((resolve6, reject) => {
256
+ await new Promise((resolve7, reject) => {
248
257
  server.once("error", reject);
249
- server.listen(0, "127.0.0.1", () => resolve6());
258
+ server.listen(0, "127.0.0.1", () => resolve7());
250
259
  });
251
260
  const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
252
261
  const authorize = new URL(`${host}/authorize`);
@@ -551,6 +560,7 @@ function resolveWithin(root, urlPath) {
551
560
  }
552
561
  var RELOAD_SNIPPET = `<script>new EventSource("/__banger/events").addEventListener("reload",()=>location.reload())</script>`;
553
562
  var EVENTS_PATH = "/__banger/events";
563
+ var STATUS_PATH = "/__banger/status";
554
564
  var CORE_PREFIX = "/__banger/core/";
555
565
  async function startServer(opts) {
556
566
  readInput(opts.file);
@@ -558,6 +568,7 @@ async function startServer(opts) {
558
568
  const root = dirname3(file);
559
569
  const served = /* @__PURE__ */ new Set();
560
570
  const clients = /* @__PURE__ */ new Set();
571
+ let listenPort = 0;
561
572
  const send = (res, status, body, type = "text/plain; charset=utf-8") => {
562
573
  res.writeHead(status, { "content-type": type, "cache-control": "no-store" });
563
574
  res.end(body);
@@ -572,6 +583,16 @@ async function startServer(opts) {
572
583
  req.on("close", () => clients.delete(res));
573
584
  return;
574
585
  }
586
+ if (urlPath === STATUS_PATH && opts.status) {
587
+ const host = (req.headers.host ?? "").toLowerCase();
588
+ if (host !== `127.0.0.1:${listenPort}` && host !== `localhost:${listenPort}`) return send(res, 403, "forbidden");
589
+ if (req.method === "HEAD") return send(res, 200, "", "application/json; charset=utf-8");
590
+ opts.status().then(
591
+ (status) => send(res, 200, JSON.stringify(status), "application/json; charset=utf-8"),
592
+ () => send(res, 500, "status unavailable")
593
+ );
594
+ return;
595
+ }
575
596
  const isCore = urlPath.startsWith(CORE_PREFIX);
576
597
  const target = isCore ? resolveWithin(coreDistDir(), urlPath.slice(CORE_PREFIX.length)) : resolveWithin(root, urlPath === "/" ? basename(file) : urlPath);
577
598
  if (!target || !existsSync3(target) || !statSync2(target).isFile()) return send(res, 404, "not found");
@@ -584,7 +605,7 @@ async function startServer(opts) {
584
605
  }
585
606
  res.writeHead(200, { "content-type": type, "cache-control": "no-store" });
586
607
  if (req.method === "HEAD") return res.end();
587
- createReadStream(target).pipe(res);
608
+ createReadStream(target).on("error", () => res.destroy()).pipe(res);
588
609
  });
589
610
  await new Promise((resolveListen, rejectListen) => {
590
611
  server.once("error", (error) => {
@@ -594,6 +615,7 @@ async function startServer(opts) {
594
615
  });
595
616
  server.listen(opts.port ?? 0, "127.0.0.1", resolveListen);
596
617
  });
618
+ listenPort = server.address().port;
597
619
  let watcher;
598
620
  let timer;
599
621
  if (opts.watch) {
@@ -962,35 +984,14 @@ function runInit(argv) {
962
984
  return 0;
963
985
  }
964
986
 
965
- // src/commands/preview.ts
966
- var USAGE4 = "usage: banger preview [file] [--port N]";
967
- async function runPreview(argv) {
968
- if (argv.includes("--help")) {
969
- process.stdout.write(`${USAGE4}
970
- `);
971
- return 0;
972
- }
973
- const { values, positionals } = parseArgsStrict(argv, { port: { type: "string" } });
974
- const file = deckFile(positionals, USAGE4);
975
- const port = values.port === void 0 ? 4321 : Number(values.port);
976
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError(2, `invalid --port: ${values.port}`);
977
- const warning = runtimeVersionWarning(readInput(file), CORE_PACKAGE, coreVersion());
978
- if (warning) process.stderr.write(`warning: ${warning.message}
979
- `);
980
- const stopped = new Promise((resolveStop) => process.once("SIGINT", resolveStop));
981
- const server = await startServer({ file, watch: true, port });
982
- process.stdout.write(`${server.url}
983
- `);
984
- await stopped;
985
- await server.close();
986
- return 0;
987
- }
987
+ // src/platform/status.ts
988
+ import { basename as basename4, dirname as dirname5, resolve as resolve5 } from "node:path";
988
989
 
989
990
  // src/commands/publish.ts
990
991
  import { createHash as createHash2, randomUUID } from "node:crypto";
991
992
  import { existsSync as existsSync5, mkdirSync as mkdirSync3, readdirSync, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
992
993
  import { basename as basename3, extname as extname3, join as join6, relative, resolve as resolve4, sep as sep2 } from "node:path";
993
- var USAGE5 = "usage: banger publish [dir] [--slug <slug>] [--title <title>] [--visibility public|unlisted] [--strict] [--skip-check] [--dry-run]";
994
+ var USAGE4 = "usage: banger publish [dir] [--slug <slug>] [--title <title>] [--visibility public|unlisted] [--strict] [--skip-check] [--dry-run]";
994
995
  var ACCEPTED = Object.fromEntries(
995
996
  [".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg", ".woff2", ".mp4", ".webm", ".json", ".css", ".js", ".pdf"].map((e) => [e, true])
996
997
  );
@@ -1064,7 +1065,7 @@ function writeState(dir, state) {
1064
1065
  }
1065
1066
  async function runPublish(argv, fetchImpl = fetch) {
1066
1067
  if (argv.includes("--help")) {
1067
- process.stdout.write(`${USAGE5}
1068
+ process.stdout.write(`${USAGE4}
1068
1069
  `);
1069
1070
  return 0;
1070
1071
  }
@@ -1076,11 +1077,11 @@ async function runPublish(argv, fetchImpl = fetch) {
1076
1077
  "skip-check": { type: "boolean" },
1077
1078
  "dry-run": { type: "boolean" }
1078
1079
  });
1079
- if (positionals.length > 1) throw new CliError(2, USAGE5);
1080
+ if (positionals.length > 1) throw new CliError(2, USAGE4);
1080
1081
  const dir = positionals[0] ?? ".";
1081
1082
  if (values.visibility !== void 0 && values.visibility !== "public" && values.visibility !== "unlisted") {
1082
1083
  throw new CliError(2, `--visibility must be public or unlisted
1083
- ${USAGE5}`);
1084
+ ${USAGE4}`);
1084
1085
  }
1085
1086
  if (values.slug !== void 0 && slugFrom(values.slug) !== values.slug) {
1086
1087
  throw new CliError(2, `--slug may use lower case letters, digits and single hyphens: ${values.slug}`);
@@ -1170,10 +1171,133 @@ the deck ${known.slug} is gone; delete ${statePath(dir)} to publish it as a new
1170
1171
  return 0;
1171
1172
  }
1172
1173
 
1174
+ // src/platform/status.ts
1175
+ var STATUS_TTL_MS = 3e4;
1176
+ var STATUS_TIMEOUT_MS = 3e3;
1177
+ var SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1178
+ var webUrl = (value) => {
1179
+ if (typeof value !== "string") return void 0;
1180
+ try {
1181
+ const url = new URL(value);
1182
+ return url.protocol === "http:" || url.protocol === "https:" ? value : void 0;
1183
+ } catch {
1184
+ return void 0;
1185
+ }
1186
+ };
1187
+ var nonEmpty = (value) => typeof value === "string" && value !== "" ? value : void 0;
1188
+ var positiveInt = (value) => typeof value === "number" && Number.isInteger(value) && value >= 1 ? value : void 0;
1189
+ function avatarOf(value, host) {
1190
+ if (typeof value !== "string") return void 0;
1191
+ try {
1192
+ const url = new URL(value);
1193
+ return url.protocol === "https:" && url.origin === new URL(host).origin ? url.href : void 0;
1194
+ } catch {
1195
+ return void 0;
1196
+ }
1197
+ }
1198
+ function accountOf(me, host) {
1199
+ if (me.status === "fulfilled") {
1200
+ const username = nonEmpty(me.value?.username);
1201
+ if (!username) return { state: "unavailable" };
1202
+ const displayName = nonEmpty(me.value.display_name);
1203
+ const avatarUrl = avatarOf(me.value.avatar_url, host);
1204
+ return { state: "logged_in", username, ...displayName ? { displayName } : {}, ...avatarUrl ? { avatarUrl } : {} };
1205
+ }
1206
+ return me.reason instanceof ApiError && me.reason.status === 401 ? { state: "invalid" } : { state: "unavailable" };
1207
+ }
1208
+ var unverifiedDeck = (url) => ({ state: "unverified", ...url ? { url } : {} });
1209
+ function deckOf(info, record) {
1210
+ if (!record) return { state: "none" };
1211
+ const recordUrl = record.url;
1212
+ const unverified = unverifiedDeck(recordUrl);
1213
+ if (info.status === "rejected") {
1214
+ const error = info.reason;
1215
+ return error instanceof ApiError && error.status === 404 && error.code === "not_found" ? { state: "missing", ...recordUrl ? { url: recordUrl } : {} } : unverified;
1216
+ }
1217
+ const deck = info.value;
1218
+ if (!deck || typeof deck !== "object") return unverified;
1219
+ const url = webUrl(deck.url) ?? recordUrl;
1220
+ if (deck.status === "unpublished") return { state: "unpublished", ...url ? { url } : {} };
1221
+ if (deck.status === "published" && (deck.visibility === "public" || deck.visibility === "unlisted")) {
1222
+ const version2 = positiveInt(deck.current_version) ?? positiveInt(deck.version);
1223
+ return { state: "published", visibility: deck.visibility, ...version2 ? { version: version2 } : {}, ...url ? { url } : {} };
1224
+ }
1225
+ return unverified;
1226
+ }
1227
+ function createStatusProvider(opts) {
1228
+ const env = opts.env ?? process.env;
1229
+ const fetchImpl = opts.fetchImpl ?? fetch;
1230
+ const now = opts.now ?? Date.now;
1231
+ const timeoutMs = opts.timeoutMs ?? STATUS_TIMEOUT_MS;
1232
+ let cache;
1233
+ const readRecord = (host) => {
1234
+ if (basename4(opts.file) !== "index.html") return null;
1235
+ try {
1236
+ const entry2 = readState(dirname5(resolve5(opts.file))).decks[host];
1237
+ if (!entry2 || typeof entry2.slug !== "string" || !SLUG.test(entry2.slug)) return null;
1238
+ const url = webUrl(entry2.url);
1239
+ return { slug: entry2.slug, ...url ? { url } : {} };
1240
+ } catch {
1241
+ return null;
1242
+ }
1243
+ };
1244
+ const collect = async () => {
1245
+ try {
1246
+ const host = platformHost(env);
1247
+ const record = readRecord(host);
1248
+ let token;
1249
+ try {
1250
+ token = tokenFor(host, env);
1251
+ } catch {
1252
+ token = null;
1253
+ }
1254
+ const recordDeck = () => record ? unverifiedDeck(record.url) : { state: "none" };
1255
+ if (token === null) return { account: { state: "logged_out" }, deck: recordDeck() };
1256
+ const timed = (input, init) => fetchImpl(input, { ...init, signal: AbortSignal.timeout(timeoutMs) });
1257
+ const client = new PlatformClient(host, token, timed);
1258
+ const [me, info] = await Promise.allSettled([client.me(), record ? client.deck(record.slug) : Promise.resolve(null)]);
1259
+ const account = accountOf(me, host);
1260
+ return { account, deck: account.state === "logged_in" ? deckOf(info, record) : recordDeck() };
1261
+ } catch {
1262
+ return { account: { state: "unavailable" }, deck: { state: "none" } };
1263
+ }
1264
+ };
1265
+ return () => {
1266
+ if (cache && now() - cache.at < STATUS_TTL_MS) return cache.value;
1267
+ const value = collect();
1268
+ cache = { at: now(), value };
1269
+ return value;
1270
+ };
1271
+ }
1272
+
1273
+ // src/commands/preview.ts
1274
+ var USAGE5 = "usage: banger preview [file] [--port N]";
1275
+ async function runPreview(argv) {
1276
+ if (argv.includes("--help")) {
1277
+ process.stdout.write(`${USAGE5}
1278
+ `);
1279
+ return 0;
1280
+ }
1281
+ const { values, positionals } = parseArgsStrict(argv, { port: { type: "string" } });
1282
+ const file = deckFile(positionals, USAGE5);
1283
+ const port = values.port === void 0 ? 4321 : Number(values.port);
1284
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new CliError(2, `invalid --port: ${values.port}`);
1285
+ const warning = runtimeVersionWarning(readInput(file), CORE_PACKAGE, coreVersion());
1286
+ if (warning) process.stderr.write(`warning: ${warning.message}
1287
+ `);
1288
+ const stopped = new Promise((resolveStop) => process.once("SIGINT", resolveStop));
1289
+ const server = await startServer({ file, watch: true, port, status: createStatusProvider({ file }) });
1290
+ process.stdout.write(`${server.url}
1291
+ `);
1292
+ await stopped;
1293
+ await server.close();
1294
+ return 0;
1295
+ }
1296
+
1173
1297
  // src/commands/skill.ts
1174
1298
  import { cpSync, existsSync as existsSync6, readFileSync as readFileSync7, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1175
1299
  import { homedir as homedir2 } from "node:os";
1176
- import { join as join8, resolve as resolve5 } from "node:path";
1300
+ import { join as join8, resolve as resolve6 } from "node:path";
1177
1301
  import { fileURLToPath as fileURLToPath3 } from "node:url";
1178
1302
 
1179
1303
  // src/zip.ts
@@ -1289,7 +1413,7 @@ function packSkill(source, out) {
1289
1413
  function runPack(rest) {
1290
1414
  const { values, positionals } = parseArgsStrict(rest, { out: { type: "string" } });
1291
1415
  if (positionals.length > 0) throw new CliError(2, USAGE6);
1292
- const out = resolve5(values.out ?? "banger-skill.zip");
1416
+ const out = resolve6(values.out ?? "banger-skill.zip");
1293
1417
  packSkill(bundledSkill(), out);
1294
1418
  process.stdout.write(`packed: ${out}
1295
1419
 
@@ -1307,7 +1431,7 @@ function runSkill(argv) {
1307
1431
  force: { type: "boolean" }
1308
1432
  });
1309
1433
  if (positionals.length > 0 || values.project && values.dir !== void 0) throw new CliError(2, USAGE6);
1310
- const dest = values.dir !== void 0 ? resolve5(values.dir) : values.project ? resolve5(".claude", "skills", "banger") : join8(homedir2(), ".claude", "skills", "banger");
1434
+ const dest = values.dir !== void 0 ? resolve6(values.dir) : values.project ? resolve6(".claude", "skills", "banger") : join8(homedir2(), ".claude", "skills", "banger");
1311
1435
  const outcome = installSkill({ source: bundledSkill(), dest, version: cliVersion(), force: values.force });
1312
1436
  process.stdout.write(`${outcome}: ${dest}
1313
1437
 
@@ -1331,7 +1455,7 @@ from the app's Skills settings. Code execution must be on.
1331
1455
 
1332
1456
  // src/commands/snap.ts
1333
1457
  import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
1334
- import { dirname as dirname5, join as join9 } from "node:path";
1458
+ import { dirname as dirname6, join as join9 } from "node:path";
1335
1459
  var USAGE7 = "usage: banger snap [file] [--stop N] [--step M|last] [--steps last|all] [--out path] [--out-dir dir] [--scale 1|2] [--lang <language>|all]";
1336
1460
  function parseCount(name, value) {
1337
1461
  if (!/^\d+$/.test(value)) throw new CliError(2, `invalid --${name}: ${value}`);
@@ -1387,7 +1511,7 @@ async function runSnap(argv) {
1387
1511
  for (const failure of report.failed) failures.add(`${run.tag}${formatReadyFailure(failure)}`);
1388
1512
  const png = await captureState(session, ref);
1389
1513
  const target = single && values.out || join9(dir, stopFileName(ref.stop, ref.step));
1390
- await mkdir2(dirname5(target), { recursive: true });
1514
+ await mkdir2(dirname6(target), { recursive: true });
1391
1515
  await writeFile2(target, png);
1392
1516
  }
1393
1517
  return void 0;
@@ -1472,7 +1596,7 @@ ${USAGE8}`);
1472
1596
  // src/update-check.ts
1473
1597
  import { mkdirSync as mkdirSync4, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "node:fs";
1474
1598
  import { homedir as homedir3 } from "node:os";
1475
- import { dirname as dirname6, join as join10 } from "node:path";
1599
+ import { dirname as dirname7, join as join10 } from "node:path";
1476
1600
  var PACKAGE = "@bangerpage/cli";
1477
1601
  var LATEST_URL = "https://registry.npmjs.org/@bangerpage%2fcli/latest";
1478
1602
  var INTERVAL_MS = 24 * 60 * 60 * 1e3;
@@ -1522,7 +1646,7 @@ function checkForUpdate(opts) {
1522
1646
  if (cache && now - cache.checkedAt < INTERVAL_MS) return Promise.resolve();
1523
1647
  return (opts.fetchLatest ?? fetchFromRegistry)().then((latest) => {
1524
1648
  if (!latest) return;
1525
- mkdirSync4(dirname6(file), { recursive: true });
1649
+ mkdirSync4(dirname7(file), { recursive: true });
1526
1650
  writeFileSync5(file, `${JSON.stringify({ checkedAt: now, latest })}
1527
1651
  `);
1528
1652
  }).catch(() => void 0);