@tobos/cli 0.4.28 → 0.4.30

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/cli.js CHANGED
@@ -2,24 +2,24 @@
2
2
  import { createRequire as __tobosRequire } from 'node:module';
3
3
  const require = __tobosRequire(import.meta.url);
4
4
  import {
5
- formatMediaJson,
6
5
  formatProblems,
7
- mediaTypeOf
8
- } from "./chunk-Q3YXIXJI.js";
6
+ mediaTypeOf,
7
+ mergeText,
8
+ parseMediaJson,
9
+ unpackTar
10
+ } from "./chunk-67QAOIEN.js";
9
11
  import {
10
12
  ASK_THE_PERSON,
11
13
  CliError,
12
14
  EXIT,
13
15
  createOutput,
14
- offerUpdate,
15
- update
16
- } from "./chunk-BEVE4YBG.js";
17
- import {
18
16
  define_TOBOS_SKILL_default,
19
17
  init_define_TOBOS_PRESENT_TYPES,
20
18
  init_define_TOBOS_SKILL,
21
- init_define_TOBOS_TOOLCHAIN
22
- } from "./chunk-3SEPIUUD.js";
19
+ init_define_TOBOS_TOOLCHAIN,
20
+ offerUpdate,
21
+ update
22
+ } from "./chunk-QZRWMMBR.js";
23
23
 
24
24
  // src/main.ts
25
25
  init_define_TOBOS_PRESENT_TYPES();
@@ -89,7 +89,7 @@ function settings() {
89
89
  }
90
90
 
91
91
  // src/api.ts
92
- var VERSION = true ? "0.4.28" : "dev";
92
+ var VERSION = true ? "0.4.30" : "dev";
93
93
  function newer(a, b) {
94
94
  const parse = (v) => /^\d+\.\d+\.\d+/.test(v) ? v.split(".").map((n) => parseInt(n)) : null;
95
95
  const x = parse(a);
@@ -112,7 +112,7 @@ async function api(path, options = {}) {
112
112
  }
113
113
  function failure(response, data, prefix = "") {
114
114
  const { error, message, ...extra } = data;
115
- const said = prefix + (error ?? message ?? `${response.status} ${response.statusText}`);
115
+ const said = prefix + (message ?? error ?? `${response.status} ${response.statusText}`);
116
116
  const limit = response.status === 402 || response.status === 423;
117
117
  return new CliError(
118
118
  limit ? `${said}
@@ -164,9 +164,9 @@ async function request(path, options = {}) {
164
164
  `Can't reach ${target}: ${error.cause ?? error.message}`
165
165
  );
166
166
  }
167
- const latest = response.headers.get("tobos-latest-cli");
168
- if (latest && newer(latest, VERSION))
169
- offerUpdate(`tobos ${latest} is out (you have ${VERSION}): npm i -g @tobos/cli`);
167
+ const latest2 = response.headers.get("tobos-latest-cli");
168
+ if (latest2 && newer(latest2, VERSION))
169
+ offerUpdate(`tobos ${latest2} is out (you have ${VERSION}): npm i -g @tobos/cli`);
170
170
  return response;
171
171
  }
172
172
 
@@ -174,176 +174,312 @@ async function request(path, options = {}) {
174
174
  init_define_TOBOS_PRESENT_TYPES();
175
175
  init_define_TOBOS_SKILL();
176
176
  init_define_TOBOS_TOOLCHAIN();
177
- import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync5 } from "node:fs";
177
+ import { existsSync as existsSync3, statSync as statSync2 } from "node:fs";
178
178
  import { hostname } from "node:os";
179
- import { dirname as dirname3, join as join7, relative as relative2, resolve as resolve2 } from "node:path";
179
+ import { join as join5, relative as relative2, resolve as resolve2 } from "node:path";
180
180
 
181
- // ../deck/src/node.ts
181
+ // src/copy.ts
182
182
  init_define_TOBOS_PRESENT_TYPES();
183
183
  init_define_TOBOS_SKILL();
184
184
  init_define_TOBOS_TOOLCHAIN();
185
- import { readdirSync, readFileSync as readFileSync2 } from "node:fs";
186
- import { join as join2 } from "node:path";
187
- var SKIP = /* @__PURE__ */ new Set([".git", "node_modules", "media", "sources", ".tobos"]);
188
- function directoryTree(root, only) {
189
- const allowed = only === void 0 ? void 0 : new Set(only);
190
- const files = [];
191
- const visit = (dir2, prefix) => {
192
- for (const entry of readdirSync(dir2, { withFileTypes: true })) {
193
- if (prefix === "" && SKIP.has(entry.name)) continue;
194
- if (entry.name === ".DS_Store" || entry.name === "node_modules") continue;
195
- const path = prefix + entry.name;
196
- if (entry.isDirectory()) visit(join2(dir2, entry.name), path + "/");
197
- else if (entry.isFile() && (allowed?.has(path) ?? true)) files.push(path);
198
- }
199
- };
200
- visit(root, "");
201
- files.sort();
202
- const listed = new Set(files);
203
- return {
204
- files: () => files,
205
- // Only what was listed: no path can reach outside the folder.
206
- read: (path) => {
207
- if (!listed.has(path)) return void 0;
208
- try {
209
- return new Uint8Array(readFileSync2(join2(root, path)));
210
- } catch (error) {
211
- throw new Error(`${path} can't be read: ${error.message}`);
212
- }
213
- }
214
- };
185
+ import { execFileSync } from "node:child_process";
186
+ import { createHash } from "node:crypto";
187
+ import {
188
+ existsSync,
189
+ lstatSync,
190
+ statSync,
191
+ mkdirSync as mkdirSync2,
192
+ readdirSync,
193
+ readFileSync as readFileSync2,
194
+ rmSync,
195
+ writeFileSync as writeFileSync2
196
+ } from "node:fs";
197
+ import { isUtf8 } from "node:buffer";
198
+ import { dirname, join as join2, relative, resolve, sep } from "node:path";
199
+ var BASE = join2(".tobos", "base.json");
200
+ var ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
201
+ var NOT_THE_DECK = /* @__PURE__ */ new Set([".tobos", ".git", "node_modules", "sources"]);
202
+ function parseId(id) {
203
+ if (!ID.test(id)) throw new CliError(`"${id}" is not a deck's id; \`tobos ls\` lists them.`);
204
+ return id;
215
205
  }
216
-
217
- // src/deck-dir.ts
218
- init_define_TOBOS_PRESENT_TYPES();
219
- init_define_TOBOS_SKILL();
220
- init_define_TOBOS_TOOLCHAIN();
221
- import { existsSync } from "node:fs";
222
- import { dirname, join as join3, resolve } from "node:path";
223
-
224
- // src/git.ts
225
- init_define_TOBOS_PRESENT_TYPES();
226
- init_define_TOBOS_SKILL();
227
- init_define_TOBOS_TOOLCHAIN();
228
- import { spawn } from "node:child_process";
229
- import { realpathSync } from "node:fs";
230
- function git(args, options = {}) {
231
- return new Promise((resolve3, reject) => {
232
- const child = spawn("git", args, {
233
- cwd: options.cwd,
234
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", ...options.env }
235
- });
236
- let stdout = "";
237
- let stderr = "";
238
- child.stdout.setEncoding("utf8");
239
- child.stderr.setEncoding("utf8");
240
- child.stdout.on("data", (d) => stdout += d);
241
- child.stderr.on("data", (d) => {
242
- stderr += d;
243
- if (options.echo) process.stderr.write(d);
244
- });
245
- child.on(
246
- "error",
247
- (error) => reject(
248
- error.code === "ENOENT" ? new CliError("git is not installed. Tobos keeps every deck in git; install it first.") : error
249
- )
206
+ function findCopy(start = process.cwd()) {
207
+ for (let dir2 = resolve(start); ; dir2 = dirname(dir2)) {
208
+ if (existsSync(join2(dir2, BASE)))
209
+ return { root: dir2, base: JSON.parse(readFileSync2(join2(dir2, BASE), "utf8")) };
210
+ if (existsSync(join2(dir2, ".git")) && existsSync(join2(dir2, "deck.json"))) return { root: dir2 };
211
+ if (dirname(dir2) === dir2) return void 0;
212
+ }
213
+ }
214
+ function requireCopy(start) {
215
+ const found = findCopy(start);
216
+ if (!found)
217
+ throw new CliError(
218
+ "Not in a deck: no .tobos/base.json here or above. `tobos pull <id>` makes one."
250
219
  );
251
- child.on("close", (code) => resolve3({ code: code ?? 1, stdout, stderr }));
252
- });
220
+ if (!found.base)
221
+ throw new CliError(
222
+ `${found.root} is a clone from before: run \`tobos pull\` there once, which makes it a working copy.`
223
+ );
224
+ return found;
253
225
  }
254
- async function gitOk(args, options = {}) {
255
- const result = await git(args, options);
256
- if (result.code !== 0) throw new CliError(`git ${args[0]} failed:
257
- ${result.stderr.trim()}`);
258
- return result.stdout;
226
+ function writeBase(root, base) {
227
+ mkdirSync2(join2(root, ".tobos"), { recursive: true });
228
+ writeFileSync2(join2(root, BASE), `${JSON.stringify(base, null, 2)}
229
+ `);
259
230
  }
260
- function credentialHelper() {
261
- const script = realpathSync(process.argv[1]);
262
- const quote = (s) => `'${s.replace(/'/g, "'\\''")}'`;
263
- return `!f() { [ "$1" = get ] || exit 0; exec ${quote(process.execPath)} ${quote(script)} credential get; }; f`;
231
+ var sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
232
+ function held(path) {
233
+ const parts = path.split("/");
234
+ return parts.every((part) => part !== "" && part !== "." && part !== ".." && !part.includes("\\")) && // Any case: a disk that ignores it would write `.TOBOS/` over the copy's own `.tobos/`.
235
+ !NOT_THE_DECK.has(parts[0].toLowerCase()) && !parts.includes(".DS_Store");
264
236
  }
265
- function credentialConfig(server) {
266
- return [
267
- "-c",
268
- `credential.${server}.helper=`,
269
- "-c",
270
- `credential.${server}.helper=${credentialHelper()}`
271
- ];
237
+ function throughLink(root, path) {
238
+ let at = root;
239
+ for (const part of path.split("/")) {
240
+ at = join2(at, part);
241
+ try {
242
+ if (lstatSync(at).isSymbolicLink()) return true;
243
+ } catch {
244
+ return false;
245
+ }
246
+ }
247
+ return false;
272
248
  }
273
- function authEnv(server) {
274
- const { server: ours, token } = settings();
275
- if (!token || new URL(ours).origin !== new URL(server).origin) return {};
276
- const n = Number(process.env.GIT_CONFIG_COUNT) || 0;
277
- return {
278
- GIT_CONFIG_COUNT: String(n + 1),
279
- [`GIT_CONFIG_KEY_${n}`]: `http.${server}.extraHeader`,
280
- [`GIT_CONFIG_VALUE_${n}`]: `Authorization: Basic ${Buffer.from(`tobos:${token}`).toString("base64")}`
249
+ function copyFiles(root) {
250
+ const files = /* @__PURE__ */ new Map();
251
+ const walk = (dir2) => {
252
+ for (const entry of readdirSync(dir2, { withFileTypes: true })) {
253
+ const path = join2(dir2, entry.name);
254
+ const name = relative(root, path).split(sep).join("/");
255
+ if (dir2 === root && NOT_THE_DECK.has(entry.name) || entry.name === ".DS_Store") continue;
256
+ if (entry.isDirectory()) walk(path);
257
+ else if (entry.isFile()) files.set(name, sha256(readFileSync2(path)));
258
+ }
281
259
  };
260
+ walk(root);
261
+ return files;
282
262
  }
283
- async function refreshCredentials(dir2, server) {
284
- const configured = await git(["config", "--local", "--get-all", `credential.${server}.helper`], {
285
- cwd: dir2
286
- });
287
- if (configured.code !== 0) return;
288
- if (configured.stdout === `
289
- ${credentialHelper()}
290
- `) return;
291
- await configureCredentials(dir2, server);
292
- }
293
- async function configureCredentials(dir2, server) {
294
- await gitOk(["config", "--replace-all", `credential.${server}.helper`, ""], { cwd: dir2 });
295
- await gitOk(["config", "--add", `credential.${server}.helper`, credentialHelper()], { cwd: dir2 });
296
- }
297
-
298
- // src/deck-dir.ts
299
- var ID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
300
- var REMOTE = new RegExp(`^(https?://[^/]+)/git/(${ID})\\.git$`);
301
- async function findDeck(start = process.cwd()) {
302
- let dir2 = resolve(start);
303
- while (!existsSync(join3(dir2, "deck.json"))) {
304
- const up = dirname(dir2);
305
- if (up === dir2)
306
- throw new CliError("Not in a deck: no deck.json here or above. `tobos clone` one first.");
307
- dir2 = up;
263
+ async function latest(deck, server) {
264
+ const response = await request(`/api/decks/${deck}/export`, { server });
265
+ if (!response.ok) throw failure(response, await response.json().catch(() => ({})));
266
+ const rev = response.headers.get("tobos-rev");
267
+ const files = unpackTar(new Uint8Array(await response.arrayBuffer()));
268
+ const media = parseMediaJson(textOf(files.get("media.json"))).media;
269
+ const hashes = new Map([...files].map(([path, bytes]) => [path, sha256(bytes)]));
270
+ for (const [name, entry] of Object.entries(media)) hashes.set(`media/${name}`, entry.hash);
271
+ return { rev, files, media, hashes };
272
+ }
273
+ var textOf = (bytes) => bytes ? Buffer.from(bytes).toString("utf8") : "{}";
274
+ async function mediaBytes(deck, server, hash) {
275
+ const response = await request(`/api/media/${hash}?deck=${deck}`, { server });
276
+ if (!response.ok) throw failure(response, await response.json().catch(() => ({})));
277
+ return new Uint8Array(await response.arrayBuffer());
278
+ }
279
+ async function pullInto(root, deck, server, base, { note, clone = false }) {
280
+ const now = await latest(deck, server);
281
+ const local = existsSync(root) ? copyFiles(root) : /* @__PURE__ */ new Map();
282
+ const was = new Map(Object.entries(base?.files ?? {}));
283
+ const next = new Map([...now.hashes].filter(([path]) => held(path)));
284
+ const changed = [];
285
+ const conflicts = [];
286
+ const fetched = /* @__PURE__ */ new Map();
287
+ const bytesOf = async (path, hash) => {
288
+ const file2 = now.files.get(path);
289
+ if (file2) return file2;
290
+ if (!fetched.has(hash))
291
+ fetched.set(hash, await mediaBytes(deck, server, hash).catch(() => null));
292
+ return fetched.get(hash);
293
+ };
294
+ const paths = /* @__PURE__ */ new Set([...was.keys(), ...next.keys(), ...local.keys()]);
295
+ for (const path of paths) {
296
+ if (!held(path)) continue;
297
+ const [b, s] = [was.get(path), next.get(path)];
298
+ const l = local.get(path);
299
+ if (s === l) continue;
300
+ const file2 = join2(root, ...path.split("/"));
301
+ if (throughLink(root, path)) {
302
+ note(`left ${path} as it is: a link in this copy leads to it`);
303
+ if (b === void 0) next.delete(path);
304
+ else next.set(path, b);
305
+ continue;
306
+ }
307
+ const fresh = !base || l === b || clone && path.startsWith("media/") && l === void 0;
308
+ if (!fresh && s === b) continue;
309
+ if (fresh) {
310
+ if (s === void 0) rmSync(file2, { force: true });
311
+ else {
312
+ const bytes = await bytesOf(path, s);
313
+ if (!bytes) {
314
+ note(`couldn't fetch ${path}: the server may have lost it; a later pull tries again`);
315
+ if (l === void 0 || b === void 0) next.delete(path);
316
+ else next.set(path, b);
317
+ continue;
318
+ }
319
+ write2(file2, bytes);
320
+ }
321
+ changed.push(path);
322
+ continue;
323
+ }
324
+ const ours = l === void 0 ? void 0 : readFileSync2(file2);
325
+ const theirs = s === void 0 ? void 0 : await bytesOf(path, s);
326
+ const older = b === void 0 ? new Uint8Array() : await fileAt(deck, server, base.rev, path);
327
+ const texts = [older, ours, theirs].every((bytes) => bytes && isUtf8(bytes));
328
+ const merged = texts ? mergeText(textOf(older), textOf(ours), textOf(theirs)) : void 0;
329
+ if (merged !== void 0) write2(file2, Buffer.from(merged));
330
+ else if (texts) {
331
+ write2(file2, Buffer.from(marked(textOf(ours), textOf(theirs))));
332
+ note(`conflict: ${path}, between <<<<<<< and >>>>>>>`);
333
+ conflicts.push(path);
334
+ } else {
335
+ if (ours) write2(join2(root, ".tobos", "conflicts", ...path.split("/")), ours);
336
+ if (theirs) write2(file2, theirs);
337
+ else if (s === void 0) rmSync(file2, { force: true });
338
+ else {
339
+ if (b === void 0) next.delete(path);
340
+ else next.set(path, b);
341
+ continue;
342
+ }
343
+ note(
344
+ `conflict: ${path} changed on both sides; the server's is here now${ours ? `, yours in .tobos/conflicts/${path}` : ""}`
345
+ );
346
+ conflicts.push(path);
347
+ }
348
+ changed.push(path);
308
349
  }
309
- const remote = await git(["remote", "get-url", "origin"], { cwd: dir2 }).catch(() => void 0);
310
- const match = remote && remote.code === 0 ? REMOTE.exec(remote.stdout.trim()) : null;
311
- if (!match) return { root: dir2 };
312
- await refreshCredentials(dir2, match[1]).catch(() => void 0);
313
- return { root: dir2, server: match[1], id: match[2] };
350
+ writeBase(root, { deck, server, rev: now.rev, files: Object.fromEntries(next) });
351
+ return { rev: now.rev, changed, conflicts };
352
+ }
353
+ function marked(ours, theirs) {
354
+ const end = (text) => text.endsWith("\n") || text === "" ? text : `${text}
355
+ `;
356
+ return `<<<<<<< yours
357
+ ${end(ours)}=======
358
+ ${end(theirs)}>>>>>>> tobos
359
+ `;
314
360
  }
315
- async function requireRemote(start) {
316
- const deck = await findDeck(start);
317
- if (!deck.id || !deck.server)
361
+ async function fileAt(deck, server, rev, path) {
362
+ const response = await request(
363
+ `/api/decks/${deck}/files/${path.split("/").map(encodeURIComponent).join("/")}${rev ? `?rev=${rev}` : ""}`,
364
+ { server }
365
+ );
366
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : new Uint8Array();
367
+ }
368
+ function write2(file2, bytes) {
369
+ mkdirSync2(dirname(file2), { recursive: true });
370
+ writeFileSync2(file2, bytes);
371
+ }
372
+ async function baseOfClone(root) {
373
+ const run = (args) => execFileSync("git", args, {
374
+ cwd: root,
375
+ encoding: "utf8",
376
+ stdio: ["ignore", "pipe", "ignore"]
377
+ }).trim();
378
+ let remote;
379
+ let rev;
380
+ try {
381
+ remote = run(["remote", "get-url", "origin"]);
382
+ rev = run(["merge-base", "HEAD", "origin/main"]);
383
+ } catch {
318
384
  throw new CliError(
319
- `${deck.root} isn't linked to a deck on a Tobos server (no matching git remote "origin").`
385
+ `${root} is a clone from before, and git can't say what it was cloned from. Pull the deck afresh: \`tobos pull <id> <folder>\`.`
320
386
  );
321
- return deck;
322
- }
323
- function parseId(id) {
324
- if (!new RegExp(`^${ID}$`).test(id))
325
- throw new CliError(`"${id}" is not a deck's id; \`tobos decks\` lists them.`);
326
- return id;
387
+ }
388
+ const match = /^(https?:\/\/[^/]+)\/git\/([0-9a-f-]{36})\.git$/.exec(remote);
389
+ if (!match) throw new CliError(`${root} is a clone of no Tobos deck (its remote is ${remote}).`);
390
+ const [, server, deck] = match;
391
+ const { files } = await api(
392
+ `/api/decks/${deck}/files?rev=${rev}`,
393
+ { server }
394
+ );
395
+ const hashes = Object.fromEntries(files.map((f) => [f.path, f.hash]));
396
+ const json = files.some((f) => f.path === "media.json") ? await fileAt(deck, server, rev, "media.json") : void 0;
397
+ const media = parseMediaJson(textOf(json)).media;
398
+ for (const [name, entry] of Object.entries(media)) hashes[`media/${name}`] = entry.hash;
399
+ return { deck, server, rev, files: hashes };
400
+ }
401
+ function changesOf(copy) {
402
+ const local = copyFiles(copy.root);
403
+ const changes = [];
404
+ for (const [path, hash] of local)
405
+ if (path !== "media.json" && copy.base.files[path] !== hash) changes.push({ path, hash });
406
+ for (const path of Object.keys(copy.base.files))
407
+ if (path !== "media.json" && !local.has(path)) changes.push({ path, hash: null });
408
+ return changes;
409
+ }
410
+ async function writeCopy(copy, message, { dry = false, note }) {
411
+ const { root, base } = copy;
412
+ const changes = changesOf(copy);
413
+ const files = /* @__PURE__ */ Object.create(null);
414
+ for (const { path, hash } of changes) {
415
+ if (hash === null) files[path] = null;
416
+ else if (path.startsWith("media/")) files[path] = { hash };
417
+ else {
418
+ const bytes = readFileSync2(join2(root, ...path.split("/")));
419
+ files[path] = isUtf8(bytes) ? Buffer.from(bytes).toString("utf8") : { base64: Buffer.from(bytes).toString("base64") };
420
+ }
421
+ }
422
+ const body = { base: base.rev, message, dry, files };
423
+ const uploaded = [];
424
+ for (let tries = 1; ; tries++) {
425
+ const response = await request(`/api/decks/${base.deck}/files`, {
426
+ method: "POST",
427
+ body,
428
+ server: base.server
429
+ });
430
+ const data = await response.json().catch(() => ({}));
431
+ if (response.ok) return { ...data, sent: changes.map((c) => c.path), uploaded };
432
+ if (data.error === "media" && tries <= 3) {
433
+ const media = [...copyFiles(root)].filter(([path]) => path.startsWith("media/"));
434
+ const sizes = new Map(
435
+ media.map(([path, hash]) => [hash, statSync(join2(root, ...path.split("/"))).size])
436
+ );
437
+ const total = [...sizes.values()].reduce((sum, size) => sum + size, 0);
438
+ const shows = Math.max(0, total - (data.elsewhere ?? 0));
439
+ for (const hash of data.hashes ?? []) {
440
+ const path = media.find(([, h]) => h === hash)?.[0];
441
+ if (!path)
442
+ throw new CliError(
443
+ `The server lacks a file of media/ (${hash}) that this copy doesn't have either: drop it on the deck's page again, or put it in media/ and push.`
444
+ );
445
+ note(`uploading ${path}`);
446
+ const put = await request(`/api/media/${hash}?deck=${base.deck}&shows=${shows}`, {
447
+ method: "PUT",
448
+ body: readFileSync2(join2(root, ...path.split("/"))),
449
+ // The type its name gives it, which the server keeps and serves it as.
450
+ contentType: mediaTypeOf(path.slice("media/".length)),
451
+ server: base.server
452
+ });
453
+ if (!put.ok)
454
+ throw failure(put, await put.json().catch(() => ({})), `Uploading ${path} failed: `);
455
+ uploaded.push(path);
456
+ }
457
+ continue;
458
+ }
459
+ if (data.error === "conflict")
460
+ throw new CliError(
461
+ `${data.message ?? "The deck changed meanwhile."}
462
+ Run \`tobos pull\`, which merges what changed, then push again.`,
463
+ EXIT.conflict,
464
+ { ...data, status: response.status }
465
+ );
466
+ if (data.error === "problems")
467
+ throw new CliError(
468
+ data.message ?? "The check refused it.",
469
+ EXIT.problems,
470
+ {
471
+ problems: data.problems,
472
+ status: response.status
473
+ }
474
+ );
475
+ throw failure(response, data);
476
+ }
327
477
  }
328
478
 
329
479
  // src/media.ts
330
480
  init_define_TOBOS_PRESENT_TYPES();
331
481
  init_define_TOBOS_SKILL();
332
482
  init_define_TOBOS_TOOLCHAIN();
333
- import { createHash } from "node:crypto";
334
- import {
335
- createReadStream,
336
- existsSync as existsSync2,
337
- lstatSync,
338
- mkdirSync as mkdirSync2,
339
- readdirSync as readdirSync2,
340
- readFileSync as readFileSync3,
341
- realpathSync as realpathSync2,
342
- statSync,
343
- writeFileSync as writeFileSync2
344
- } from "node:fs";
345
- import { join as join4, relative, sep } from "node:path";
346
- import { Readable } from "node:stream";
347
483
  var LOSSLESS = /\.(wav|aiff?|flac)$/i;
348
484
  var shellWord = (path) => /^[\w./-]+$/.test(path) ? path : `'${path.replaceAll("'", "'\\''")}'`;
349
485
  function sizeNote(name, size) {
@@ -357,110 +493,12 @@ function sizeNote(name, size) {
357
493
  return `note: media/${name} is ${mb} MB. Every viewer downloads it; size it for the stage.`;
358
494
  return void 0;
359
495
  }
360
- function hashFile(path) {
361
- return new Promise((resolve3, reject) => {
362
- const hash = createHash("sha256");
363
- createReadStream(path).on("data", (d) => hash.update(d)).on("end", () => resolve3(hash.digest("hex"))).on("error", reject);
364
- });
365
- }
366
- function walk(dir2) {
367
- if (!existsSync2(dir2) || !lstatSync(dir2).isDirectory()) return [];
368
- return readdirSync2(dir2, { withFileTypes: true }).flatMap(
369
- (d) => d.name.startsWith(".") ? [] : d.isDirectory() ? walk(join4(dir2, d.name)) : d.isFile() ? [join4(dir2, d.name)] : []
370
- );
371
- }
372
- function mediaFile(root, name) {
373
- const parts = name.split(process.platform === "win32" ? /[\\/]/ : "/");
374
- if (name.startsWith("/") || name.includes("\0") || parts.some((p) => p === "" || p === ".."))
375
- throw new CliError(`media.json names "${name}", which isn't a file in media/.`);
376
- const path = join4(root, "media", name);
377
- const refused = new CliError(
378
- `media/${name} is a link or a folder, not a file: media/ holds files only.`
379
- );
380
- let entry;
381
- try {
382
- entry = lstatSync(path, { throwIfNoEntry: false });
383
- } catch (error) {
384
- const code = error.code;
385
- if (code === "ENOTDIR" || code === "ENAMETOOLONG") return path;
386
- throw refused;
387
- }
388
- if (entry && (!entry.isFile() || realpathSync2(path) !== join4(realpathSync2(root), "media", name)))
389
- throw refused;
390
- return path;
391
- }
392
- async function syncMediaJson(root) {
393
- const file2 = join4(root, "media.json");
394
- const before = existsSync2(file2) ? readFileSync3(file2, "utf8") : "{}\n";
395
- const media = JSON.parse(before);
396
- const cacheFile = join4(root, ".tobos", "media-cache.json");
397
- let cache = {};
398
- try {
399
- cache = JSON.parse(readFileSync3(cacheFile, "utf8"));
400
- } catch {
401
- }
402
- for (const name of Object.keys(media))
403
- if (!(process.platform === "win32" && name.includes("\\"))) mediaFile(root, name);
404
- const dir2 = join4(root, "media");
405
- for (const path of walk(dir2)) {
406
- const name = relative(dir2, path).split(sep).join("/");
407
- const { size, mtimeMs } = statSync(path);
408
- const cached = cache[name];
409
- const hash = cached && cached.size === size && cached.mtime === mtimeMs ? cached.hash : await hashFile(path);
410
- cache[name] = { size, mtime: mtimeMs, hash };
411
- media[name] = {
412
- hash,
413
- size,
414
- type: mediaTypeOf(name)
415
- };
416
- }
417
- mkdirSync2(join4(root, ".tobos"), { recursive: true });
418
- writeFileSync2(cacheFile, JSON.stringify(cache));
419
- const sorted = Object.fromEntries(Object.entries(media).sort(([a], [b]) => a.localeCompare(b)));
420
- const after = formatMediaJson(sorted);
421
- if (after !== before) writeFileSync2(file2, after);
422
- return { media: sorted, changed: after !== before };
423
- }
424
- async function uploadMedia(root, media, server, deck, note) {
425
- const hashes = [...new Set(Object.values(media).map((m) => m.hash))];
426
- if (hashes.length === 0) return [];
427
- const { missing, elsewhere = 0 } = await api(
428
- "/api/media/missing",
429
- { body: { hashes, deck }, server }
430
- );
431
- const sizes = Object.fromEntries(Object.values(media).map((m) => [m.hash, m.size]));
432
- const shows = Object.values(sizes).reduce((sum, size) => sum + size, 0) - elsewhere;
433
- const uploaded = [];
434
- for (const hash of missing) {
435
- const [name, entry] = Object.entries(media).find(([, m]) => m.hash === hash);
436
- const path = mediaFile(root, name);
437
- if (!existsSync2(path))
438
- throw new CliError(
439
- `media/${name} is on a slide but not on this machine, and the server doesn't have it: put it in media/, then push again.`
440
- );
441
- note(`uploading media/${name} (${Math.round(entry.size / 1e3)} kB)`);
442
- const response = await request(`/api/media/${hash}?deck=${deck}&shows=${shows}`, {
443
- method: "PUT",
444
- body: Readable.toWeb(createReadStream(path)),
445
- contentType: entry.type,
446
- server
447
- });
448
- if (!response.ok)
449
- throw failure(
450
- response,
451
- await response.json().catch(() => ({})),
452
- `Uploading media/${name} failed: `
453
- );
454
- uploaded.push(name);
455
- }
456
- return uploaded;
457
- }
458
496
 
459
497
  // src/open-url.ts
460
498
  init_define_TOBOS_PRESENT_TYPES();
461
499
  init_define_TOBOS_SKILL();
462
500
  init_define_TOBOS_TOOLCHAIN();
463
- import { spawn as spawn2 } from "node:child_process";
501
+ import { spawn } from "node:child_process";
464
502
  async function openUrl(url) {
465
503
  if (!/^https?:$/.test(URL.parse(url)?.protocol ?? "")) return false;
466
504
  const env = process.env;
@@ -469,7 +507,7 @@ async function openUrl(url) {
469
507
  const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "rundll32" : "xdg-open";
470
508
  const args = process.platform === "win32" ? ["url.dll,FileProtocolHandler", url] : [url];
471
509
  try {
472
- const child = spawn2(command, args, { stdio: "ignore", detached: true });
510
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
473
511
  child.unref();
474
512
  return await new Promise((resolve3) => {
475
513
  let timer;
@@ -491,14 +529,14 @@ init_define_TOBOS_PRESENT_TYPES();
491
529
  init_define_TOBOS_SKILL();
492
530
  init_define_TOBOS_TOOLCHAIN();
493
531
  import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
494
- import { join as join5 } from "node:path";
532
+ import { join as join3 } from "node:path";
495
533
  async function writeFormatGuide(root, server) {
496
- const dir2 = join5(root, ".tobos");
534
+ const dir2 = join3(root, ".tobos");
497
535
  mkdirSync3(dir2, { recursive: true });
498
536
  const format = await request("/api/format", { anonymous: true, server });
499
537
  if (!format.ok)
500
538
  throw new CliError(`Couldn't fetch the format guide from ${server} (${format.status}).`);
501
- writeFileSync3(join5(dir2, "FORMAT.md"), await format.text());
539
+ writeFileSync3(join3(dir2, "FORMAT.md"), await format.text());
502
540
  }
503
541
 
504
542
  // src/skill.ts
@@ -506,23 +544,23 @@ init_define_TOBOS_PRESENT_TYPES();
506
544
  init_define_TOBOS_SKILL();
507
545
  init_define_TOBOS_TOOLCHAIN();
508
546
  import {
509
- existsSync as existsSync3,
547
+ existsSync as existsSync2,
510
548
  mkdirSync as mkdirSync4,
511
- readdirSync as readdirSync3,
512
- readFileSync as readFileSync4,
549
+ readdirSync as readdirSync2,
550
+ readFileSync as readFileSync3,
513
551
  renameSync as renameSync2,
514
- rmSync,
552
+ rmSync as rmSync2,
515
553
  writeFileSync as writeFileSync4
516
554
  } from "node:fs";
517
555
  import { homedir as homedir2 } from "node:os";
518
- import { dirname as dirname2, join as join6 } from "node:path";
556
+ import { dirname as dirname2, join as join4 } from "node:path";
519
557
  var SKILL_NAME = "tobos-present";
520
558
  function readTree(root) {
521
559
  const files = {};
522
- for (const entry of readdirSync3(root, { recursive: true, withFileTypes: true }))
560
+ for (const entry of readdirSync2(root, { recursive: true, withFileTypes: true }))
523
561
  if (entry.isFile()) {
524
- const path = join6(entry.parentPath, entry.name);
525
- files[path.slice(root.length).replace(/^[\\/]/, "").split("\\").join("/")] = readFileSync4(path, "utf8");
562
+ const path = join4(entry.parentPath, entry.name);
563
+ files[path.slice(root.length).replace(/^[\\/]/, "").split("\\").join("/")] = readFileSync3(path, "utf8");
526
564
  }
527
565
  return files;
528
566
  }
@@ -534,35 +572,35 @@ function targets() {
534
572
  const home = homedir2();
535
573
  return [
536
574
  {
537
- dir: join6(process.env.CLAUDE_CONFIG_DIR || join6(home, ".claude"), "skills", SKILL_NAME),
575
+ dir: join4(process.env.CLAUDE_CONFIG_DIR || join4(home, ".claude"), "skills", SKILL_NAME),
538
576
  harnesses: ["Claude Code", "OpenCode", "Cursor", "GitHub Copilot", "Goose"]
539
577
  },
540
578
  {
541
- dir: join6(home, ".agents", "skills", SKILL_NAME),
579
+ dir: join4(home, ".agents", "skills", SKILL_NAME),
542
580
  harnesses: ["Codex", "OpenCode", "Cursor", "Gemini CLI", "GitHub Copilot", "Amp"]
543
581
  }
544
582
  ];
545
583
  }
546
- function write2(dir2, files, version) {
584
+ function write3(dir2, files, version) {
547
585
  const next = `${dir2}.next-${process.pid}`;
548
586
  for (const [path, text] of Object.entries(files)) {
549
- mkdirSync4(dirname2(join6(next, path)), { recursive: true });
550
- writeFileSync4(join6(next, path), text);
587
+ mkdirSync4(dirname2(join4(next, path)), { recursive: true });
588
+ writeFileSync4(join4(next, path), text);
551
589
  }
552
- writeFileSync4(join6(next, "VERSION"), `${version}
590
+ writeFileSync4(join4(next, "VERSION"), `${version}
553
591
  `);
554
- rmSync(dir2, { recursive: true, force: true });
592
+ rmSync2(dir2, { recursive: true, force: true });
555
593
  try {
556
594
  renameSync2(next, dir2);
557
595
  } catch (error) {
558
- rmSync(next, { recursive: true, force: true });
559
- if (!existsSync3(join6(dir2, "VERSION"))) throw error;
596
+ rmSync2(next, { recursive: true, force: true });
597
+ if (!existsSync2(join4(dir2, "VERSION"))) throw error;
560
598
  }
561
599
  }
562
600
  var refusedCodes = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EROFS"]);
563
601
  function place(target, files, version) {
564
602
  try {
565
- write2(target.dir, files, version);
603
+ write3(target.dir, files, version);
566
604
  return { ...target, action: "installed" };
567
605
  } catch (error) {
568
606
  const code = error.code;
@@ -577,11 +615,11 @@ function install(options = {}) {
577
615
  }
578
616
  function refresh(options = {}) {
579
617
  const version = options.version ?? VERSION;
580
- return targets().filter((t) => existsSync3(join6(t.dir, "SKILL.md")) && newer(version, installed(t.dir))).map((t) => place(t, options.files ?? bundled(), version)).filter((r) => r.action === "refused");
618
+ return targets().filter((t) => existsSync2(join4(t.dir, "SKILL.md")) && newer(version, installed(t.dir))).map((t) => place(t, options.files ?? bundled(), version)).filter((r) => r.action === "refused");
581
619
  }
582
620
  function installed(dir2) {
583
621
  try {
584
- return readFileSync4(join6(dir2, "VERSION"), "utf8").trim();
622
+ return readFileSync3(join4(dir2, "VERSION"), "utf8").trim();
585
623
  } catch {
586
624
  return "0.0.0";
587
625
  }
@@ -651,11 +689,11 @@ function aboutDeck(d) {
651
689
  return notes.length ? ` (${notes.join("; ")})` : "";
652
690
  }
653
691
  var inFolder = (path) => path === "/" ? "" : `${path}/`;
654
- async function decks(out, args) {
692
+ async function ls(out, args) {
655
693
  const path = args.positionals[0];
656
694
  if (path !== void 0) {
657
695
  const listed = await api(
658
- `/api/drive?${new URLSearchParams({ path })}`
696
+ `/api/decks?${new URLSearchParams({ path })}`
659
697
  );
660
698
  out.result(
661
699
  listed,
@@ -663,10 +701,10 @@ async function decks(out, args) {
663
701
  );
664
702
  return;
665
703
  }
666
- const { decks: decks2 } = await api("/api/decks");
704
+ const { decks } = await api("/api/decks");
667
705
  out.result(
668
- { decks: decks2 },
669
- () => decks2.length === 0 ? 'No decks yet. `tobos new "Title"` starts one.' : decks2.map((d) => `${d.id} ${inFolder(d.folder ?? "/")}${d.title}${aboutDeck(d)}`).join("\n")
706
+ { decks },
707
+ () => decks.length === 0 ? 'No decks yet. `tobos new "Title"` starts one.' : decks.map((d) => `${d.id} ${inFolder(d.folder ?? "/")}${d.title}${aboutDeck(d)}`).join("\n")
670
708
  );
671
709
  }
672
710
  async function mv(out, args) {
@@ -685,32 +723,52 @@ async function mv(out, args) {
685
723
  });
686
724
  out.result(moved, () => `Moved ${plural(named.length, "item")} into ${moved.to}.`);
687
725
  }
688
- async function cloneInto(out, info, dir2) {
689
- const { server } = settings();
690
- if (existsSync4(dir2)) throw new CliError(`${dir2} already exists.`);
691
- out.note(`cloning ${info.title} into ${dir2}`);
692
- await gitOk([...credentialConfig(server), "clone", "--quiet", info.git, dir2], {
693
- env: authEnv(server)
694
- });
695
- await configureCredentials(dir2, server);
696
- return writeFormatGuide(dir2, server);
697
- }
698
- async function clone(out, args) {
726
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
727
+ async function pull(out, args) {
699
728
  const given = args.positionals[0];
700
- if (!given) throw new CliError("Which deck? `tobos clone <id>` (`tobos decks` lists them).");
701
- const id = parseId(given);
702
- const info = await api(`/api/decks/${id}`);
703
- const dir2 = resolve2(args.positionals[1] ?? id);
704
- await cloneInto(out, info, dir2);
705
- out.result(
706
- { ...info, dir: dir2 },
707
- () => `Cloned ${info.title} into ${relative2(process.cwd(), dir2) || "."}.
729
+ const note = (m) => out.note(m);
730
+ if (given) {
731
+ const id = parseId(given);
732
+ const info = await api(`/api/decks/${id}`);
733
+ const dir2 = resolve2(args.positionals[1] ?? id);
734
+ if (existsSync3(dir2)) throw new CliError(`${dir2} already exists.`);
735
+ await pullCopy(out, info, dir2);
736
+ out.result(
737
+ { ...info, dir: dir2 },
738
+ () => `Pulled ${info.title} into ${relative2(process.cwd(), dir2) || "."}.
708
739
  Read AGENTS.md there first. Preview: ${info.url}`
740
+ );
741
+ return;
742
+ }
743
+ const found = findCopy();
744
+ if (!found) throw new CliError("Not in a deck. `tobos pull <id>` makes a copy of one.");
745
+ const base = found.base ?? await baseOfClone(found.root);
746
+ const pulled = await pullInto(found.root, base.deck, base.server, base, {
747
+ note,
748
+ clone: !found.base
749
+ });
750
+ await writeFormatGuide(found.root, base.server);
751
+ out.result(
752
+ { id: base.deck, ...pulled },
753
+ () => [
754
+ `In step with the server (${pulled.rev?.slice(0, 7) ?? "no version yet"}): ${plural(pulled.changed.length, "file")} changed.`,
755
+ pulled.conflicts.length ? `${plural(pulled.conflicts.length, "conflict")}, between <<<<<<< and >>>>>>> in each: resolve them, then push.
756
+ ${pulled.conflicts.join("\n")}` : ""
757
+ ].filter(Boolean).join("\n")
709
758
  );
759
+ if (pulled.conflicts.length) process.exitCode = EXIT.conflict;
760
+ }
761
+ async function pullCopy(out, info, dir2) {
762
+ const { server } = settings();
763
+ out.note(`pulling ${info.title} into ${dir2}`);
764
+ await pullInto(dir2, info.id, server, void 0, { note: (m) => out.note(m) });
765
+ await writeFormatGuide(dir2, server);
710
766
  }
711
767
  async function create(out, args) {
712
768
  const title = args.positionals.join(" ").trim();
713
769
  if (!title) throw new CliError('What is it called? `tobos new "My talk"`.');
770
+ if (!args.values["no-pull"] && typeof args.values.dir === "string" && existsSync3(resolve2(args.values.dir)))
771
+ throw new CliError(`${resolve2(args.values.dir)} already exists.`);
714
772
  const info = await api("/api/decks", {
715
773
  body: {
716
774
  title,
@@ -719,225 +777,119 @@ async function create(out, args) {
719
777
  }
720
778
  });
721
779
  let dir2;
722
- if (!args.values["no-clone"]) {
780
+ if (!args.values["no-pull"]) {
723
781
  dir2 = resolve2(args.values.dir ?? info.id);
724
- await cloneInto(out, info, dir2);
782
+ if (existsSync3(dir2)) throw new CliError(`${dir2} already exists.`);
783
+ await pullCopy(out, info, dir2);
725
784
  }
726
785
  out.result(
727
786
  { ...info, dir: dir2 ?? null },
728
787
  () => [
729
788
  `Created ${info.title}: ${info.url}`,
730
- dir2 ? `Cloned into ${relative2(process.cwd(), dir2) || "."}. Read AGENTS.md there first.` : ""
789
+ dir2 ? `Pulled into ${relative2(process.cwd(), dir2) || "."}. Read AGENTS.md there first.` : ""
731
790
  ].filter(Boolean).join("\n")
732
791
  );
733
792
  }
734
- async function pull(out) {
735
- const deck = await requireRemote();
736
- const result = await git(
737
- [...credentialConfig(deck.server), "pull", "--ff-only", "--quiet", "origin", "main"],
738
- { cwd: deck.root, env: authEnv(deck.server) }
739
- );
740
- if (result.code !== 0)
741
- throw new CliError(
742
- `Couldn't fast-forward to the server's main:
743
- ${result.stderr.trim()}
744
- Commit or stash your changes, then merge with \`git pull\`.`
745
- );
746
- await writeFormatGuide(deck.root, deck.server);
747
- const rev = (await gitOk(["rev-parse", "HEAD"], { cwd: deck.root })).trim();
748
- out.result({ id: deck.id, rev }, () => `Up to date with the server (${rev.slice(0, 7)}).`);
749
- }
750
- async function pushedFiles(root) {
751
- try {
752
- const prefix = await git(["rev-parse", "--show-prefix"], { cwd: root });
753
- if (prefix.code !== 0 || prefix.stdout.trim() !== "") return void 0;
754
- const listed = await git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
755
- cwd: root
756
- });
757
- return listed.code === 0 ? listed.stdout.split("\0").filter(Boolean) : void 0;
758
- } catch {
759
- return void 0;
760
- }
761
- }
762
- async function runCheck(dir2) {
763
- const { buildDeck } = await import("./src-MEXQ6W3D.js");
764
- const started = performance.now();
765
- const files = await pushedFiles(dir2.root);
766
- const result = await buildDeck(directoryTree(dir2.root, files));
767
- return { ...result, files, ms: Math.round(performance.now() - started) };
768
- }
769
- var remoteLines = (stderr) => stderr.split("\n").filter((l) => l.startsWith("remote: ")).map((l) => l.slice(8));
770
- var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
771
- var MEDIA_LIMIT = /^tobos: (This deck belongs to .+, whose )?Tobos \w+ keeps .+ of media/;
772
- function pushFailure(output, remote) {
773
- const forThePerson = `${remote.map((line) => line.replace(/^tobos: /, "")).join("\n")}
774
- ${ASK_THE_PERSON}`;
775
- if (remote.some((line) => /^tobos: This (deck|template) is archived/.test(line)))
776
- return { message: forThePerson, exit: EXIT.limit, archived: true };
777
- if (remote.some((line) => MEDIA_LIMIT.test(line)))
778
- return { message: forThePerson, exit: EXIT.limit, limit: "media" };
779
- if (/non-fast-forward|fetch first/.test(output))
780
- return {
781
- message: "The server has changes you don't have. Run `tobos pull` (or `git pull`), then push again.",
782
- exit: EXIT.error
783
- };
784
- if (remote.some((line) => line.startsWith("tobos: rejected:")))
785
- return { message: `The server rejected the deck.
786
- ${remote.join("\n")}`, exit: EXIT.problems };
787
- if (/Authentication failed|returned error: 401|could not read Username/i.test(output))
788
- return {
789
- message: "The server didn't take your login. Run `tobos login` again, then push.",
790
- exit: EXIT.auth
791
- };
792
- if (/returned error: 403/.test(output))
793
- return {
794
- message: "You may not push to this deck: ask its owner to make you an editor.",
795
- exit: EXIT.error
796
- };
797
- if (remote.length > 0)
798
- return { message: `The server refused the push.
799
- ${remote.join("\n")}`, exit: EXIT.error };
800
- if (/Could not resolve host|Failed to connect|Connection refused|SSL|certificate/i.test(output))
801
- return {
802
- message: `Couldn't reach the server: nothing was pushed. Try again.
803
- ${output.trim()}`,
804
- exit: EXIT.error
805
- };
806
- if (/timed out|Connection reset|unexpected disconnect|RPC failed/i.test(output))
807
- return {
808
- message: `The connection broke off, and the push may have gone through. Run \`tobos pull\` to see where the server is, then push again if it still lacks your change.
809
- ${output.trim()}`,
810
- exit: EXIT.error
811
- };
812
- return { message: `The push failed.
813
- ${output.trim()}`, exit: EXIT.error };
814
- }
815
793
  function problemSummary(problems) {
816
794
  const errors = problems.filter((p) => p.severity === "error").length;
817
795
  return { errors, warnings: problems.length - errors };
818
796
  }
797
+ function noteSizes(out, root, paths) {
798
+ for (const path of paths.filter((p) => p.startsWith("media/"))) {
799
+ const file2 = join5(root, ...path.split("/"));
800
+ if (!existsSync3(file2)) continue;
801
+ const note = sizeNote(path.slice("media/".length), statSync2(file2).size);
802
+ if (note) out.note(note, true);
803
+ }
804
+ }
819
805
  async function check(out, args) {
820
- const deck = await findDeck(args.positionals[0]);
821
- await syncMediaJson(deck.root);
822
- const result = await runCheck(deck);
806
+ const copy = requireCopy(args.positionals[0]);
807
+ const started = performance.now();
808
+ const unchanged = changesOf(copy).length === 0;
809
+ const written = unchanged ? { problems: [] } : await writeCopy(copy, "Checked", { dry: true, note: (m) => out.note(m) }).catch(
810
+ (error) => {
811
+ if (error instanceof CliError && error.exit === EXIT.problems)
812
+ return { problems: error.extra.problems ?? [], refused: true };
813
+ throw error;
814
+ }
815
+ );
816
+ const problems = [...written.problems];
823
817
  if (args.values.types) {
824
- const { checkTypes } = await import("./types-3525WKH2.js");
825
- const sent = result.files && new Set(result.files);
826
- result.problems.push(
827
- ...(await checkTypes(deck.root, (m) => out.note(m))).filter((p) => sent?.has(p.file) ?? true)
828
- );
818
+ const { checkTypes } = await import("./types-YY3IZCJO.js");
819
+ problems.push(...await checkTypes(copy.root, (m) => out.note(m)));
829
820
  }
830
- const { errors, warnings } = problemSummary(result.problems);
831
- const scenes = result.manifest?.chapters.reduce((n, c) => n + c.scenes.length, 0) ?? 0;
832
- const beats = result.manifest?.chapters.reduce(
833
- (n, c) => n + c.scenes.reduce((m, s) => m + s.beats.length, 0),
834
- 0
835
- ) ?? 0;
821
+ const { errors, warnings } = problemSummary(problems);
822
+ const ms = Math.round(performance.now() - started);
836
823
  out.result(
837
- { ok: errors === 0, errors, warnings, problems: result.problems, scenes, beats, ms: result.ms },
824
+ { ok: errors === 0, changed: !unchanged, errors, warnings, problems, ms },
838
825
  () => [
839
- formatProblems(result.problems),
840
- errors === 0 ? `\u2713 ${plural(scenes, "scene")}, ${plural(beats, "beat")}${warnings ? `, ${plural(warnings, "warning")}` : ""} (${result.ms} ms)` : `\u2717 ${plural(errors, "error")}${warnings ? `, ${plural(warnings, "warning")}` : ""}`
826
+ unchanged ? "Nothing changed in the copy: the version it is of passed the check when it landed." : "",
827
+ formatProblems(problems),
828
+ errors === 0 ? unchanged ? "" : `\u2713 The check takes it${warnings ? `, with ${plural(warnings, "warning")}` : ""} (${ms} ms)` : `\u2717 ${plural(errors, "error")}${warnings ? `, ${plural(warnings, "warning")}` : ""}`
841
829
  ].filter(Boolean).join("\n")
842
830
  );
843
831
  if (errors > 0) process.exitCode = EXIT.problems;
844
832
  }
845
- async function pushWorkingCopy(out, deck, message) {
846
- const { root, server } = deck;
847
- const { media } = await syncMediaJson(root);
848
- const result = await runCheck(deck);
849
- const { errors, warnings } = problemSummary(result.problems);
850
- if (errors > 0) return { ok: false, errors, warnings, problems: result.problems };
851
- const { mediaInUse } = await import("./src-MEXQ6W3D.js");
852
- const shown = result.manifest ? mediaInUse(result.manifest) : media;
853
- for (const [name, entry] of Object.entries(shown)) {
854
- const note = sizeNote(name, entry.size);
855
- if (note) out.note(note, true);
856
- }
857
- const uploaded = await uploadMedia(root, shown, server, deck.id, (m) => out.note(m));
858
- await gitOk(["add", "-A"], { cwd: root });
859
- const committed = (await gitOk(["diff", "--cached", "--name-only"], { cwd: root })).split("\n").filter(Boolean);
860
- for (const file2 of committed) out.note(` ${file2}`);
861
- if (committed.length > 0)
862
- await gitOk(["commit", "--quiet", "-m", message || "Update the deck"], {
863
- cwd: root,
864
- env: await identity(root)
865
- });
866
- out.note("pushing\u2026");
867
- const pushed = await git(
868
- [...credentialConfig(server), "push", "--porcelain", "origin", "HEAD:main"],
869
- { cwd: root, echo: !out.json, env: authEnv(server) }
833
+ async function pushCopy(out, copy, message) {
834
+ const changes = changesOf(copy);
835
+ if (changes.length === 0) return { pushed: false, rev: copy.base.rev, uploaded: [] };
836
+ noteSizes(
837
+ out,
838
+ copy.root,
839
+ changes.filter((c) => c.hash).map((c) => c.path)
870
840
  );
871
- const remote = remoteLines(pushed.stderr);
872
- if (pushed.code !== 0) {
873
- const { message: message2, exit, ...extra } = pushFailure(pushed.stdout + pushed.stderr, remote);
874
- throw new CliError(message2, exit, { remote, ...extra });
841
+ for (const { path, hash } of changes) out.note(` ${hash ? "" : "deleted "}${path}`);
842
+ out.note("pushing\u2026");
843
+ const written = await writeCopy(copy, message || "Update the deck", { note: (m) => out.note(m) });
844
+ try {
845
+ await pullInto(
846
+ copy.root,
847
+ copy.base.deck,
848
+ copy.base.server,
849
+ { ...copy.base, files: Object.fromEntries(copyFiles(copy.root)) },
850
+ { note: (m) => out.note(m) }
851
+ );
852
+ } catch (error) {
853
+ out.note(
854
+ `Pushed, but the copy couldn't take the version it made: run \`tobos pull\`. (${error.message})`,
855
+ true
856
+ );
875
857
  }
876
- const rev = (await gitOk(["rev-parse", "HEAD"], { cwd: root })).trim();
877
- return { ok: true, rev, committed, uploaded, warnings, remote };
858
+ return {
859
+ pushed: true,
860
+ rev: written.rev,
861
+ uploaded: written.uploaded,
862
+ problems: written.problems
863
+ };
878
864
  }
879
865
  async function push(out, args) {
880
- const deck = await requireRemote();
881
- const result = await pushWorkingCopy(out, deck, args.values.message);
882
- if (!result.ok) {
883
- out.result(
884
- { ...result, pushed: false },
885
- () => `${formatProblems(result.problems)}
886
- \u2717 Not pushed: ${plural(result.errors, "error")}. Fix them and push again.`
887
- );
888
- process.exitCode = EXIT.problems;
889
- return;
890
- }
891
- const url = `${deck.server}/${deck.id}`;
866
+ const copy = requireCopy();
867
+ const result = await pushCopy(out, copy, args.values.message);
868
+ const url = `${copy.base.server}/${copy.base.deck}`;
892
869
  out.result(
893
- { ...result, pushed: true, url },
894
- () => `\u2713 Pushed ${result.rev.slice(0, 7)}${result.uploaded.length ? ` with ${plural(result.uploaded.length, "media file")}` : ""}. Live at ${url}`
870
+ { ...result, url },
871
+ () => result.pushed ? `\u2713 Pushed ${result.rev?.slice(0, 7)}${result.uploaded.length ? ` with ${plural(result.uploaded.length, "media file")}` : ""}. Live at ${url}` : `Nothing to push: the copy is as the server has it. Live at ${url}`
895
872
  );
896
873
  }
897
874
  async function pushIfChanged(out, id, message) {
898
- const found = await findDeck().catch(() => void 0);
899
- if (!found?.server || found.id !== id) return { pushed: false, uploaded: [] };
900
- const deck = found;
901
- const dirty = (await gitOk(["status", "--porcelain"], { cwd: deck.root })).trim() !== "";
902
- const head = await git(["rev-parse", "--verify", "--quiet", "HEAD"], { cwd: deck.root });
903
- const remote = await git(["rev-parse", "--verify", "--quiet", "origin/main"], { cwd: deck.root });
904
- if (!dirty && head.stdout.trim() === remote.stdout.trim())
905
- return { pushed: false, uploaded: [] };
906
- const result = await pushWorkingCopy(out, deck, message);
907
- if (!result.ok)
908
- throw new CliError(
909
- `${formatProblems(result.problems)}
910
- \u2717 ${plural(result.errors, "error")} in your working copy. Fix them and try again.`,
911
- EXIT.problems,
912
- { problems: result.problems }
913
- );
914
- return { pushed: true, uploaded: result.uploaded };
915
- }
916
- async function identity(root) {
917
- if ((await git(["config", "user.email"], { cwd: root })).code === 0) return {};
918
- const who = settings().email;
919
- return {
920
- GIT_AUTHOR_NAME: who ?? "tobos",
921
- GIT_AUTHOR_EMAIL: who ?? "tobos@localhost",
922
- GIT_COMMITTER_NAME: who ?? "tobos",
923
- GIT_COMMITTER_EMAIL: who ?? "tobos@localhost"
924
- };
875
+ const found = findCopy();
876
+ if (!found?.base || found.base.deck !== id) return { pushed: false, uploaded: [] };
877
+ const { pushed, uploaded } = await pushCopy(out, found, message);
878
+ return { pushed, uploaded };
925
879
  }
926
880
  async function viewUrl(id, view, hours) {
927
881
  return api(`/api/decks/${id}/view`, { body: { view, hours } });
928
882
  }
929
883
  async function deckId(args) {
930
884
  if (typeof args.values.deck === "string") return parseId(args.values.deck);
931
- return (await requireRemote()).id;
885
+ return requireCopy().base.deck;
932
886
  }
933
887
  async function open(out, args) {
934
888
  const position = args.positionals[0];
935
- if (!position && typeof args.values.deck !== "string" && !await findDeck().catch(() => null))
936
- return openApp(out);
937
- const view = args.values.presenter ? "presenter" : void 0;
889
+ if (!position && typeof args.values.deck !== "string" && !findCopy()?.base) return openApp(out);
938
890
  const id = await deckId(args);
939
891
  const { pushed } = await pushIfChanged(out, id);
940
- const { url } = await viewUrl(id, view, 12);
892
+ const url = args.values.presenter ? (await viewUrl(id, "presenter", 12)).url : `${settings().server}/${id}`;
941
893
  const full = position ? `${url}#${position}` : url;
942
894
  const opened = !args.values.print && await openUrl(full);
943
895
  out.result({ url: full, opened, pushed }, () => full);
@@ -1014,44 +966,12 @@ async function story(out, args) {
1014
966
  }
1015
967
  throw new CliError(`No \`tobos story ${action}\`: edit, add or delete.`);
1016
968
  }
1017
- async function exportTarget(args, file2) {
1018
- if (args.values.out) return resolve2(args.values.out);
1019
- const deck = await findDeck().catch(() => void 0);
1020
- if (!deck) return resolve2(file2);
1021
- mkdirSync5(join7(deck.root, ".tobos", "exports"), { recursive: true });
1022
- return join7(deck.root, ".tobos", "exports", file2);
1023
- }
1024
- async function exportDeck(out, args) {
1025
- const kind = args.positionals[0];
1026
- if (kind !== "pdf") throw new CliError("Export what? `tobos export pdf`.");
1027
- const id = await deckId(args);
1028
- out.note("getting the PDF of the latest push\u2026");
1029
- const response = await request(`/api/decks/${id}/deck.pdf`);
1030
- if (!response.ok) {
1031
- const text = await response.text();
1032
- let data;
1033
- try {
1034
- data = JSON.parse(text);
1035
- } catch {
1036
- data = { error: text.slice(0, 500) };
1037
- }
1038
- throw failure(response, data);
1039
- }
1040
- const pdf = new Uint8Array(await response.arrayBuffer());
1041
- const target = await exportTarget(args, `${id}.pdf`);
1042
- mkdirSync5(dirname3(target), { recursive: true });
1043
- writeFileSync5(target, pdf);
1044
- const pages = Buffer.from(pdf).toString("latin1").match(/\/Type\s*\/Page(?![s\w])/g)?.length ?? 0;
1045
- out.result(
1046
- { file: target, pages },
1047
- () => `Wrote ${relative2(process.cwd(), target)} (${pages} pages).`
1048
- );
1049
- }
1050
969
  async function render(out, args) {
1051
- const { renderBeats } = await import("./render-C7UKAYCT.js");
1052
- const deck = await findDeck().catch(() => void 0);
970
+ const { renderBeats } = await import("./render-WZUAK4TK.js");
971
+ const copy = findCopy();
972
+ const deck = copy?.base ? { id: copy.base.deck, root: copy.root } : void 0;
1053
973
  const id = typeof args.values.deck === "string" ? parseId(args.values.deck) : deck?.id;
1054
- if (!id) throw new CliError("Run this inside a cloned deck, or pass --deck <id>.");
974
+ if (!id) throw new CliError("Run this inside a deck you pulled, or pass --deck <id>.");
1055
975
  const { pushed, uploaded } = await pushIfChanged(out, id, args.values.message);
1056
976
  const view = await viewUrl(id, "render");
1057
977
  const { url } = view;
@@ -1073,7 +993,7 @@ async function render(out, args) {
1073
993
  } else targets2.push(...scene.beats.map((b) => `${scene.id}/${b}`));
1074
994
  }
1075
995
  const root = deck?.id === id ? deck.root : ".";
1076
- const dir2 = resolve2(args.values.out ?? join7(root, ".tobos", "render"));
996
+ const dir2 = resolve2(args.values.out ?? join5(root, ".tobos", "render"));
1077
997
  const { files, errors } = await renderBeats(url, targets2, {
1078
998
  dir: dir2,
1079
999
  film: Boolean(args.values.film),
@@ -1111,27 +1031,6 @@ async function skill(out, args) {
1111
1031
  ].join("\n")
1112
1032
  );
1113
1033
  }
1114
- async function credential(args) {
1115
- if (args.positionals[0] !== "get") return;
1116
- const input = readFileSync5(0, "utf8");
1117
- const fields = Object.fromEntries(
1118
- input.split("\n").filter((l) => l.includes("=")).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)])
1119
- );
1120
- let stored;
1121
- try {
1122
- stored = settings();
1123
- } catch (error) {
1124
- process.stderr.write(`tobos: ${error.message}
1125
- `);
1126
- return;
1127
- }
1128
- const { server, token } = stored;
1129
- const target = new URL(server);
1130
- if (!token || fields.host !== target.host || `${fields.protocol}:` !== target.protocol) return;
1131
- process.stdout.write(`username=tobos
1132
- password=${token}
1133
- `);
1134
- }
1135
1034
 
1136
1035
  // src/main.ts
1137
1036
  var HELP = `tobos ${VERSION}: the command line of Tobos, the office suite your coding agent works in.
@@ -1141,7 +1040,7 @@ Account
1141
1040
  tobos login --code <code> finish: the code they read from the mail
1142
1041
  tobos logout forget this machine's token
1143
1042
  tobos whoami who you are, on which server
1144
- tobos decks [/path] your decks and templates, by id, each in its folder,
1043
+ tobos ls [/path] your decks and templates, by id, each in its folder,
1145
1044
  and those shared with you; an archived one is
1146
1045
  read-only. With a path: what that folder holds,
1147
1046
  its folders, then its decks
@@ -1150,26 +1049,28 @@ Folders (your decks and templates in a tree; a deck by its id or title, a folder
1150
1049
  tobos mv <deck or /folder>\u2026 </path> move them into that folder, made if there is none;
1151
1050
  a folder a move empties goes
1152
1051
 
1153
- Working on a deck
1154
- tobos new "Title" [--dir dir] [--no-clone] create a deck and clone it here, into ./<id>
1155
- (or into dir; --no-clone: only create it)
1156
- tobos clone <id> [dir] clone a deck, with the agent pack
1157
- tobos pull get the latest pushes and the format guide
1158
- tobos check [--types] compile and check the deck, offline (~1 s);
1159
- --types: TypeScript too (installs a checker once)
1160
- tobos push [-m "what changed"] upload media, commit, push; the server checks it
1052
+ Working on a deck (a working copy: no git; the server keeps the versions)
1053
+ tobos new "Title" [--dir dir] [--no-pull] create a deck and pull it here, into ./<id>
1054
+ (or into dir; --no-pull: only create it)
1055
+ tobos pull <id> [dir] a working copy of a deck, with the agent pack
1056
+ tobos pull the latest version into the copy, merged with your
1057
+ changes; a conflict is left between <<<<<<< and
1058
+ >>>>>>> to resolve; and the format guide
1059
+ tobos check [--types] the server's check of your changes; nothing lands;
1060
+ --types: TypeScript too, here (installs a checker once)
1061
+ tobos push [-m "what changed"] your changes as one version, media uploaded; the
1062
+ server checks it, and it goes live
1161
1063
 
1162
1064
  Looking at it (from the working copy, render and open push what changed first; with --deck <id>,
1163
1065
  from anywhere)
1164
1066
  tobos render scene/beat | scene | --all PNGs of beats, for you to look at
1165
1067
  [--film] [--frames 6] [--out dir] --film: frames through the animation
1166
1068
  [--scale 2] [-m "what changed"] --scale: pixels per stage pixel; -m: for the push
1167
- tobos open [scene/beat] [--presenter] the deck in a browser (prints the URL, which opens once)
1168
- [--print] --print: print the URL only, open nothing
1069
+ tobos open [scene/beat] [--presenter] the deck's page in a browser (--presenter: a
1070
+ [--print] presenter's link, which opens once); --print: print
1071
+ the URL only, open nothing
1169
1072
  tobos open outside a deck: a link, or its code for /login,
1170
1073
  that logs a browser in once; show the person both
1171
- tobos export pdf [--out file] the deck's PDF, as its page and its link give it:
1172
- a page per scene at its last beat, no polls
1173
1074
 
1174
1075
  The story (what the speaker says, held by the server; a scene mentioned: [Title](scene:<id>),
1175
1076
  a beat: [Title](scene:<id>/<beat>))
@@ -1186,13 +1087,14 @@ The skill (what your harness reads to know Tobos without this help)
1186
1087
 
1187
1088
  Templates (decks people start from: a new deck copies a template's master/)
1188
1089
  tobos new "Title" --from <id> start a deck from that template (default: Tobos
1189
- simple; \`tobos decks\` lists the person's own)
1090
+ simple; \`tobos ls\` lists the person's own)
1190
1091
  tobos new "Our brand" --template a new template: a copy of Tobos simple (or of --from)
1191
1092
 
1192
1093
  Every command takes --json and then prints one JSON object.
1193
- Exit codes: 0 ok, 1 error, 2 the deck has problems, 3 not logged in, 4 the story changed
1194
- meanwhile (the reply has the paragraph as it is now: anchor on that and try again), 5 a plan's
1195
- limit or an archived deck: the person decides what to do, so show them the message and wait.
1094
+ Exit codes: 0 ok, 1 error, 2 the deck has problems, 3 not logged in, 4 a conflict: someone
1095
+ changed the same lines (pull, resolve, push again; for the story, the reply has the paragraph as
1096
+ it is now), 5 a plan's limit or an archived deck: the person decides what to do, so show them the
1097
+ message and wait.
1196
1098
  `;
1197
1099
  var COMMON = {
1198
1100
  json: { type: "boolean" },
@@ -1205,18 +1107,17 @@ var TABLE = {
1205
1107
  },
1206
1108
  logout: { run: logout },
1207
1109
  whoami: { run: whoami },
1208
- decks: { run: decks },
1110
+ ls: { run: ls },
1209
1111
  new: {
1210
1112
  run: create,
1211
1113
  options: {
1212
1114
  dir: { type: "string" },
1213
- "no-clone": { type: "boolean" },
1115
+ "no-pull": { type: "boolean" },
1214
1116
  from: { type: "string" },
1215
1117
  template: { type: "boolean" }
1216
1118
  }
1217
1119
  },
1218
1120
  mv: { run: mv },
1219
- clone: { run: clone },
1220
1121
  pull: { run: pull },
1221
1122
  check: { run: check, options: { types: { type: "boolean" } } },
1222
1123
  push: { run: push, options: { message: { type: "string", short: "m" } } },
@@ -1228,13 +1129,6 @@ var TABLE = {
1228
1129
  print: { type: "boolean" }
1229
1130
  }
1230
1131
  },
1231
- export: {
1232
- run: exportDeck,
1233
- options: {
1234
- out: { type: "string" },
1235
- deck: { type: "string" }
1236
- }
1237
- },
1238
1132
  skill: { run: skill },
1239
1133
  story: {
1240
1134
  run: story,
@@ -1264,10 +1158,6 @@ async function main(argv) {
1264
1158
  `);
1265
1159
  return;
1266
1160
  }
1267
- if (name === "credential") {
1268
- await credential({ positionals: rest, values: {} });
1269
- return;
1270
- }
1271
1161
  const command = TABLE[name];
1272
1162
  const json = rest.includes("--json");
1273
1163
  const out = createOutput(json);