@foleo/cli 0.1.35 → 0.1.45

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/index.js CHANGED
@@ -1,14 +1,18 @@
1
1
  #!/usr/bin/env node
2
+ import { workspaceCommand, WORKSPACE_HELP } from "./workspaces.js";
2
3
  import { spawn } from "node:child_process";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import { constants } from "node:fs";
5
- import { lstat as defaultLstat, readFile, realpath, stat as defaultStat, } from "node:fs/promises";
6
+ import { mkdir, mkdtemp, rm, writeFile, lstat as defaultLstat, readFile, realpath, stat as defaultStat, } from "node:fs/promises";
6
7
  import { open } from "node:fs/promises";
7
8
  import { lstat, readdir } from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
8
10
  import { createServer } from "node:http";
9
11
  import { dirname, join, relative, resolve, sep } from "node:path";
10
12
  import { fileURLToPath, pathToFileURL } from "node:url";
11
13
  import { FoleoError, LocalError, renderFailure, toFoleoError, UsageError, } from "./errors.js";
14
+ import { auditImages } from "./images.js";
15
+ import { optimizeImages, } from "./image-encoder.js";
12
16
  import { deriveArtifactName, resolveHtmlTitle, resolveVisibility, } from "./plan.js";
13
17
  const KEYCHAIN_SERVICE = "com.contraverse.foleo.cli";
14
18
  /**
@@ -33,6 +37,7 @@ const CLI_KEY_SCOPES = [
33
37
  "html:unpublish",
34
38
  ];
35
39
  const HTML_BUNDLE_MAX_FILES = 1_000;
40
+ const HTML_BUNDLE_MAX_NEW_FILES = 300;
36
41
  const HTML_BUNDLE_MAX_HTML_FILES = 100;
37
42
  const HTML_BUNDLE_MAX_BYTES = 100 * 1024 * 1024;
38
43
  const HTML_BUNDLE_MAX_FILE_BYTES = 8 * 1024 * 1024;
@@ -55,6 +60,7 @@ export const SETTINGS_SURFACE_FIELD_IDS = [
55
60
  "slug",
56
61
  "slugUserSet",
57
62
  "frontmatterDisplay",
63
+ "foleoBarDisplay",
58
64
  "visibility",
59
65
  "password",
60
66
  "customDomain",
@@ -101,6 +107,87 @@ const LIVE_DOC_ASSET_MEDIA_TYPES = {
101
107
  ".webp": "image/webp",
102
108
  ".avif": "image/avif",
103
109
  };
110
+ const uploadRuns = new WeakMap();
111
+ const jsonOutputs = new WeakMap();
112
+ /** Cleanup cannot turn an already observed failure into cancellation. */
113
+ async function cancelUploadSessions(deps, sessions) {
114
+ const cleanup = new AbortController();
115
+ let timer;
116
+ try {
117
+ await Promise.race([
118
+ new Promise((resolve) => {
119
+ timer = setTimeout(resolve, 2800);
120
+ }),
121
+ (async () => {
122
+ const credential = await resolveCredentialWithSource(deps);
123
+ if (!credential)
124
+ return;
125
+ await Promise.allSettled([...sessions].map((id) => deps.fetch(`${apiBase(deps)}/uploads/${encodeURIComponent(id)}/cancel`, {
126
+ method: "POST",
127
+ headers: { authorization: `Bearer ${credential.token}` },
128
+ signal: cleanup.signal,
129
+ })));
130
+ })(),
131
+ ]);
132
+ }
133
+ catch {
134
+ // Expiry remains the fallback when cancellation is unavailable.
135
+ }
136
+ finally {
137
+ clearTimeout(timer);
138
+ cleanup.abort();
139
+ }
140
+ }
141
+ function uploadRun(deps) {
142
+ const existing = uploadRuns.get(deps);
143
+ if (existing)
144
+ return existing;
145
+ const controller = new AbortController();
146
+ const sessions = new Set();
147
+ let stopping = false;
148
+ const handler = (signal) => {
149
+ if (stopping || run.failed)
150
+ return;
151
+ stopping = true;
152
+ if (!run.submitted) {
153
+ const rendered = renderFailure(new LocalError("cancelled", "Upload cancelled; nothing was published.", { retryable: true }), jsonOutputs.get(deps) ?? false);
154
+ if (rendered.stdout !== null)
155
+ deps.stdout(rendered.stdout);
156
+ if (rendered.stderr !== null)
157
+ deps.stderr(rendered.stderr);
158
+ run.reported = true;
159
+ }
160
+ controller.abort();
161
+ void cancelUploadSessions(deps, sessions).finally(() => {
162
+ (deps.exit ?? process.exit)(signal === "SIGINT" ? 130 : 143);
163
+ });
164
+ };
165
+ const onInt = () => handler("SIGINT");
166
+ const onTerm = () => handler("SIGTERM");
167
+ const remove = deps.onUploadSignal
168
+ ? deps.onUploadSignal(handler)
169
+ : (() => {
170
+ process.on("SIGINT", onInt);
171
+ process.on("SIGTERM", onTerm);
172
+ return () => {
173
+ process.off("SIGINT", onInt);
174
+ process.off("SIGTERM", onTerm);
175
+ };
176
+ })();
177
+ const run = {
178
+ reported: false,
179
+ submitted: false,
180
+ failed: false,
181
+ sessions,
182
+ controller,
183
+ dispose: () => {
184
+ remove();
185
+ uploadRuns.delete(deps);
186
+ },
187
+ };
188
+ uploadRuns.set(deps, run);
189
+ return run;
190
+ }
104
191
  export async function runCli(argv, deps = {
105
192
  fetch,
106
193
  readFile,
@@ -109,17 +196,26 @@ export async function runCli(argv, deps = {
109
196
  stderr: (message) => process.stderr.write(message),
110
197
  }) {
111
198
  const wantsJson = argv.includes("--json");
199
+ let activeDeps = deps;
112
200
  try {
113
201
  const global = parseGlobalFlags(argv);
114
202
  const commandDeps = global.environment
115
203
  ? { ...deps, env: { ...deps.env, FOLEO_ENV: global.environment } }
116
204
  : deps;
205
+ activeDeps = commandDeps;
206
+ jsonOutputs.set(commandDeps, wantsJson);
117
207
  const [command, ...rest] = global.argv;
208
+ if (rest.includes("--optimize-images") &&
209
+ !["publish", "update"].includes(command ?? "")) {
210
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
211
+ }
118
212
  if (command === undefined ||
119
213
  command === "help" ||
120
214
  command === "--help" ||
121
- command === "-h") {
122
- commandDeps.stdout(help());
215
+ command === "-h" ||
216
+ (command === "settings" &&
217
+ (rest.includes("--help") || rest.includes("-h")))) {
218
+ commandDeps.stdout(help() + "\n" + WORKSPACE_HELP);
123
219
  return 0;
124
220
  }
125
221
  if (command === "--version" || command === "-v" || command === "version") {
@@ -147,6 +243,35 @@ export async function runCli(argv, deps = {
147
243
  operation: describeArgvToken(command),
148
244
  });
149
245
  }
246
+ if (command === "workspace" ||
247
+ command === "capabilities" ||
248
+ command === "approval") {
249
+ return await workspaceCommand(command === "capabilities"
250
+ ? ["capabilities", ...rest]
251
+ : command === "approval"
252
+ ? ["approval", ...rest]
253
+ : rest, {
254
+ stdout: commandDeps.stdout,
255
+ readStdin: () => readStdinText(commandDeps),
256
+ request: async (path, init) => {
257
+ const credential = await resolveCredentialWithSource(commandDeps);
258
+ if (!credential)
259
+ throw new LocalError("credential_missing", "No Foleo credential found.", { next: "Sign in or set FOLEO_TOKEN." });
260
+ const response = await commandDeps.fetch(`${apiBase(commandDeps)}${path}`, init
261
+ ? {
262
+ ...init,
263
+ headers: {
264
+ ...Object.fromEntries(new Headers(init.headers)),
265
+ authorization: `Bearer ${credential.token}`,
266
+ },
267
+ }
268
+ : { headers: { authorization: `Bearer ${credential.token}` } });
269
+ if (!response.ok)
270
+ throw apiResponseError(response.status, await response.json());
271
+ return response;
272
+ },
273
+ });
274
+ }
150
275
  if (command === "publish")
151
276
  return await publish(rest, commandDeps);
152
277
  if (command === "update")
@@ -169,6 +294,8 @@ export async function runCli(argv, deps = {
169
294
  return await status(rest, commandDeps);
170
295
  if (command === "get")
171
296
  return await status(rest, commandDeps);
297
+ if (command === "export")
298
+ return await exportArtifact(rest, commandDeps);
172
299
  if (command === "html-publish") {
173
300
  warnDeprecatedAlias(commandDeps, "html-publish", "publish <path> --accept-hosting-risk");
174
301
  return await htmlPublish(rest, commandDeps);
@@ -223,6 +350,15 @@ export async function runCli(argv, deps = {
223
350
  return 2;
224
351
  }
225
352
  catch (error) {
353
+ const run = uploadRuns.get(activeDeps);
354
+ if (run?.reported)
355
+ return 1;
356
+ if (run) {
357
+ // Capture the cause before any asynchronous cleanup or later signal.
358
+ run.failed = true;
359
+ if (!run.submitted && run.sessions.size)
360
+ await cancelUploadSessions(activeDeps, run.sessions);
361
+ }
226
362
  const rendered = renderFailure(normalizeThrown(error), wantsJson);
227
363
  if (rendered.stdout !== null)
228
364
  deps.stdout(rendered.stdout);
@@ -230,6 +366,10 @@ export async function runCli(argv, deps = {
230
366
  deps.stderr(rendered.stderr);
231
367
  return rendered.exitCode;
232
368
  }
369
+ finally {
370
+ uploadRuns.get(activeDeps)?.dispose();
371
+ jsonOutputs.delete(activeDeps);
372
+ }
233
373
  }
234
374
  /**
235
375
  * Usage-shaped failures exit 2 even when they were thrown as a plain `Error`.
@@ -611,8 +751,23 @@ function stringArray(value) {
611
751
  async function login(args, deps) {
612
752
  const parsed = parseFlags(args, { allowLoginScopeFlags: true });
613
753
  if (parsed.positionals.length > 0)
614
- throw new Error("Usage: foleo login [--allow-purge] [--json]");
754
+ throw new Error("Usage: foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
615
755
  const base = apiBase(deps);
756
+ const workspaceScopes = [
757
+ ...(parsed.allowWorkspaces || parsed.allowWorkspaceSharing
758
+ ? ["workspaces:read"]
759
+ : []),
760
+ ...(parsed.allowWorkspaces ? ["workspaces:write"] : []),
761
+ ...(parsed.allowWorkspaceSharing ? ["workspaces:share"] : []),
762
+ ];
763
+ const target = new URL(base);
764
+ if (workspaceScopes.length &&
765
+ !(target.origin === "https://api-staging.foleo.app" ||
766
+ (target.protocol === "http:" &&
767
+ ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname))))
768
+ throw new LocalError("workspace_login_unavailable", "Workspace login flags are available only on staging/local. Production workspace access is disabled.", {
769
+ next: "Use FOLEO_ENV=staging foleo login --allow-workspaces (add --allow-workspace-sharing for sharing).",
770
+ });
616
771
  announceApi(deps, parsed.json);
617
772
  const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
618
773
  const saveCredential = deps.saveCredential ?? saveKeychainCredential;
@@ -630,7 +785,12 @@ async function login(args, deps) {
630
785
  let loginResult = null;
631
786
  let operationError = null;
632
787
  try {
633
- const start = await requestPublicJson(deps, "/desktop/handoff/start", { nonce, callbackUrl: callback.callbackUrl, clientKind: "cli" });
788
+ const start = await requestPublicJson(deps, "/desktop/handoff/start", {
789
+ nonce,
790
+ callbackUrl: callback.callbackUrl,
791
+ clientKind: "cli",
792
+ ...(workspaceScopes.length ? { workspaceScopes } : {}),
793
+ });
634
794
  deps.stderr("Opening Foleo sign-in in your browser...\n");
635
795
  try {
636
796
  await openUrl(start.authorizeUrl);
@@ -655,6 +815,7 @@ async function login(args, deps) {
655
815
  scopes: [
656
816
  ...CLI_KEY_SCOPES,
657
817
  ...(parsed.allowPurge ? ["artifacts:purge"] : []),
818
+ ...workspaceScopes.filter((scope) => exchanged.approvedWorkspaceScopes?.includes(scope)),
658
819
  ],
659
820
  deferredActivation: true,
660
821
  },
@@ -884,7 +1045,8 @@ function refuseUnavailableName(label, availability, next) {
884
1045
  /** The largest bundle files by size, so a dry run can flag a heavy upload before it starts. */
885
1046
  const DRY_RUN_LARGEST_FILES_SHOWN = 5;
886
1047
  async function htmlPublishDryRun(root, name, parsed, deps) {
887
- const { files, skipped, routes } = await scanBundle(root, deps);
1048
+ const { files, skipped, routes, warnings, imageOptimization } = await prepareImageBundle(root, deps, parsed);
1049
+ assertFirstPublishFileBudget(files.length);
888
1050
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
889
1051
  const entryFile = files.find((file) => file.path === "/index.html");
890
1052
  const entryHtml = entryFile
@@ -967,6 +1129,8 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
967
1129
  const previewUrl = artifactPreviewUrl(derived, deps);
968
1130
  const plan = {
969
1131
  ok: true,
1132
+ warnings,
1133
+ ...(imageOptimization ? { imageOptimization } : {}),
970
1134
  plan: {
971
1135
  action: "create",
972
1136
  scope: cost === null ? "bundle-only" : "full",
@@ -1016,6 +1180,7 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1016
1180
  totalBytes: files.reduce((n, file) => n + file.byteSize, 0),
1017
1181
  entry: "/index.html",
1018
1182
  routes,
1183
+ files: files.map(({ bytes: _bytes, ...file }) => file),
1019
1184
  notFoundPage: files.some((file) => file.path === "/404.html")
1020
1185
  ? "/404.html"
1021
1186
  : null,
@@ -1098,6 +1263,8 @@ function htmlWireOptions(parsed) {
1098
1263
  ? {}
1099
1264
  : { runtimeProfile: parsed.runtimeProfile }),
1100
1265
  acknowledgeAccessWidening: parsed.acknowledgeAccessWidening,
1266
+ optimizeImages: parsed.optimizeImages,
1267
+ json: parsed.json,
1101
1268
  };
1102
1269
  }
1103
1270
  async function htmlUpdate(args, deps) {
@@ -1190,7 +1357,7 @@ async function settingsCommand(args, deps) {
1190
1357
  }
1191
1358
  announceApi(deps, parsed.json);
1192
1359
  if (Object.keys(patch).length === 0) {
1193
- writeResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1360
+ writeSettingsResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1194
1361
  method: "GET",
1195
1362
  body: undefined,
1196
1363
  }), parsed.json);
@@ -1200,7 +1367,7 @@ async function settingsCommand(args, deps) {
1200
1367
  if (revision === null) {
1201
1368
  throw new Error("Usage: foleo settings <id> --set k=v ... --revision <etag> [--acknowledge-access-widening] [--json]");
1202
1369
  }
1203
- writeResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1370
+ writeSettingsResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1204
1371
  method: "PATCH",
1205
1372
  body: {
1206
1373
  settings: patch,
@@ -1331,6 +1498,125 @@ async function htmlUnpublish(args, deps) {
1331
1498
  writeResult(deps, result, parsed.json);
1332
1499
  return 0;
1333
1500
  }
1501
+ function withImageReport(result, warnings, imageOptimization) {
1502
+ const record = result !== null && typeof result === "object"
1503
+ ? result
1504
+ : {};
1505
+ return {
1506
+ ...record,
1507
+ ...(warnings.length
1508
+ ? {
1509
+ warnings: [
1510
+ ...(Array.isArray(record.warnings) ? record.warnings : []),
1511
+ ...warnings,
1512
+ ],
1513
+ }
1514
+ : {}),
1515
+ ...(imageOptimization ? { imageOptimization } : {}),
1516
+ };
1517
+ }
1518
+ function reportHeavyImages(deps, warnings, html, json = false) {
1519
+ if (json || !warnings.length)
1520
+ return;
1521
+ for (const w of warnings.slice(0, 10))
1522
+ deps.stderr(`Heavy image: ${w.path} (${w.bytes} bytes${w.width ? `, ${w.width} × ${w.height}` : ""})\n`);
1523
+ if (warnings.length > 10)
1524
+ deps.stderr(`(+${warnings.length - 10} more)\n`);
1525
+ const mb = (warnings.reduce((n, w) => n + w.bytes, 0) / 1_000_000).toFixed(2);
1526
+ deps.stderr(`${warnings.length} images are heavy (${mb} MB). ${html ? "For HTML, --optimize-images makes smaller AVIF copies for readers; your folder is not changed." : "Resize images before publishing to reduce what readers download."}\n`);
1527
+ }
1528
+ export async function prepareImageBundle(root, deps, options = {}) {
1529
+ const scanned = await scanBundle(root, deps);
1530
+ const localDigest = htmlLocalDigest(scanned.files);
1531
+ let files = scanned.files;
1532
+ let imageOptimization;
1533
+ const encoderWarnings = [];
1534
+ let optimized;
1535
+ if (options.optimizeImages !== false) {
1536
+ try {
1537
+ optimized = await optimizeImages(files, deps.imageProcessRunner);
1538
+ }
1539
+ catch (error) {
1540
+ if (options.optimizeImages === true ||
1541
+ !(error instanceof LocalError) ||
1542
+ error.code !== "image_encoder_unavailable")
1543
+ throw error;
1544
+ encoderWarnings.push({
1545
+ code: "image_encoder_unavailable",
1546
+ message: error.message,
1547
+ });
1548
+ if (!options.json)
1549
+ deps.stderr(`image_encoder_unavailable: ${error.message} Publishing without image optimization.\n`);
1550
+ }
1551
+ }
1552
+ if (optimized) {
1553
+ imageOptimization = optimized.imageOptimization;
1554
+ const scannedByPath = new Map(scanned.files.map((file) => [file.path, file]));
1555
+ files = optimized.files.map((file) => {
1556
+ const original = scannedByPath.get(file.path);
1557
+ if (original?.bytes === file.bytes)
1558
+ return original;
1559
+ return {
1560
+ path: file.path,
1561
+ bytes: file.bytes,
1562
+ byteSize: file.bytes.byteLength,
1563
+ sha256: createHash("sha256").update(file.bytes).digest("hex"),
1564
+ mediaType: mediaTypeFor(file.path),
1565
+ };
1566
+ });
1567
+ const total = files.reduce((n, f) => n + f.byteSize, 0);
1568
+ const extra = ` --optimize-images added ${imageOptimization.addedFiles} files / ${imageOptimization.addedBytes} bytes: ${imageOptimization.images.flatMap((i) => i.variants.map((v) => v.path)).join(", ")}`;
1569
+ const fail = (code, message) => {
1570
+ throw new LocalError(code, message + extra);
1571
+ };
1572
+ if (files.length > HTML_BUNDLE_MAX_FILES)
1573
+ fail("bundle_too_many_files", "Bundle exceeds the file-count limit.");
1574
+ if (total > HTML_BUNDLE_MAX_BYTES)
1575
+ fail("bundle_total_too_large", "Bundle exceeds the total size limit.");
1576
+ for (const f of files) {
1577
+ if (f.byteSize > HTML_BUNDLE_MAX_FILE_BYTES)
1578
+ fail("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${f.path}`);
1579
+ if (f.mediaType === "text/html; charset=utf-8" &&
1580
+ f.byteSize > HTML_BUNDLE_MAX_HTML_BYTES)
1581
+ fail("bundle_html_too_large", `HTML file exceeds the size limit: ${f.path}`);
1582
+ if (Buffer.byteLength(f.path) > HTML_BUNDLE_MAX_PATH_BYTES ||
1583
+ f.path
1584
+ .split("/")
1585
+ .some((p) => Buffer.byteLength(p) > HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES))
1586
+ fail("bundle_path_invalid", `Invalid bundle path: ${f.path}`);
1587
+ }
1588
+ if (!options.json) {
1589
+ const r = imageOptimization;
1590
+ const before = r.images.reduce((n, i) => n + i.bytes, 0);
1591
+ const after = r.images.reduce((n, i) => n +
1592
+ (i.variants.find((v) => v.width >= 1280) ?? i.variants.at(-1)).bytes, 0);
1593
+ if (r.images.length)
1594
+ deps.stderr(`Optimized ${r.images.length} images (${r.images.reduce((n, i) => n + i.tags, 0)} tags on ${optimized.pages} pages): readers download about ${(after / 1_000_000).toFixed(2)} MB instead of ${(before / 1_000_000).toFixed(2)} MB at 1280 px. Added ${r.addedFiles} files / ${r.addedBytes} bytes.\n`);
1595
+ for (const skip of r.skipped.slice(0, 10))
1596
+ deps.stderr(`image_optimize_skipped: ${skip.path} (${skip.reason})\n`);
1597
+ if (r.skipped.length > 10)
1598
+ deps.stderr(`(+${r.skipped.length - 10} more)\n`);
1599
+ }
1600
+ }
1601
+ const warnings = auditImages(files, new Set(imageOptimization?.images.map((i) => i.path)));
1602
+ reportHeavyImages(deps, warnings, true, options.json);
1603
+ return {
1604
+ ...scanned,
1605
+ localDigest,
1606
+ files,
1607
+ warnings: [...encoderWarnings, ...warnings],
1608
+ ...(imageOptimization ? { imageOptimization } : {}),
1609
+ };
1610
+ }
1611
+ function assertFirstPublishFileBudget(count) {
1612
+ if (count > HTML_BUNDLE_MAX_NEW_FILES) {
1613
+ const message = `This bundle has ${count} new files; the limit is ${HTML_BUNDLE_MAX_NEW_FILES} per first publish. Reduce the bundle before publishing. Updates may contain 1,000 total files when the server can reuse enough files.`;
1614
+ throw new LocalError("bundle_new_files_limit", message, {
1615
+ context: { limit: HTML_BUNDLE_MAX_NEW_FILES, count: count },
1616
+ next: "Reduce the bundle. For updates, keep files unchanged so the server can reuse them.",
1617
+ });
1618
+ }
1619
+ }
1334
1620
  async function publishBundle(root, deps, update, hostingRiskAcknowledged = false, publishSeparately = false, settings, wire = {}) {
1335
1621
  // Top-level fields every HTML create/update body carries (spec 103): the
1336
1622
  // runtime profile only when the caller chose one, and the widening
@@ -1341,7 +1627,7 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1341
1627
  : { runtimeProfile: wire.runtimeProfile }),
1342
1628
  ...accessWideningField(wire.acknowledgeAccessWidening === true),
1343
1629
  };
1344
- const { files, skipped } = await scanBundle(root, deps);
1630
+ const { files, skipped, warnings, imageOptimization, localDigest } = await prepareImageBundle(root, deps, wire);
1345
1631
  if (skipped.length > 0) {
1346
1632
  // Spec 089 §K.3 / L914: a dropped `.well-known/` must never be silent on
1347
1633
  // a real run either, not only in a `--dry-run` plan. stderr, unconditionally
@@ -1353,7 +1639,10 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1353
1639
  const rest = skipped.length > 10 ? ` (+${skipped.length - 10} more)` : "";
1354
1640
  deps.stderr(`Skipped ${skipped.length} bundle ${skipped.length === 1 ? "entry" : "entries"} not uploaded: ${shown}${rest}\n`);
1355
1641
  }
1642
+ if (!update)
1643
+ assertFirstPublishFileBudget(files.length);
1356
1644
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
1645
+ const filesByPath = new Map(files.map((file) => [file.path, file]));
1357
1646
  // One pacer for every /v1/ call in this publish: the zone rate-limit fence
1358
1647
  // counts the session create and complete calls against the same budget as the
1359
1648
  // file PUTs, so pacing only the PUTs overspends it.
@@ -1362,101 +1651,129 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1362
1651
  // retry is another request against the same fence, so pacing only the first
1363
1652
  // attempt spends the budget it was meant to protect.
1364
1653
  const budget = createRetryBudget();
1365
- const uploadKey = randomUUID();
1366
- const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1367
- await pace();
1368
- return requestJson(deps, "/uploads", {
1369
- method: "POST",
1370
- body: {
1371
- kind: "html-artifact-bundle",
1372
- manifest,
1373
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1374
- },
1375
- headers: { "idempotency-key": uploadKey },
1376
- });
1377
- }, budget);
1378
- let uploaded = 0;
1379
- for (const plan of upload.files) {
1380
- const file = files.find((candidate) => candidate.path === plan.path);
1381
- if (!file)
1382
- throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1383
- await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1384
- await pace();
1385
- return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1386
- }, budget);
1387
- uploaded += 1;
1388
- // A large bundle is paced to well under a minute's worth of requests, so a
1389
- // silent multi-minute publish reads as a hang. Progress goes to stderr so
1390
- // `--json` stdout stays machine-parseable.
1391
- if (upload.files.length > 20 && uploaded % 20 === 0) {
1392
- deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
1393
- }
1394
- }
1395
- const completeKey = randomUUID();
1396
- await withRateLimitRetry(deps, "finishing the upload", async () => {
1397
- await pace();
1398
- return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1399
- method: "POST",
1400
- body: {},
1401
- headers: { "idempotency-key": completeKey },
1402
- });
1403
- }, budget);
1404
- if (update)
1405
- await pace();
1406
- const sourceId = update
1407
- ? await ownerArtifactSourceId(deps, update.id)
1408
- : undefined;
1409
- const source = publishSourcePayload(upload.manifestHash, sourceId);
1410
- // The whole bundle is already uploaded by the time we get here, so losing this
1411
- // one request to a throttle discards the entire publish — the exact failure
1412
- // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1413
- // so a retry reuses it and cannot double-create.
1414
- const createKey = randomUUID();
1415
- return withRateLimitRetry(deps, "creating the artifact", async () => {
1416
- await pace();
1417
- if (update?.family === "compatibility") {
1418
- return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1419
- method: "PUT",
1420
- body: {
1421
- uploadId: upload.uploadId,
1422
- manifestHash: upload.manifestHash,
1423
- source,
1424
- ...wireFields,
1425
- },
1426
- headers: {
1427
- "if-match": `"r${update.revision}"`,
1428
- "idempotency-key": createKey,
1429
- },
1430
- });
1654
+ for (let attempt = 0; attempt < 2; attempt++) {
1655
+ const reuseFrom = update && attempt === 0 ? update.id : undefined;
1656
+ try {
1657
+ const uploadKey = randomUUID();
1658
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1659
+ await pace();
1660
+ return requestJson(deps, "/uploads", {
1661
+ method: "POST",
1662
+ body: {
1663
+ kind: "html-artifact-bundle",
1664
+ ...(reuseFrom ? { reuseFrom } : {}),
1665
+ manifest,
1666
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1667
+ },
1668
+ headers: { "idempotency-key": uploadKey },
1669
+ });
1670
+ }, budget);
1671
+ let uploaded = 0;
1672
+ let bytesUploaded = 0;
1673
+ for (const plan of upload.files) {
1674
+ const file = filesByPath.get(plan.path);
1675
+ if (!file)
1676
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1677
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1678
+ await pace();
1679
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1680
+ }, budget);
1681
+ uploaded += 1;
1682
+ bytesUploaded += file.byteSize;
1683
+ // A large bundle is paced to well under a minute's worth of requests, so a
1684
+ // silent multi-minute publish reads as a hang. Progress goes to stderr so
1685
+ // `--json` stdout stays machine-parseable.
1686
+ if (upload.files.length > 20 && uploaded % 20 === 0) {
1687
+ deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
1688
+ }
1689
+ }
1690
+ const completeKey = randomUUID();
1691
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
1692
+ await pace();
1693
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1694
+ method: "POST",
1695
+ body: {},
1696
+ headers: { "idempotency-key": completeKey },
1697
+ });
1698
+ }, budget);
1699
+ if (update)
1700
+ await pace();
1701
+ const sourceId = update
1702
+ ? await ownerArtifactSourceId(deps, update.id)
1703
+ : undefined;
1704
+ const source = {
1705
+ ...publishSourcePayload(upload.manifestHash, sourceId),
1706
+ localDigest,
1707
+ };
1708
+ // The whole bundle is already uploaded by the time we get here, so losing this
1709
+ // one request to a throttle discards the entire publish — the exact failure
1710
+ // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1711
+ // so a retry reuses it and cannot double-create.
1712
+ const createKey = randomUUID();
1713
+ const result = await withRateLimitRetry(deps, "creating the artifact", async () => {
1714
+ await pace();
1715
+ if (update?.family === "compatibility") {
1716
+ return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1717
+ method: "PUT",
1718
+ body: {
1719
+ uploadId: upload.uploadId,
1720
+ manifestHash: upload.manifestHash,
1721
+ source,
1722
+ ...wireFields,
1723
+ },
1724
+ headers: {
1725
+ "if-match": `"r${update.revision}"`,
1726
+ "idempotency-key": createKey,
1727
+ },
1728
+ });
1729
+ }
1730
+ if (update?.family === "generic") {
1731
+ return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1732
+ method: "PUT",
1733
+ body: {
1734
+ sourceFormat: "html",
1735
+ uploadId: upload.uploadId,
1736
+ manifestHash: upload.manifestHash,
1737
+ source,
1738
+ ...wireFields,
1739
+ },
1740
+ headers: artifactMutationHeaders(update.etag, createKey),
1741
+ });
1742
+ }
1743
+ return requestJson(deps, "/artifacts", {
1744
+ method: "POST",
1745
+ body: {
1746
+ sourceFormat: "html",
1747
+ uploadId: upload.uploadId,
1748
+ manifestHash: upload.manifestHash,
1749
+ hostingRiskAcknowledged,
1750
+ source,
1751
+ ...(publishSeparately ? { allowDuplicate: true } : {}),
1752
+ ...(settings && Object.keys(settings).length > 0
1753
+ ? { settings }
1754
+ : {}),
1755
+ ...wireFields,
1756
+ },
1757
+ headers: { "idempotency-key": createKey },
1758
+ });
1759
+ }, budget);
1760
+ const reused = upload.reused?.length ?? 0;
1761
+ if (!wire.json)
1762
+ deps.stderr(`Uploaded ${uploaded} of ${files.length} files (${reused} unchanged, reused).\nBytes uploaded: ${bytesUploaded}.\n`);
1763
+ return withImageReport({
1764
+ ...result,
1765
+ upload: { uploaded, reused, bytesUploaded },
1766
+ }, warnings, imageOptimization);
1431
1767
  }
1432
- if (update?.family === "generic") {
1433
- return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1434
- method: "PUT",
1435
- body: {
1436
- sourceFormat: "html",
1437
- uploadId: upload.uploadId,
1438
- manifestHash: upload.manifestHash,
1439
- source,
1440
- ...wireFields,
1441
- },
1442
- headers: artifactMutationHeaders(update.etag, createKey),
1443
- });
1768
+ catch (error) {
1769
+ if (!reuseFrom ||
1770
+ !(error instanceof FoleoError) ||
1771
+ error.code !== "reuse_source_missing")
1772
+ throw error;
1773
+ deps.stderr("Reuse source missing; retrying once with a full upload.\n");
1444
1774
  }
1445
- return requestJson(deps, "/artifacts", {
1446
- method: "POST",
1447
- body: {
1448
- sourceFormat: "html",
1449
- uploadId: upload.uploadId,
1450
- manifestHash: upload.manifestHash,
1451
- hostingRiskAcknowledged,
1452
- source,
1453
- ...(publishSeparately ? { allowDuplicate: true } : {}),
1454
- ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
1455
- ...wireFields,
1456
- },
1457
- headers: { "idempotency-key": createKey },
1458
- });
1459
- }, budget);
1775
+ }
1776
+ throw new LocalError("reuse_source_missing", "Full upload retry exhausted.");
1460
1777
  }
1461
1778
  function revisionHeaders(revision) {
1462
1779
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
@@ -1965,8 +2282,10 @@ async function publish(args, deps) {
1965
2282
  const parsed = parseFlags(args);
1966
2283
  const file = parsed.positionals[0];
1967
2284
  if (!file || parsed.positionals.length !== 1)
1968
- throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <label>] [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
2285
+ throw new Error("Usage: foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--accept-hosting-risk] [--name <label>] [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]\nAn HTML site bundle also requires --name <label>; Markdown does not.");
1969
2286
  const isDirectory = await pathIsDirectory(file, deps);
2287
+ if (parsed.optimizeImages && !isDirectory)
2288
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
1970
2289
  if (!isDirectory && parsed.dryRun) {
1971
2290
  throw new UsageError("--dry-run is only implemented for HTML site bundles (a directory with --accept-hosting-risk). A Markdown publish is not previewable yet; run it without --dry-run, or use `foleo publish <dir> --accept-hosting-risk --name <label> --dry-run`.", "dry_run_unsupported", { sourceFormat: "markdown" });
1972
2291
  }
@@ -1983,7 +2302,7 @@ async function publish(args, deps) {
1983
2302
  throw runtimeProfileNotApplicable({ sourceFormat: "markdown" });
1984
2303
  }
1985
2304
  const markdown = await deps.readFile(file, "utf8");
1986
- const assets = await uploadMarkdownAssets(file, markdown, deps);
2305
+ const assets = await uploadMarkdownAssets(file, markdown, deps, parsed.json);
1987
2306
  const result = await requestJson(deps, "/artifacts", {
1988
2307
  method: "POST",
1989
2308
  body: {
@@ -2000,32 +2319,61 @@ async function publish(args, deps) {
2000
2319
  : {}),
2001
2320
  ...accessWideningField(parsed.acknowledgeAccessWidening),
2002
2321
  },
2322
+ headers: { "idempotency-key": randomUUID() },
2003
2323
  });
2004
- writeResult(deps, result, parsed.json);
2324
+ writeResult(deps, withImageReport(result, assets?.warnings ?? []), parsed.json);
2005
2325
  return 0;
2006
2326
  }
2007
2327
  async function update(args, deps) {
2008
2328
  resolveUploadRate(deps);
2009
2329
  const parsed = parseFlags(args);
2010
- // Asking for a plan must never mutate. Until an update plan exists, refuse
2011
- // the flag rather than silently performing the real update.
2012
- if (parsed.dryRun) {
2013
- throw new UsageError("--dry-run is not implemented for update. Run the update without it.", "dry_run_unsupported", { operation: "update" });
2014
- }
2015
2330
  const [id, file] = parsed.positionals;
2016
2331
  if (!id || !file || parsed.positionals.length !== 2) {
2017
- throw new Error("Usage: foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json] (or Markdown compatibility --version <version>)");
2332
+ throw new Error("Usage: foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json] (or Markdown compatibility --version <version>)");
2018
2333
  }
2019
2334
  const isDirectory = await pathIsDirectory(file, deps);
2335
+ if (parsed.optimizeImages && !isDirectory)
2336
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
2020
2337
  if (isDirectory) {
2338
+ if (parsed.dryRun) {
2339
+ const bundle = await prepareImageBundle(file, deps, parsed);
2340
+ const plan = {
2341
+ ok: true,
2342
+ plan: {
2343
+ action: "update",
2344
+ id,
2345
+ scope: "bundle-only",
2346
+ executable: false,
2347
+ note: "Revision, access widening and safety review are checked by the server on apply.",
2348
+ bundle: {
2349
+ fileCount: bundle.files.length,
2350
+ totalBytes: bundle.files.reduce((n, f) => n + f.byteSize, 0),
2351
+ files: bundle.files.map(({ bytes: _bytes, ...f }) => f),
2352
+ routes: bundle.routes,
2353
+ skipped: bundle.skipped,
2354
+ },
2355
+ },
2356
+ warnings: bundle.warnings,
2357
+ ...(bundle.imageOptimization
2358
+ ? { imageOptimization: bundle.imageOptimization }
2359
+ : {}),
2360
+ };
2361
+ if (parsed.json)
2362
+ deps.stdout(`${JSON.stringify(plan, null, 2)}\n`);
2363
+ else
2364
+ deps.stdout(`plan: update ${id} (bundle-only; server checks pending)\nfiles: ${bundle.files.length}\n`);
2365
+ return 0;
2366
+ }
2021
2367
  const revision = artifactRevision(parsed.revision);
2022
2368
  if (revision === null) {
2023
- throw new Error("Usage: foleo update <id> <bundle-root> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json]");
2369
+ throw new Error("Usage: foleo update <id> <bundle-root> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]");
2024
2370
  }
2025
2371
  const result = await publishBundle(file, deps, { family: "generic", id, etag: revision }, false, false, undefined, htmlWireOptions(parsed));
2026
2372
  writeResult(deps, result, parsed.json);
2027
2373
  return 0;
2028
2374
  }
2375
+ if (parsed.dryRun)
2376
+ throw new UsageError("--dry-run is only implemented for HTML bundle folders", "dry_run_unsupported", { operation: "update" });
2029
2377
  if (!file.toLowerCase().endsWith(".md")) {
2030
2378
  throw new Error("Unsupported update input. Use a .md file or an HTML site directory.");
2031
2379
  }
@@ -2040,36 +2388,66 @@ async function update(args, deps) {
2040
2388
  throw new UsageError("--revision requires an opaque Artifact ETag", "revision_invalid");
2041
2389
  }
2042
2390
  const markdown = await deps.readFile(file, "utf8");
2043
- const assets = await uploadMarkdownAssets(file, markdown, deps);
2044
2391
  const sourceId = await ownerArtifactSourceId(deps, id);
2045
2392
  const source = publishSourcePayload(sha256Utf8(markdown), sourceId);
2046
- const result = opaqueRevision !== null
2047
- ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2048
- method: "PUT",
2049
- body: {
2050
- sourceFormat: "markdown",
2051
- markdown,
2052
- source,
2053
- ...(assets
2054
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
2055
- : {}),
2056
- ...accessWideningField(parsed.acknowledgeAccessWidening),
2057
- },
2058
- headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
2059
- })
2060
- : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
2061
- method: "PUT",
2062
- body: {
2063
- markdown,
2064
- version: parsed.version,
2065
- source,
2066
- ...(assets
2067
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
2068
- : {}),
2069
- ...accessWideningField(parsed.acknowledgeAccessWidening),
2070
- },
2071
- });
2072
- writeResult(deps, result, parsed.json);
2393
+ let assets = null;
2394
+ let result;
2395
+ for (let attempt = 0; attempt < 2; attempt++) {
2396
+ const reuseFrom = attempt === 0 ? id : undefined;
2397
+ try {
2398
+ assets = await uploadMarkdownAssets(file, markdown, deps, parsed.json, reuseFrom, id);
2399
+ result =
2400
+ opaqueRevision !== null
2401
+ ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2402
+ method: "PUT",
2403
+ body: {
2404
+ sourceFormat: "markdown",
2405
+ markdown,
2406
+ source,
2407
+ ...(assets
2408
+ ? {
2409
+ uploadId: assets.uploadId,
2410
+ manifestHash: assets.manifestHash,
2411
+ }
2412
+ : {}),
2413
+ ...accessWideningField(parsed.acknowledgeAccessWidening),
2414
+ },
2415
+ headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
2416
+ })
2417
+ : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
2418
+ method: "PUT",
2419
+ body: {
2420
+ markdown,
2421
+ version: parsed.version,
2422
+ source,
2423
+ ...(assets
2424
+ ? {
2425
+ uploadId: assets.uploadId,
2426
+ manifestHash: assets.manifestHash,
2427
+ }
2428
+ : {}),
2429
+ ...accessWideningField(parsed.acknowledgeAccessWidening),
2430
+ },
2431
+ headers: { "idempotency-key": randomUUID() },
2432
+ });
2433
+ break;
2434
+ }
2435
+ catch (error) {
2436
+ if (!reuseFrom ||
2437
+ !(error instanceof FoleoError) ||
2438
+ error.code !== "reuse_source_missing")
2439
+ throw error;
2440
+ deps.stderr("Reuse source missing; retrying once with a full upload.\n");
2441
+ }
2442
+ }
2443
+ writeResult(deps, {
2444
+ ...withImageReport(result, assets?.warnings ?? []),
2445
+ upload: assets?.upload ?? { uploaded: 0, reused: 0, bytesUploaded: 0 },
2446
+ }, parsed.json);
2447
+ if (!parsed.json) {
2448
+ const upload = assets?.upload ?? { uploaded: 0, reused: 0 };
2449
+ deps.stdout(`Uploaded ${upload.uploaded} of ${upload.uploaded + upload.reused} images (${upload.reused} reused).\n`);
2450
+ }
2073
2451
  return 0;
2074
2452
  }
2075
2453
  async function pathIsDirectory(path, deps) {
@@ -2211,10 +2589,27 @@ function liveDocAssetMediaType(path) {
2211
2589
  const extension = path.slice(path.lastIndexOf(".")).toLowerCase();
2212
2590
  return LIVE_DOC_ASSET_MEDIA_TYPES[extension] ?? null;
2213
2591
  }
2214
- async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2592
+ async function uploadMarkdownAssets(markdownPath, markdown, deps, json, reuseFrom, replaceEmptyFor) {
2215
2593
  const files = await scanMarkdownAssets(markdownPath, markdown, deps);
2216
- if (files.length === 0)
2217
- return null;
2594
+ const warnings = auditImages(files);
2595
+ reportHeavyImages(deps, warnings, false, json);
2596
+ if (files.length === 0) {
2597
+ if (!replaceEmptyFor)
2598
+ return null;
2599
+ // An omitted upload preserves the current attachments. Only request an
2600
+ // empty replacement when the owner read confirms there are attachments.
2601
+ let previous;
2602
+ try {
2603
+ previous = await requestJson(deps, `/artifacts/${encodeURIComponent(replaceEmptyFor)}/source/content?manifest=1`, { method: "GET", body: undefined });
2604
+ }
2605
+ catch (error) {
2606
+ if (error instanceof ApiRequestError && error.status === 404)
2607
+ return null;
2608
+ throw error;
2609
+ }
2610
+ if (!(typeof previous.fileCount === "number" && previous.fileCount > 1))
2611
+ return null;
2612
+ }
2218
2613
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
2219
2614
  // Same pacing and retry contract as the HTML bundle path: this loop hits the
2220
2615
  // same /v1/ fence and previously discarded the whole upload on one 429. The
@@ -2229,6 +2624,7 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2229
2624
  method: "POST",
2230
2625
  body: {
2231
2626
  kind: "live-doc-assets",
2627
+ ...(reuseFrom ? { reuseFrom } : {}),
2232
2628
  manifest,
2233
2629
  declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
2234
2630
  },
@@ -2253,7 +2649,16 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2253
2649
  headers: { "idempotency-key": completeKey },
2254
2650
  });
2255
2651
  }, budget);
2256
- return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
2652
+ return {
2653
+ uploadId: upload.uploadId,
2654
+ manifestHash: upload.manifestHash,
2655
+ warnings,
2656
+ upload: {
2657
+ uploaded: upload.files.length,
2658
+ reused: files.length - upload.files.length,
2659
+ bytesUploaded: upload.files.reduce((n, plan) => n + files.find((file) => file.path === plan.path).byteSize, 0),
2660
+ },
2661
+ };
2257
2662
  }
2258
2663
  async function unpublish(args, deps) {
2259
2664
  const parsed = parseFlags(args);
@@ -2762,14 +3167,40 @@ async function deletionStatus(args, deps) {
2762
3167
  async function status(args, deps) {
2763
3168
  const parsed = parseFlags(args);
2764
3169
  const id = parsed.positionals[0];
2765
- if (!id || parsed.positionals.length !== 1) {
2766
- throw new Error("Usage: foleo status <id> [--json]");
3170
+ if (!id ||
3171
+ parsed.positionals.length > 2 ||
3172
+ (parsed.positionals[1] && parsed.sourcePath)) {
3173
+ throw new Error("Usage: foleo status <id> [<path> | --source <path>] [--json]");
2767
3174
  }
2768
3175
  const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2769
3176
  method: "GET",
2770
3177
  body: undefined,
2771
3178
  });
2772
- writeStatusResult(deps, result, parsed.json);
3179
+ const path = parsed.sourcePath ?? parsed.positionals[1];
3180
+ if (path && isRecord(result)) {
3181
+ const artifact = nestedRecord(result, "artifact") ?? result;
3182
+ const source = nestedRecord(artifact, "source");
3183
+ const remoteDigest = source ? stringField(source, "localDigest") : null;
3184
+ let localDrift = "unknown";
3185
+ if (remoteDigest) {
3186
+ const format = stringField(artifact, "sourceFormat") ??
3187
+ (source ? stringField(source, "sourceFormat") : null);
3188
+ let digest;
3189
+ if (format === "markdown") {
3190
+ const markdown = await deps.readFile(path, "utf8");
3191
+ digest = markdownLocalDigest(markdown, await scanMarkdownAssets(path, markdown, deps));
3192
+ }
3193
+ else if (format === "html") {
3194
+ digest = htmlLocalDigest((await scanBundle(path, deps)).files);
3195
+ }
3196
+ if (digest)
3197
+ localDrift = digest === remoteDigest ? "in_sync" : "local_changed";
3198
+ }
3199
+ writeStatusResult(deps, { ...result, localDrift }, parsed.json);
3200
+ }
3201
+ else {
3202
+ writeStatusResult(deps, result, parsed.json);
3203
+ }
2773
3204
  return 0;
2774
3205
  }
2775
3206
  async function list(args, deps) {
@@ -2874,6 +3305,213 @@ function environmentCommand(args, deps) {
2874
3305
  deps.stdout(`Environment: ${info.name}\nAPI: ${info.apiBase}\n`);
2875
3306
  return 0;
2876
3307
  }
3308
+ /** Download one revision completely before writing any destination files. */
3309
+ async function exportArtifact(args, deps) {
3310
+ const force = args.includes("--force");
3311
+ const parsed = parseFlags(args.filter((arg) => arg !== "--force"));
3312
+ if (parsed.positionals.length !== 2)
3313
+ throw new UsageError("Usage: foleo export <id> <dir> [--force] [--json]");
3314
+ const [id, directory] = parsed.positionals;
3315
+ const root = resolve(directory);
3316
+ const inspect = async (path) => {
3317
+ try {
3318
+ return await lstat(path);
3319
+ }
3320
+ catch (error) {
3321
+ if (isRecord(error) && error.code === "ENOENT")
3322
+ return null;
3323
+ throw error;
3324
+ }
3325
+ };
3326
+ const existing = await inspect(root);
3327
+ if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
3328
+ throw new LocalError("export_unsafe_path", "Export destination must be a directory, not a symlink.");
3329
+ if (existing && !force && (await readdir(root)).length)
3330
+ throw new LocalError("export_directory_not_empty", "Export destination is not empty. Use --force to overwrite matching files.");
3331
+ const discover = () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/source/content?manifest=1`, {
3332
+ method: "GET",
3333
+ body: undefined,
3334
+ });
3335
+ const source = await discover();
3336
+ const origin = new URL(apiBase(deps)).origin;
3337
+ // Source URLs are signed capabilities. Never forward the API bearer token.
3338
+ const download = async (url) => {
3339
+ const target = new URL(url);
3340
+ if (target.origin !== origin || target.pathname !== "/v1/source-downloads")
3341
+ throw new LocalError("export_invalid_manifest", "Invalid source download URL.");
3342
+ const response = await deps.fetch(target.href, { redirect: "error" });
3343
+ if (!response.ok)
3344
+ throw apiResponseError(response.status, await response.json().catch(() => null));
3345
+ return response;
3346
+ };
3347
+ const loadManifest = async (current) => {
3348
+ if (current.delivery.kind !== "manifest_url" ||
3349
+ !current.delivery.url ||
3350
+ !Number.isSafeInteger(current.fileCount) ||
3351
+ current.fileCount < 1 ||
3352
+ current.fileCount > 1000)
3353
+ throw new LocalError("export_invalid_manifest", "Invalid source manifest.");
3354
+ const files = [];
3355
+ const seen = new Set();
3356
+ let next = current.delivery.url;
3357
+ for (let page = 0; next && page < 10; page++) {
3358
+ const manifest = (await (await download(next)).json());
3359
+ if (manifest.id !== id ||
3360
+ manifest.sourceRevisionId !== current.sourceRevisionId ||
3361
+ manifest.fileCount !== current.fileCount ||
3362
+ !Array.isArray(manifest.files))
3363
+ throw new LocalError("export_invalid_manifest", "Source manifest changed during export.");
3364
+ for (const file of manifest.files) {
3365
+ if (typeof file.path !== "string" ||
3366
+ !file.path.startsWith("/") ||
3367
+ file.path.includes("\\") ||
3368
+ [...file.path].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127) ||
3369
+ file.path
3370
+ .slice(1)
3371
+ .split("/")
3372
+ .some((part) => !part || part === "." || part === "..") ||
3373
+ seen.has(file.path) ||
3374
+ !/^[a-f0-9]{64}$/.test(file.sha256) ||
3375
+ !Number.isSafeInteger(file.byteSize) ||
3376
+ file.byteSize < 0 ||
3377
+ file.byteSize > HTML_BUNDLE_MAX_FILE_BYTES ||
3378
+ typeof file.url !== "string")
3379
+ throw new LocalError("export_invalid_manifest", "Unsafe or invalid source file entry.");
3380
+ seen.add(file.path);
3381
+ files.push(file);
3382
+ }
3383
+ if (files.length > current.fileCount)
3384
+ throw new LocalError("export_invalid_manifest", "Source manifest has too many files.");
3385
+ next = manifest.nextUrl;
3386
+ }
3387
+ if (next ||
3388
+ files.length !== current.fileCount ||
3389
+ files.reduce((sum, file) => sum + file.byteSize, 0) >
3390
+ HTML_BUNDLE_MAX_BYTES)
3391
+ throw new LocalError("export_invalid_manifest", "Source manifest is incomplete or exceeds export limits.");
3392
+ return files;
3393
+ };
3394
+ const loadFreshManifest = async (initial) => {
3395
+ let current = initial;
3396
+ for (let refresh = 0;; refresh++) {
3397
+ if (current.sourceFormat !== source.sourceFormat ||
3398
+ current.sourceRevisionId !== source.sourceRevisionId ||
3399
+ current.contentHash !== source.contentHash ||
3400
+ current.fileCount !== source.fileCount)
3401
+ throw new LocalError("export_revision_changed", "Source changed while renewing download URLs. Restart export.");
3402
+ try {
3403
+ return await loadManifest(current);
3404
+ }
3405
+ catch (error) {
3406
+ if (!(error instanceof FoleoError) ||
3407
+ error.httpStatus !== 410 ||
3408
+ error.code !== "source_url_expired" ||
3409
+ refresh >= 3)
3410
+ throw error;
3411
+ current = await discover();
3412
+ }
3413
+ }
3414
+ };
3415
+ let files = await loadFreshManifest(source);
3416
+ const identity = (entries) => JSON.stringify(entries
3417
+ .map(({ path, sha256, byteSize, mediaType }) => ({
3418
+ path,
3419
+ sha256,
3420
+ byteSize,
3421
+ mediaType,
3422
+ }))
3423
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)));
3424
+ const originalIdentity = identity(files);
3425
+ const staging = await mkdtemp(join(tmpdir(), "foleo-export-"));
3426
+ try {
3427
+ for (let index = 0; index < files.length; index++) {
3428
+ let file = files[index];
3429
+ let response;
3430
+ // Refresh only the pending file's capabilities; verified staging files
3431
+ // survive refresh. Bound repeated expiry so a broken clock cannot loop.
3432
+ for (let refresh = 0;; refresh++) {
3433
+ try {
3434
+ response = await download(file.url);
3435
+ break;
3436
+ }
3437
+ catch (error) {
3438
+ if (!(error instanceof FoleoError) ||
3439
+ error.httpStatus !== 410 ||
3440
+ error.code !== "source_url_expired" ||
3441
+ refresh >= 3)
3442
+ throw error;
3443
+ const current = await discover();
3444
+ const renewed = await loadFreshManifest(current);
3445
+ if (current.sourceFormat !== source.sourceFormat ||
3446
+ current.sourceRevisionId !== source.sourceRevisionId ||
3447
+ current.contentHash !== source.contentHash ||
3448
+ identity(renewed) !== originalIdentity)
3449
+ throw new LocalError("export_revision_changed", "Source changed while renewing download URLs. Restart export.");
3450
+ const byPath = new Map(renewed.map((entry) => [entry.path, entry]));
3451
+ files = files.map((entry) => byPath.get(entry.path));
3452
+ file = files[index];
3453
+ }
3454
+ }
3455
+ const bytes = new Uint8Array(await response.arrayBuffer());
3456
+ if (bytes.byteLength !== file.byteSize ||
3457
+ createHash("sha256").update(bytes).digest("hex") !== file.sha256)
3458
+ throw new LocalError("export_hash_mismatch", `Source integrity check failed for ${file.path}.`);
3459
+ await writeFile(join(staging, String(index)), bytes);
3460
+ }
3461
+ await mkdir(root, { recursive: true });
3462
+ // Check each component: --force permits replacing regular files only.
3463
+ for (const file of files) {
3464
+ const parts = file.path.slice(1).split("/");
3465
+ let parent = root;
3466
+ for (const part of parts.slice(0, -1)) {
3467
+ parent = join(parent, part);
3468
+ try {
3469
+ await mkdir(parent);
3470
+ }
3471
+ catch (error) {
3472
+ if (!isRecord(error) || error.code !== "EEXIST")
3473
+ throw error;
3474
+ }
3475
+ const entry = await lstat(parent);
3476
+ if (entry.isSymbolicLink() || !entry.isDirectory())
3477
+ throw new LocalError("export_unsafe_path", "Export path contains a symlink or non-directory.");
3478
+ }
3479
+ const entry = await inspect(join(root, ...parts));
3480
+ if (entry &&
3481
+ (!force || !entry.isFile() || entry.isSymbolicLink() || entry.nlink > 1))
3482
+ throw new LocalError("export_unsafe_path", `Refusing to overwrite ${file.path}.`);
3483
+ }
3484
+ for (const [index, file] of files.entries()) {
3485
+ const handle = await open(join(root, file.path.slice(1)), constants.O_WRONLY |
3486
+ constants.O_CREAT |
3487
+ constants.O_NOFOLLOW |
3488
+ (force ? constants.O_TRUNC : constants.O_EXCL), 0o600);
3489
+ try {
3490
+ await handle.writeFile(await readFile(join(staging, String(index))));
3491
+ }
3492
+ finally {
3493
+ await handle.close();
3494
+ }
3495
+ }
3496
+ }
3497
+ finally {
3498
+ await rm(staging, { recursive: true, force: true });
3499
+ }
3500
+ const summary = {
3501
+ id,
3502
+ directory: root,
3503
+ sourceFormat: source.sourceFormat,
3504
+ sourceRevisionId: source.sourceRevisionId,
3505
+ fileCount: files.length,
3506
+ byteSize: files.reduce((sum, file) => sum + file.byteSize, 0),
3507
+ verified: true,
3508
+ exportNote: source.exportNote,
3509
+ };
3510
+ deps.stdout(parsed.json
3511
+ ? `${JSON.stringify(summary, null, 2)}\n`
3512
+ : `Exported ${files.length} files (${summary.byteSize} bytes) to ${root}; SHA-256 verified.\n${source.exportNote ?? ""}\n`);
3513
+ return 0;
3514
+ }
2877
3515
  async function requestJson(deps, path, init) {
2878
3516
  const credential = await resolveCredentialWithSource(deps);
2879
3517
  if (!credential)
@@ -2890,12 +3528,58 @@ async function requestJsonWithToken(deps, path, token, init) {
2890
3528
  "content-type": "application/json",
2891
3529
  ...init.headers,
2892
3530
  };
2893
- const response = await deps.fetch(`${apiBase(deps)}${path}`, {
2894
- method: init.method,
2895
- headers,
2896
- ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
2897
- });
2898
- const body = await response.json().catch(() => null);
3531
+ uploadRuns.get(deps)?.controller.signal.throwIfAborted();
3532
+ if (uploadRuns.has(deps) &&
3533
+ /^\/(?:artifacts|docs)(?:\/|$)/u.test(path) &&
3534
+ init.method !== "GET")
3535
+ uploadRuns.get(deps).submitted = true;
3536
+ const frozenBody = init.body === undefined ? undefined : JSON.stringify(init.body);
3537
+ const key = init.headers?.["idempotency-key"];
3538
+ const receiptWrite = key &&
3539
+ (init.method === "POST" || init.method === "PUT") &&
3540
+ /^\/(?:artifacts(?:\/html)?|docs)(?:\/[^/]+)?$/u.test(path);
3541
+ let response;
3542
+ let body;
3543
+ for (let retry = 0;; retry++) {
3544
+ try {
3545
+ response = await deps.fetch(`${apiBase(deps)}${path}`, {
3546
+ method: init.method,
3547
+ ...(uploadRuns.has(deps)
3548
+ ? { signal: uploadRuns.get(deps).controller.signal }
3549
+ : {}),
3550
+ headers,
3551
+ ...(frozenBody === undefined ? {} : { body: frozenBody }),
3552
+ });
3553
+ if (!receiptWrite ||
3554
+ (response.status !== 502 && response.status !== 504)) {
3555
+ if (response.ok && receiptWrite)
3556
+ body = await response.json();
3557
+ else
3558
+ body = await response.json().catch(() => null);
3559
+ break;
3560
+ }
3561
+ await response.body?.cancel();
3562
+ }
3563
+ catch (error) {
3564
+ // fetch throws TypeError for network loss; Node also exposes reset/socket
3565
+ // codes. Local validation/auth failures never enter this transport loop.
3566
+ if (!receiptWrite ||
3567
+ uploadRuns.get(deps)?.controller.signal.aborted ||
3568
+ !(error instanceof TypeError ||
3569
+ (isRecord(error) &&
3570
+ ["ECONNRESET", "ETIMEDOUT", "EPIPE", "UND_ERR_SOCKET"].includes(String(error.code)))))
3571
+ throw error;
3572
+ }
3573
+ if (retry >= 3)
3574
+ throw new LocalError("write_result_unknown", "The write may have succeeded, but its response could not be recovered.", {
3575
+ retryable: true,
3576
+ context: { idempotencyKey: key, method: init.method, path },
3577
+ next: `Replay the original ${init.method} ${path} JSON body and precondition with Idempotency-Key: ${key}. Do not start a new publish; the accepted receipt returns the original result.`,
3578
+ });
3579
+ deps.stderr(`Response lost; replaying the same write (attempt ${retry + 2}).\n`);
3580
+ await (deps.sleep ??
3581
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(Math.min(4000, 500 * 2 ** retry));
3582
+ }
2899
3583
  if (RETRYABLE_STATUSES.has(response.status)) {
2900
3584
  // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
2901
3585
  // zone fence in front of this API answers with a Cloudflare error page rather
@@ -2906,6 +3590,11 @@ async function requestJsonWithToken(deps, path, token, init) {
2906
3590
  if (!response.ok) {
2907
3591
  throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
2908
3592
  }
3593
+ if (path === "/uploads" &&
3594
+ isRecord(body) &&
3595
+ typeof body.uploadId === "string") {
3596
+ uploadRun(deps).sessions.add(body.uploadId);
3597
+ }
2909
3598
  return body;
2910
3599
  }
2911
3600
  class ApiRequestError extends FoleoError {
@@ -2923,19 +3612,43 @@ class ApiRequestError extends FoleoError {
2923
3612
  : null;
2924
3613
  super({
2925
3614
  code,
2926
- message: code === "matching_source_exists"
2927
- ? matchingSourceExistsMessage(body)
2928
- : code === "acknowledgement_required" &&
2929
- envelope?.field !== "acknowledgeLinkBreakage"
2930
- ? "Foleo API error: acknowledgement_required. This change would expose the artifact to more readers or add a working address. Only after the human approves it, re-run the same command with --acknowledge-access-widening."
2931
- : code === "contained_profile_unavailable"
2932
- ? containedProfileUnavailableMessage(references ?? [])
2933
- : `Foleo API error: ${code}`,
3615
+ message: code === "bundle_new_files_limit" &&
3616
+ typeof envelope?.message === "string"
3617
+ ? envelope.message
3618
+ : code === "matching_source_exists"
3619
+ ? matchingSourceExistsMessage(body)
3620
+ : code === "acknowledgement_required" &&
3621
+ envelope?.field !== "acknowledgeLinkBreakage"
3622
+ ? "Foleo API error: acknowledgement_required. This change would expose the artifact to more readers or add a working address. Only after the human approves it, re-run the same command with --acknowledge-access-widening."
3623
+ : code === "contained_profile_unavailable"
3624
+ ? containedProfileUnavailableMessage(references ?? [])
3625
+ : `Foleo API error: ${code}`,
2934
3626
  httpStatus: status,
2935
3627
  source: "api",
2936
3628
  retryable,
2937
3629
  ...(next === null ? {} : { next }),
2938
- ...(references === null ? {} : { context: { references } }),
3630
+ ...(["approval_required", "input_required"].includes(code) && envelope
3631
+ ? {
3632
+ next: `Open ${String(envelope.reviewUrl ?? "Foleo")} to review, then use foleo approval commit ${String(envelope.approvalId ?? "<id>")} --idempotency-key <key>.`,
3633
+ context: Object.fromEntries([
3634
+ "approvalId",
3635
+ "reviewUrl",
3636
+ "approvalReason",
3637
+ "targetType",
3638
+ "audiences",
3639
+ ]
3640
+ .filter((key) => envelope[key] !== undefined)
3641
+ .map((key) => [key, envelope[key]])),
3642
+ }
3643
+ : code === "bundle_new_files_limit" && envelope
3644
+ ? {
3645
+ context: Object.fromEntries(["limit", "count", "newFiles", "copiedFiles", "sharedObjects"]
3646
+ .filter((field) => envelope[field] !== undefined)
3647
+ .map((field) => [field, envelope[field]])),
3648
+ }
3649
+ : references === null
3650
+ ? {}
3651
+ : { context: { references } }),
2939
3652
  });
2940
3653
  this.name = "ApiRequestError";
2941
3654
  this.status = status;
@@ -3019,8 +3732,12 @@ allowReplay = false) {
3019
3732
  next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
3020
3733
  });
3021
3734
  const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
3735
+ uploadRuns.get(deps)?.controller.signal.throwIfAborted();
3022
3736
  const response = await deps.fetch(`${apiBase(deps)}${path}`, {
3023
3737
  method: "PUT",
3738
+ ...(uploadRuns.has(deps)
3739
+ ? { signal: uploadRuns.get(deps).controller.signal }
3740
+ : {}),
3024
3741
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
3025
3742
  body: bytes,
3026
3743
  });
@@ -3257,6 +3974,26 @@ function loopbackSuccessBody() {
3257
3974
  function sha256Utf8(value) {
3258
3975
  return createHash("sha256").update(value, "utf8").digest("hex");
3259
3976
  }
3977
+ /** SHA-256 of UTF-8 JSON ["html-v1", sorted [path, sha256, byteSize] triples].
3978
+ * Paths are the upload scanner's root-relative POSIX paths, with leading slash.
3979
+ * Capture this before optimization: the uploaded manifest has different bytes.
3980
+ */
3981
+ export function htmlLocalDigest(files) {
3982
+ const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3983
+ return sha256Utf8(JSON.stringify([
3984
+ "html-v1",
3985
+ sorted.map(({ path, sha256, byteSize }) => [path, sha256, byteSize]),
3986
+ ]));
3987
+ }
3988
+ /** Must match the server's markdownLocalDigest, including preserved images. */
3989
+ export function markdownLocalDigest(markdown, images) {
3990
+ const sorted = [...images].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3991
+ return sha256Utf8(JSON.stringify([
3992
+ "markdown-v1",
3993
+ markdown,
3994
+ sorted.map(({ path, sha256 }) => [path, sha256]),
3995
+ ]));
3996
+ }
3260
3997
  function publishSourcePayload(contentHash, sourceId) {
3261
3998
  return {
3262
3999
  provider: "local",
@@ -3365,6 +4102,8 @@ function writeResult(deps, result, json) {
3365
4102
  }
3366
4103
  if (result !== null && typeof result === "object" && "url" in result) {
3367
4104
  deps.stdout(`${String(result.url)}\n`);
4105
+ if ("unchanged" in result && result.unchanged === true)
4106
+ deps.stderr("Unchanged; the existing published version is current.\n");
3368
4107
  // The applied HTML runtime profile is chosen by the server; say which one
3369
4108
  // a human got. stderr, so stdout stays the bare URL it always was.
3370
4109
  const profile = stringField(result, "runtimeProfile");
@@ -3376,6 +4115,34 @@ function writeResult(deps, result, json) {
3376
4115
  }
3377
4116
  deps.stdout(`${JSON.stringify(result)}\n`);
3378
4117
  }
4118
+ /** Render the server's visibility descriptor; never infer capabilities from the id. */
4119
+ function writeSettingsResult(deps, result, json) {
4120
+ if (json || !isRecord(result) || !Array.isArray(result.visibilityOptions)) {
4121
+ writeResult(deps, result, json);
4122
+ return;
4123
+ }
4124
+ const settings = nestedRecord(result, "settings") ?? {};
4125
+ const options = result.visibilityOptions.filter(isRecord);
4126
+ const selected = options.find((option) => option.value === settings.visibility);
4127
+ const lines = [
4128
+ `Visibility: ${stringField(selected, "label") ?? settings.visibility ?? "-"}`,
4129
+ ];
4130
+ for (const option of options) {
4131
+ const disabled = option.available === false;
4132
+ lines.push(` ${String(option.label)} (${String(option.value)})${disabled ? " [disabled]" : ""}: ${String(option.audience)}`);
4133
+ if (disabled && typeof option.reason === "string")
4134
+ lines.push(` ${option.reason}`);
4135
+ if (option.widening === true)
4136
+ lines.push(" Access widening; existing connection policy or API-key acknowledgement rules apply.");
4137
+ }
4138
+ for (const [key, value] of Object.entries(settings)) {
4139
+ if (key !== "visibility")
4140
+ lines.push(`${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
4141
+ }
4142
+ if (typeof result.stateRevision === "number")
4143
+ lines.push(`State revision: ${result.stateRevision}`);
4144
+ deps.stdout(`${lines.join("\n")}\n`);
4145
+ }
3379
4146
  function writeStatusResult(deps, result, json) {
3380
4147
  if (json) {
3381
4148
  writeResult(deps, result, true);
@@ -3396,6 +4163,9 @@ function writeStatusResult(deps, result, json) {
3396
4163
  lines.push(`Version: ${statusRecord.version}`);
3397
4164
  if (typeof statusRecord.stateRevision === "number")
3398
4165
  lines.push(`State revision: ${statusRecord.stateRevision}`);
4166
+ const localDrift = stringField(result, "localDrift");
4167
+ if (localDrift)
4168
+ lines.push(`Local drift: ${localDrift}`);
3399
4169
  const revision = stringField(statusRecord, "etag");
3400
4170
  if (revision)
3401
4171
  lines.push(`Revision: ${revision}`);
@@ -3436,6 +4206,7 @@ function writeDeletionResult(deps, result, json) {
3436
4206
  }
3437
4207
  function parseFlags(args, options = {}) {
3438
4208
  const positionals = [];
4209
+ let sourcePath;
3439
4210
  let json = false;
3440
4211
  let title;
3441
4212
  let version;
@@ -3453,8 +4224,11 @@ function parseFlags(args, options = {}) {
3453
4224
  let publishSeparately = false;
3454
4225
  let allowDelete = false;
3455
4226
  let allowPurge = false;
4227
+ let allowWorkspaces = false;
4228
+ let allowWorkspaceSharing = false;
3456
4229
  let name;
3457
4230
  let dryRun = false;
4231
+ let optimizeImages;
3458
4232
  let previous;
3459
4233
  let acknowledgeLinkBreakage = false;
3460
4234
  let acknowledgeAccessWidening = false;
@@ -3479,6 +4253,14 @@ function parseFlags(args, options = {}) {
3479
4253
  throw new UsageError("--name requires a value", "name_missing");
3480
4254
  continue;
3481
4255
  }
4256
+ if (arg === "--optimize-images") {
4257
+ optimizeImages = true;
4258
+ continue;
4259
+ }
4260
+ if (arg === "--no-optimize-images") {
4261
+ optimizeImages = false;
4262
+ continue;
4263
+ }
3482
4264
  if (arg === "--dry-run") {
3483
4265
  dryRun = true;
3484
4266
  continue;
@@ -3510,6 +4292,12 @@ function parseFlags(args, options = {}) {
3510
4292
  throw new Error("--kind requires a value");
3511
4293
  continue;
3512
4294
  }
4295
+ if (arg === "--source") {
4296
+ sourcePath = args[++i];
4297
+ if (!sourcePath)
4298
+ throw new Error("--source requires a path");
4299
+ continue;
4300
+ }
3513
4301
  if (arg === "--format") {
3514
4302
  format = args[++i];
3515
4303
  if (!format)
@@ -3600,6 +4388,15 @@ function parseFlags(args, options = {}) {
3600
4388
  allowDelete = true;
3601
4389
  continue;
3602
4390
  }
4391
+ if (arg === "--allow-workspaces" || arg === "--allow-workspace-sharing") {
4392
+ if (!options.allowLoginScopeFlags)
4393
+ throw new UsageError(`${arg} is valid only with login`);
4394
+ if (arg === "--allow-workspaces")
4395
+ allowWorkspaces = true;
4396
+ else
4397
+ allowWorkspaceSharing = true;
4398
+ continue;
4399
+ }
3603
4400
  if (arg === "--allow-purge") {
3604
4401
  if (!options.allowLoginScopeFlags)
3605
4402
  throw new Error("--allow-purge is valid only with login");
@@ -3611,6 +4408,7 @@ function parseFlags(args, options = {}) {
3611
4408
  positionals.push(arg);
3612
4409
  }
3613
4410
  return {
4411
+ ...(sourcePath ? { sourcePath } : {}),
3614
4412
  positionals,
3615
4413
  json,
3616
4414
  ...(title !== undefined ? { title } : {}),
@@ -3629,8 +4427,11 @@ function parseFlags(args, options = {}) {
3629
4427
  publishSeparately,
3630
4428
  allowDelete,
3631
4429
  allowPurge,
4430
+ allowWorkspaces,
4431
+ allowWorkspaceSharing,
3632
4432
  ...(name === undefined ? {} : { name }),
3633
4433
  dryRun,
4434
+ optimizeImages,
3634
4435
  ...(previous === undefined ? {} : { previous }),
3635
4436
  acknowledgeLinkBreakage,
3636
4437
  acknowledgeAccessWidening,
@@ -3653,8 +4454,10 @@ function help() {
3653
4454
  return [
3654
4455
  "Usage:",
3655
4456
  " foleo --help",
3656
- " foleo login [--allow-purge] [--json]",
4457
+ " foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
3657
4458
  " foleo logout [--no-revoke] [--json]",
4459
+ " Workspace login flags are staging/local only; browser consent starts unchecked.",
4460
+ " --allow-workspaces requests read + write; --allow-workspace-sharing requests share + read.",
3658
4461
  " foleo whoami [--json]",
3659
4462
  " foleo doctor [--json]",
3660
4463
  " foleo skill get|path",
@@ -3662,16 +4465,20 @@ function help() {
3662
4465
  " foleo environment [--json]",
3663
4466
  " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
3664
4467
  " foleo get <id> [--json]",
4468
+ " foleo export <id> <dir> [--force] [--json] (source and assets; SHA-256 verified)",
3665
4469
  " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--acknowledge-access-widening] [--json]",
3666
- " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--dry-run] [--json]",
3667
- " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json]",
4470
+ " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--dry-run] [--json]",
4471
+ " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]",
3668
4472
  " foleo update <id> <file.md> --version <version> [--acknowledge-access-widening] [--json] (compatibility)",
4473
+ " Identical updates may return unchanged: true; revision/ETag stay unchanged. Retry an interrupted request with the same idempotency key.",
4474
+ " Shared storage can reuse files from retained versions of the same artifact; legacy storage reuses only its live version.",
3669
4475
  " foleo name-check <label> [--json]",
3670
4476
  " foleo names [--artifact <id>] [--limit <n>] [--cursor <cursor>] [--json]",
3671
4477
  " foleo name attach <id> <label> [--revision <etag>] [--acknowledge-access-widening] [--dry-run] [--json]",
3672
4478
  " foleo name set <id> <label> --previous keep-as-alias|release [--revision <etag>] [--acknowledge-access-widening] [--dry-run] [--json]",
3673
4479
  " foleo name release <id> <label> --acknowledge-link-breakage [--revision <etag>] [--dry-run] [--json]",
3674
- " foleo status <id> [--json]",
4480
+ " foleo status <id> [<path>] [--json]",
4481
+ " foleo get <id> [--source <path>] [--json]",
3675
4482
  " foleo settings <id> [--json]",
3676
4483
  " foleo settings <id> --set k=v [--set k=v ...] [--password-stdin] --revision <etag> [--acknowledge-access-widening] [--json]",
3677
4484
  " foleo limits [--json]",
@@ -3701,6 +4508,12 @@ function help() {
3701
4508
  " The chosen name is the artifact's only address; there is no generated",
3702
4509
  " fallback, and the old generated a-<id> hosts no longer serve.",
3703
4510
  "",
4511
+ " HTML bundles: 300 new files per publish/update, 1,000 total with server reuse.",
4512
+ " Legacy storage copies every file and permits 300 total. See `foleo limits`.",
4513
+ " HTML bundle folders get responsive AVIF copies by default; --no-optimize-images opts out.",
4514
+ " Optimization runs locally; create dry-runs still probe name and access.",
4515
+ " HTML update dry-runs are local bundle plans without network.",
4516
+ " --optimize-images explicitly requires the macOS encoder (fails if unavailable).",
3704
4517
  " --dry-run plans an HTML publish without uploading, creating, or spending",
3705
4518
  " quota. It reports the resolved name and availability, url, title with its",
3706
4519
  " resolvedFrom source, visibility, routes, largestFiles and skipped[], the",
@@ -3729,12 +4542,29 @@ function help() {
3729
4542
  " name-check <label> is free and checks availability without publishing.",
3730
4543
  "",
3731
4544
  "Access control:",
4545
+ " Visibility labels: Private (private), Link (unlisted), Link + password",
4546
+ " (password), Public (public). Private: Only you and your organization.",
4547
+ " settings <id> lists all options; unavailable options are disabled with",
4548
+ " their reason. --json includes visibilityOptions and its widening flags.",
4549
+ " HTML Public is gated by the Public Suffix List (public_publish_gated).",
3732
4550
  " A Markdown document is unlisted (anyone with the link) or private (signed-in",
3733
4551
  " members of your Foleo organization, at the same URL): settings <id> --set",
3734
4552
  " visibility=private|unlisted --revision <etag>. Private to unlisted lets more",
3735
4553
  " people read it, so it needs --acknowledge-access-widening with an API key.",
3736
4554
  " Password and public are refused for Markdown; passwords are HTML-only.",
3737
4555
  "",
4556
+ "Foleo bar (HTML only):",
4557
+ " An unlisted HTML page opens with a thin Foleo bar above it: the page runs in",
4558
+ " a frame below it, at the same URL. settings <id> --set foleoBarDisplay=shown|hidden",
4559
+ " --revision <etag> sets it, and foleoBarDisplay=null resets it to shown. It is",
4560
+ " presentation, not access, so it never needs --acknowledge-access-widening.",
4561
+ " Hiding it needs the publish.badge.remove entitlement, which only Foleo staff",
4562
+ " hold during beta: without it the call fails with entitlement_required (HTTP",
4563
+ " 403, retryable false) and changes nothing, so do not retry with hidden. A",
4564
+ " page under review or restricted keeps the bar shown (foleo_bar_hold).",
4565
+ " Markdown pages carry Foleo's own navigation and refuse the field",
4566
+ " (not_implemented). `get <id> --json` reports presentation (shell or direct).",
4567
+ "",
3738
4568
  "Access widening (an explicit human decision, never a blanket consent):",
3739
4569
  " --acknowledge-access-widening tells the API that the human approved THIS",
3740
4570
  " change exposing an existing artifact to more readers (private or password",