@foleo/cli 0.1.36 → 0.1.48

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;
@@ -102,6 +107,87 @@ const LIVE_DOC_ASSET_MEDIA_TYPES = {
102
107
  ".webp": "image/webp",
103
108
  ".avif": "image/avif",
104
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
+ }
105
191
  export async function runCli(argv, deps = {
106
192
  fetch,
107
193
  readFile,
@@ -110,17 +196,26 @@ export async function runCli(argv, deps = {
110
196
  stderr: (message) => process.stderr.write(message),
111
197
  }) {
112
198
  const wantsJson = argv.includes("--json");
199
+ let activeDeps = deps;
113
200
  try {
114
201
  const global = parseGlobalFlags(argv);
115
202
  const commandDeps = global.environment
116
203
  ? { ...deps, env: { ...deps.env, FOLEO_ENV: global.environment } }
117
204
  : deps;
205
+ activeDeps = commandDeps;
206
+ jsonOutputs.set(commandDeps, wantsJson);
118
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
+ }
119
212
  if (command === undefined ||
120
213
  command === "help" ||
121
214
  command === "--help" ||
122
- command === "-h") {
123
- commandDeps.stdout(help());
215
+ command === "-h" ||
216
+ (command === "settings" &&
217
+ (rest.includes("--help") || rest.includes("-h")))) {
218
+ commandDeps.stdout(help() + "\n" + WORKSPACE_HELP);
124
219
  return 0;
125
220
  }
126
221
  if (command === "--version" || command === "-v" || command === "version") {
@@ -148,6 +243,35 @@ export async function runCli(argv, deps = {
148
243
  operation: describeArgvToken(command),
149
244
  });
150
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
+ }
151
275
  if (command === "publish")
152
276
  return await publish(rest, commandDeps);
153
277
  if (command === "update")
@@ -170,6 +294,8 @@ export async function runCli(argv, deps = {
170
294
  return await status(rest, commandDeps);
171
295
  if (command === "get")
172
296
  return await status(rest, commandDeps);
297
+ if (command === "export")
298
+ return await exportArtifact(rest, commandDeps);
173
299
  if (command === "html-publish") {
174
300
  warnDeprecatedAlias(commandDeps, "html-publish", "publish <path> --accept-hosting-risk");
175
301
  return await htmlPublish(rest, commandDeps);
@@ -224,6 +350,15 @@ export async function runCli(argv, deps = {
224
350
  return 2;
225
351
  }
226
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
+ }
227
362
  const rendered = renderFailure(normalizeThrown(error), wantsJson);
228
363
  if (rendered.stdout !== null)
229
364
  deps.stdout(rendered.stdout);
@@ -231,6 +366,10 @@ export async function runCli(argv, deps = {
231
366
  deps.stderr(rendered.stderr);
232
367
  return rendered.exitCode;
233
368
  }
369
+ finally {
370
+ uploadRuns.get(activeDeps)?.dispose();
371
+ jsonOutputs.delete(activeDeps);
372
+ }
234
373
  }
235
374
  /**
236
375
  * Usage-shaped failures exit 2 even when they were thrown as a plain `Error`.
@@ -612,8 +751,27 @@ function stringArray(value) {
612
751
  async function login(args, deps) {
613
752
  const parsed = parseFlags(args, { allowLoginScopeFlags: true });
614
753
  if (parsed.positionals.length > 0)
615
- throw new Error("Usage: foleo login [--allow-purge] [--json]");
754
+ throw new Error("Usage: foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]");
616
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
+ !(
766
+ // Spec 114 G0: production is allowed; the server's allowlist decides
767
+ // who is actually offered workspace permissions.
768
+ (target.origin === "https://api.foleo.app" ||
769
+ target.origin === "https://api-staging.foleo.app" ||
770
+ (target.protocol === "http:" &&
771
+ ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname)))))
772
+ throw new LocalError("workspace_login_unavailable", "Workspace login flags are available only against Foleo's own API.", {
773
+ next: "Sign in against production or --staging with --allow-workspaces (add --allow-workspace-sharing for sharing).",
774
+ });
617
775
  announceApi(deps, parsed.json);
618
776
  const verifyStore = deps.verifyCredentialStore ?? verifyKeychainWritable;
619
777
  const saveCredential = deps.saveCredential ?? saveKeychainCredential;
@@ -631,7 +789,12 @@ async function login(args, deps) {
631
789
  let loginResult = null;
632
790
  let operationError = null;
633
791
  try {
634
- const start = await requestPublicJson(deps, "/desktop/handoff/start", { nonce, callbackUrl: callback.callbackUrl, clientKind: "cli" });
792
+ const start = await requestPublicJson(deps, "/desktop/handoff/start", {
793
+ nonce,
794
+ callbackUrl: callback.callbackUrl,
795
+ clientKind: "cli",
796
+ ...(workspaceScopes.length ? { workspaceScopes } : {}),
797
+ });
635
798
  deps.stderr("Opening Foleo sign-in in your browser...\n");
636
799
  try {
637
800
  await openUrl(start.authorizeUrl);
@@ -656,6 +819,7 @@ async function login(args, deps) {
656
819
  scopes: [
657
820
  ...CLI_KEY_SCOPES,
658
821
  ...(parsed.allowPurge ? ["artifacts:purge"] : []),
822
+ ...workspaceScopes.filter((scope) => exchanged.approvedWorkspaceScopes?.includes(scope)),
659
823
  ],
660
824
  deferredActivation: true,
661
825
  },
@@ -885,7 +1049,8 @@ function refuseUnavailableName(label, availability, next) {
885
1049
  /** The largest bundle files by size, so a dry run can flag a heavy upload before it starts. */
886
1050
  const DRY_RUN_LARGEST_FILES_SHOWN = 5;
887
1051
  async function htmlPublishDryRun(root, name, parsed, deps) {
888
- const { files, skipped, routes } = await scanBundle(root, deps);
1052
+ const { files, skipped, routes, warnings, imageOptimization } = await prepareImageBundle(root, deps, parsed);
1053
+ assertFirstPublishFileBudget(files.length);
889
1054
  const htmlFiles = files.filter((file) => file.mediaType === "text/html; charset=utf-8");
890
1055
  const entryFile = files.find((file) => file.path === "/index.html");
891
1056
  const entryHtml = entryFile
@@ -968,6 +1133,8 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
968
1133
  const previewUrl = artifactPreviewUrl(derived, deps);
969
1134
  const plan = {
970
1135
  ok: true,
1136
+ warnings,
1137
+ ...(imageOptimization ? { imageOptimization } : {}),
971
1138
  plan: {
972
1139
  action: "create",
973
1140
  scope: cost === null ? "bundle-only" : "full",
@@ -1017,6 +1184,7 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
1017
1184
  totalBytes: files.reduce((n, file) => n + file.byteSize, 0),
1018
1185
  entry: "/index.html",
1019
1186
  routes,
1187
+ files: files.map(({ bytes: _bytes, ...file }) => file),
1020
1188
  notFoundPage: files.some((file) => file.path === "/404.html")
1021
1189
  ? "/404.html"
1022
1190
  : null,
@@ -1099,6 +1267,8 @@ function htmlWireOptions(parsed) {
1099
1267
  ? {}
1100
1268
  : { runtimeProfile: parsed.runtimeProfile }),
1101
1269
  acknowledgeAccessWidening: parsed.acknowledgeAccessWidening,
1270
+ optimizeImages: parsed.optimizeImages,
1271
+ json: parsed.json,
1102
1272
  };
1103
1273
  }
1104
1274
  async function htmlUpdate(args, deps) {
@@ -1191,7 +1361,7 @@ async function settingsCommand(args, deps) {
1191
1361
  }
1192
1362
  announceApi(deps, parsed.json);
1193
1363
  if (Object.keys(patch).length === 0) {
1194
- writeResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1364
+ writeSettingsResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1195
1365
  method: "GET",
1196
1366
  body: undefined,
1197
1367
  }), parsed.json);
@@ -1201,7 +1371,7 @@ async function settingsCommand(args, deps) {
1201
1371
  if (revision === null) {
1202
1372
  throw new Error("Usage: foleo settings <id> --set k=v ... --revision <etag> [--acknowledge-access-widening] [--json]");
1203
1373
  }
1204
- writeResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1374
+ writeSettingsResult(deps, await requestJson(deps, `/artifacts/${encodeURIComponent(id)}/settings`, {
1205
1375
  method: "PATCH",
1206
1376
  body: {
1207
1377
  settings: patch,
@@ -1332,6 +1502,125 @@ async function htmlUnpublish(args, deps) {
1332
1502
  writeResult(deps, result, parsed.json);
1333
1503
  return 0;
1334
1504
  }
1505
+ function withImageReport(result, warnings, imageOptimization) {
1506
+ const record = result !== null && typeof result === "object"
1507
+ ? result
1508
+ : {};
1509
+ return {
1510
+ ...record,
1511
+ ...(warnings.length
1512
+ ? {
1513
+ warnings: [
1514
+ ...(Array.isArray(record.warnings) ? record.warnings : []),
1515
+ ...warnings,
1516
+ ],
1517
+ }
1518
+ : {}),
1519
+ ...(imageOptimization ? { imageOptimization } : {}),
1520
+ };
1521
+ }
1522
+ function reportHeavyImages(deps, warnings, html, json = false) {
1523
+ if (json || !warnings.length)
1524
+ return;
1525
+ for (const w of warnings.slice(0, 10))
1526
+ deps.stderr(`Heavy image: ${w.path} (${w.bytes} bytes${w.width ? `, ${w.width} × ${w.height}` : ""})\n`);
1527
+ if (warnings.length > 10)
1528
+ deps.stderr(`(+${warnings.length - 10} more)\n`);
1529
+ const mb = (warnings.reduce((n, w) => n + w.bytes, 0) / 1_000_000).toFixed(2);
1530
+ 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`);
1531
+ }
1532
+ export async function prepareImageBundle(root, deps, options = {}) {
1533
+ const scanned = await scanBundle(root, deps);
1534
+ const localDigest = htmlLocalDigest(scanned.files);
1535
+ let files = scanned.files;
1536
+ let imageOptimization;
1537
+ const encoderWarnings = [];
1538
+ let optimized;
1539
+ if (options.optimizeImages !== false) {
1540
+ try {
1541
+ optimized = await optimizeImages(files, deps.imageProcessRunner);
1542
+ }
1543
+ catch (error) {
1544
+ if (options.optimizeImages === true ||
1545
+ !(error instanceof LocalError) ||
1546
+ error.code !== "image_encoder_unavailable")
1547
+ throw error;
1548
+ encoderWarnings.push({
1549
+ code: "image_encoder_unavailable",
1550
+ message: error.message,
1551
+ });
1552
+ if (!options.json)
1553
+ deps.stderr(`image_encoder_unavailable: ${error.message} Publishing without image optimization.\n`);
1554
+ }
1555
+ }
1556
+ if (optimized) {
1557
+ imageOptimization = optimized.imageOptimization;
1558
+ const scannedByPath = new Map(scanned.files.map((file) => [file.path, file]));
1559
+ files = optimized.files.map((file) => {
1560
+ const original = scannedByPath.get(file.path);
1561
+ if (original?.bytes === file.bytes)
1562
+ return original;
1563
+ return {
1564
+ path: file.path,
1565
+ bytes: file.bytes,
1566
+ byteSize: file.bytes.byteLength,
1567
+ sha256: createHash("sha256").update(file.bytes).digest("hex"),
1568
+ mediaType: mediaTypeFor(file.path),
1569
+ };
1570
+ });
1571
+ const total = files.reduce((n, f) => n + f.byteSize, 0);
1572
+ const extra = ` --optimize-images added ${imageOptimization.addedFiles} files / ${imageOptimization.addedBytes} bytes: ${imageOptimization.images.flatMap((i) => i.variants.map((v) => v.path)).join(", ")}`;
1573
+ const fail = (code, message) => {
1574
+ throw new LocalError(code, message + extra);
1575
+ };
1576
+ if (files.length > HTML_BUNDLE_MAX_FILES)
1577
+ fail("bundle_too_many_files", "Bundle exceeds the file-count limit.");
1578
+ if (total > HTML_BUNDLE_MAX_BYTES)
1579
+ fail("bundle_total_too_large", "Bundle exceeds the total size limit.");
1580
+ for (const f of files) {
1581
+ if (f.byteSize > HTML_BUNDLE_MAX_FILE_BYTES)
1582
+ fail("bundle_file_too_large", `Bundle file exceeds the per-file limit: ${f.path}`);
1583
+ if (f.mediaType === "text/html; charset=utf-8" &&
1584
+ f.byteSize > HTML_BUNDLE_MAX_HTML_BYTES)
1585
+ fail("bundle_html_too_large", `HTML file exceeds the size limit: ${f.path}`);
1586
+ if (Buffer.byteLength(f.path) > HTML_BUNDLE_MAX_PATH_BYTES ||
1587
+ f.path
1588
+ .split("/")
1589
+ .some((p) => Buffer.byteLength(p) > HTML_BUNDLE_MAX_PATH_SEGMENT_BYTES))
1590
+ fail("bundle_path_invalid", `Invalid bundle path: ${f.path}`);
1591
+ }
1592
+ if (!options.json) {
1593
+ const r = imageOptimization;
1594
+ const before = r.images.reduce((n, i) => n + i.bytes, 0);
1595
+ const after = r.images.reduce((n, i) => n +
1596
+ (i.variants.find((v) => v.width >= 1280) ?? i.variants.at(-1)).bytes, 0);
1597
+ if (r.images.length)
1598
+ 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`);
1599
+ for (const skip of r.skipped.slice(0, 10))
1600
+ deps.stderr(`image_optimize_skipped: ${skip.path} (${skip.reason})\n`);
1601
+ if (r.skipped.length > 10)
1602
+ deps.stderr(`(+${r.skipped.length - 10} more)\n`);
1603
+ }
1604
+ }
1605
+ const warnings = auditImages(files, new Set(imageOptimization?.images.map((i) => i.path)));
1606
+ reportHeavyImages(deps, warnings, true, options.json);
1607
+ return {
1608
+ ...scanned,
1609
+ localDigest,
1610
+ files,
1611
+ warnings: [...encoderWarnings, ...warnings],
1612
+ ...(imageOptimization ? { imageOptimization } : {}),
1613
+ };
1614
+ }
1615
+ function assertFirstPublishFileBudget(count) {
1616
+ if (count > HTML_BUNDLE_MAX_NEW_FILES) {
1617
+ 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.`;
1618
+ throw new LocalError("bundle_new_files_limit", message, {
1619
+ context: { limit: HTML_BUNDLE_MAX_NEW_FILES, count: count },
1620
+ next: "Reduce the bundle. For updates, keep files unchanged so the server can reuse them.",
1621
+ });
1622
+ }
1623
+ }
1335
1624
  async function publishBundle(root, deps, update, hostingRiskAcknowledged = false, publishSeparately = false, settings, wire = {}) {
1336
1625
  // Top-level fields every HTML create/update body carries (spec 103): the
1337
1626
  // runtime profile only when the caller chose one, and the widening
@@ -1342,7 +1631,7 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1342
1631
  : { runtimeProfile: wire.runtimeProfile }),
1343
1632
  ...accessWideningField(wire.acknowledgeAccessWidening === true),
1344
1633
  };
1345
- const { files, skipped } = await scanBundle(root, deps);
1634
+ const { files, skipped, warnings, imageOptimization, localDigest } = await prepareImageBundle(root, deps, wire);
1346
1635
  if (skipped.length > 0) {
1347
1636
  // Spec 089 §K.3 / L914: a dropped `.well-known/` must never be silent on
1348
1637
  // a real run either, not only in a `--dry-run` plan. stderr, unconditionally
@@ -1354,7 +1643,10 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1354
1643
  const rest = skipped.length > 10 ? ` (+${skipped.length - 10} more)` : "";
1355
1644
  deps.stderr(`Skipped ${skipped.length} bundle ${skipped.length === 1 ? "entry" : "entries"} not uploaded: ${shown}${rest}\n`);
1356
1645
  }
1646
+ if (!update)
1647
+ assertFirstPublishFileBudget(files.length);
1357
1648
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
1649
+ const filesByPath = new Map(files.map((file) => [file.path, file]));
1358
1650
  // One pacer for every /v1/ call in this publish: the zone rate-limit fence
1359
1651
  // counts the session create and complete calls against the same budget as the
1360
1652
  // file PUTs, so pacing only the PUTs overspends it.
@@ -1363,101 +1655,129 @@ async function publishBundle(root, deps, update, hostingRiskAcknowledged = false
1363
1655
  // retry is another request against the same fence, so pacing only the first
1364
1656
  // attempt spends the budget it was meant to protect.
1365
1657
  const budget = createRetryBudget();
1366
- const uploadKey = randomUUID();
1367
- const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1368
- await pace();
1369
- return requestJson(deps, "/uploads", {
1370
- method: "POST",
1371
- body: {
1372
- kind: "html-artifact-bundle",
1373
- manifest,
1374
- declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1375
- },
1376
- headers: { "idempotency-key": uploadKey },
1377
- });
1378
- }, budget);
1379
- let uploaded = 0;
1380
- for (const plan of upload.files) {
1381
- const file = files.find((candidate) => candidate.path === plan.path);
1382
- if (!file)
1383
- throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1384
- await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1385
- await pace();
1386
- return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1387
- }, budget);
1388
- uploaded += 1;
1389
- // A large bundle is paced to well under a minute's worth of requests, so a
1390
- // silent multi-minute publish reads as a hang. Progress goes to stderr so
1391
- // `--json` stdout stays machine-parseable.
1392
- if (upload.files.length > 20 && uploaded % 20 === 0) {
1393
- deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
1394
- }
1395
- }
1396
- const completeKey = randomUUID();
1397
- await withRateLimitRetry(deps, "finishing the upload", async () => {
1398
- await pace();
1399
- return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1400
- method: "POST",
1401
- body: {},
1402
- headers: { "idempotency-key": completeKey },
1403
- });
1404
- }, budget);
1405
- if (update)
1406
- await pace();
1407
- const sourceId = update
1408
- ? await ownerArtifactSourceId(deps, update.id)
1409
- : undefined;
1410
- const source = publishSourcePayload(upload.manifestHash, sourceId);
1411
- // The whole bundle is already uploaded by the time we get here, so losing this
1412
- // one request to a throttle discards the entire publish — the exact failure
1413
- // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1414
- // so a retry reuses it and cannot double-create.
1415
- const createKey = randomUUID();
1416
- return withRateLimitRetry(deps, "creating the artifact", async () => {
1417
- await pace();
1418
- if (update?.family === "compatibility") {
1419
- return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1420
- method: "PUT",
1421
- body: {
1422
- uploadId: upload.uploadId,
1423
- manifestHash: upload.manifestHash,
1424
- source,
1425
- ...wireFields,
1426
- },
1427
- headers: {
1428
- "if-match": `"r${update.revision}"`,
1429
- "idempotency-key": createKey,
1430
- },
1431
- });
1658
+ for (let attempt = 0; attempt < 2; attempt++) {
1659
+ const reuseFrom = update && attempt === 0 ? update.id : undefined;
1660
+ try {
1661
+ const uploadKey = randomUUID();
1662
+ const upload = await withRateLimitRetry(deps, "starting the upload", async () => {
1663
+ await pace();
1664
+ return requestJson(deps, "/uploads", {
1665
+ method: "POST",
1666
+ body: {
1667
+ kind: "html-artifact-bundle",
1668
+ ...(reuseFrom ? { reuseFrom } : {}),
1669
+ manifest,
1670
+ declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
1671
+ },
1672
+ headers: { "idempotency-key": uploadKey },
1673
+ });
1674
+ }, budget);
1675
+ let uploaded = 0;
1676
+ let bytesUploaded = 0;
1677
+ for (const plan of upload.files) {
1678
+ const file = filesByPath.get(plan.path);
1679
+ if (!file)
1680
+ throw new LocalError("upload_manifest_mismatch", "Server returned an unexpected upload file", { context: { path: plan.path } });
1681
+ await withRateLimitRetry(deps, `uploading ${plan.path}`, async (attemptIndex) => {
1682
+ await pace();
1683
+ return requestRaw(deps, `/uploads/${upload.uploadId}/files/${plan.fileToken}`, file.bytes, { "content-length": String(file.byteSize) }, attemptIndex > 0);
1684
+ }, budget);
1685
+ uploaded += 1;
1686
+ bytesUploaded += file.byteSize;
1687
+ // A large bundle is paced to well under a minute's worth of requests, so a
1688
+ // silent multi-minute publish reads as a hang. Progress goes to stderr so
1689
+ // `--json` stdout stays machine-parseable.
1690
+ if (upload.files.length > 20 && uploaded % 20 === 0) {
1691
+ deps.stderr(`Uploaded ${uploaded}/${upload.files.length} files.\n`);
1692
+ }
1693
+ }
1694
+ const completeKey = randomUUID();
1695
+ await withRateLimitRetry(deps, "finishing the upload", async () => {
1696
+ await pace();
1697
+ return requestJson(deps, `/uploads/${upload.uploadId}/complete`, {
1698
+ method: "POST",
1699
+ body: {},
1700
+ headers: { "idempotency-key": completeKey },
1701
+ });
1702
+ }, budget);
1703
+ if (update)
1704
+ await pace();
1705
+ const sourceId = update
1706
+ ? await ownerArtifactSourceId(deps, update.id)
1707
+ : undefined;
1708
+ const source = {
1709
+ ...publishSourcePayload(upload.manifestHash, sourceId),
1710
+ localDigest,
1711
+ };
1712
+ // The whole bundle is already uploaded by the time we get here, so losing this
1713
+ // one request to a throttle discards the entire publish — the exact failure
1714
+ // spec 089 exists to close. The key is minted ONCE outside the retry closure,
1715
+ // so a retry reuses it and cannot double-create.
1716
+ const createKey = randomUUID();
1717
+ const result = await withRateLimitRetry(deps, "creating the artifact", async () => {
1718
+ await pace();
1719
+ if (update?.family === "compatibility") {
1720
+ return requestJson(deps, `/artifacts/html/${encodeURIComponent(update.id)}`, {
1721
+ method: "PUT",
1722
+ body: {
1723
+ uploadId: upload.uploadId,
1724
+ manifestHash: upload.manifestHash,
1725
+ source,
1726
+ ...wireFields,
1727
+ },
1728
+ headers: {
1729
+ "if-match": `"r${update.revision}"`,
1730
+ "idempotency-key": createKey,
1731
+ },
1732
+ });
1733
+ }
1734
+ if (update?.family === "generic") {
1735
+ return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1736
+ method: "PUT",
1737
+ body: {
1738
+ sourceFormat: "html",
1739
+ uploadId: upload.uploadId,
1740
+ manifestHash: upload.manifestHash,
1741
+ source,
1742
+ ...wireFields,
1743
+ },
1744
+ headers: artifactMutationHeaders(update.etag, createKey),
1745
+ });
1746
+ }
1747
+ return requestJson(deps, "/artifacts", {
1748
+ method: "POST",
1749
+ body: {
1750
+ sourceFormat: "html",
1751
+ uploadId: upload.uploadId,
1752
+ manifestHash: upload.manifestHash,
1753
+ hostingRiskAcknowledged,
1754
+ source,
1755
+ ...(publishSeparately ? { allowDuplicate: true } : {}),
1756
+ ...(settings && Object.keys(settings).length > 0
1757
+ ? { settings }
1758
+ : {}),
1759
+ ...wireFields,
1760
+ },
1761
+ headers: { "idempotency-key": createKey },
1762
+ });
1763
+ }, budget);
1764
+ const reused = upload.reused?.length ?? 0;
1765
+ if (!wire.json)
1766
+ deps.stderr(`Uploaded ${uploaded} of ${files.length} files (${reused} unchanged, reused).\nBytes uploaded: ${bytesUploaded}.\n`);
1767
+ return withImageReport({
1768
+ ...result,
1769
+ upload: { uploaded, reused, bytesUploaded },
1770
+ }, warnings, imageOptimization);
1432
1771
  }
1433
- if (update?.family === "generic") {
1434
- return requestJson(deps, `/artifacts/${encodeURIComponent(update.id)}`, {
1435
- method: "PUT",
1436
- body: {
1437
- sourceFormat: "html",
1438
- uploadId: upload.uploadId,
1439
- manifestHash: upload.manifestHash,
1440
- source,
1441
- ...wireFields,
1442
- },
1443
- headers: artifactMutationHeaders(update.etag, createKey),
1444
- });
1772
+ catch (error) {
1773
+ if (!reuseFrom ||
1774
+ !(error instanceof FoleoError) ||
1775
+ error.code !== "reuse_source_missing")
1776
+ throw error;
1777
+ deps.stderr("Reuse source missing; retrying once with a full upload.\n");
1445
1778
  }
1446
- return requestJson(deps, "/artifacts", {
1447
- method: "POST",
1448
- body: {
1449
- sourceFormat: "html",
1450
- uploadId: upload.uploadId,
1451
- manifestHash: upload.manifestHash,
1452
- hostingRiskAcknowledged,
1453
- source,
1454
- ...(publishSeparately ? { allowDuplicate: true } : {}),
1455
- ...(settings && Object.keys(settings).length > 0 ? { settings } : {}),
1456
- ...wireFields,
1457
- },
1458
- headers: { "idempotency-key": createKey },
1459
- });
1460
- }, budget);
1779
+ }
1780
+ throw new LocalError("reuse_source_missing", "Full upload retry exhausted.");
1461
1781
  }
1462
1782
  function revisionHeaders(revision) {
1463
1783
  return { "if-match": `"r${revision}"`, "idempotency-key": randomUUID() };
@@ -1966,8 +2286,10 @@ async function publish(args, deps) {
1966
2286
  const parsed = parseFlags(args);
1967
2287
  const file = parsed.positionals[0];
1968
2288
  if (!file || parsed.positionals.length !== 1)
1969
- 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.");
2289
+ 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.");
1970
2290
  const isDirectory = await pathIsDirectory(file, deps);
2291
+ if (parsed.optimizeImages && !isDirectory)
2292
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
1971
2293
  if (!isDirectory && parsed.dryRun) {
1972
2294
  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" });
1973
2295
  }
@@ -1984,7 +2306,7 @@ async function publish(args, deps) {
1984
2306
  throw runtimeProfileNotApplicable({ sourceFormat: "markdown" });
1985
2307
  }
1986
2308
  const markdown = await deps.readFile(file, "utf8");
1987
- const assets = await uploadMarkdownAssets(file, markdown, deps);
2309
+ const assets = await uploadMarkdownAssets(file, markdown, deps, parsed.json);
1988
2310
  const result = await requestJson(deps, "/artifacts", {
1989
2311
  method: "POST",
1990
2312
  body: {
@@ -2001,32 +2323,61 @@ async function publish(args, deps) {
2001
2323
  : {}),
2002
2324
  ...accessWideningField(parsed.acknowledgeAccessWidening),
2003
2325
  },
2326
+ headers: { "idempotency-key": randomUUID() },
2004
2327
  });
2005
- writeResult(deps, result, parsed.json);
2328
+ writeResult(deps, withImageReport(result, assets?.warnings ?? []), parsed.json);
2006
2329
  return 0;
2007
2330
  }
2008
2331
  async function update(args, deps) {
2009
2332
  resolveUploadRate(deps);
2010
2333
  const parsed = parseFlags(args);
2011
- // Asking for a plan must never mutate. Until an update plan exists, refuse
2012
- // the flag rather than silently performing the real update.
2013
- if (parsed.dryRun) {
2014
- throw new UsageError("--dry-run is not implemented for update. Run the update without it.", "dry_run_unsupported", { operation: "update" });
2015
- }
2016
2334
  const [id, file] = parsed.positionals;
2017
2335
  if (!id || !file || parsed.positionals.length !== 2) {
2018
- throw new Error("Usage: foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json] (or Markdown compatibility --version <version>)");
2336
+ 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>)");
2019
2337
  }
2020
2338
  const isDirectory = await pathIsDirectory(file, deps);
2339
+ if (parsed.optimizeImages && !isDirectory)
2340
+ throw new UsageError("--optimize-images applies to an HTML bundle folder", "image_optimization_not_applicable");
2021
2341
  if (isDirectory) {
2342
+ if (parsed.dryRun) {
2343
+ const bundle = await prepareImageBundle(file, deps, parsed);
2344
+ const plan = {
2345
+ ok: true,
2346
+ plan: {
2347
+ action: "update",
2348
+ id,
2349
+ scope: "bundle-only",
2350
+ executable: false,
2351
+ note: "Revision, access widening and safety review are checked by the server on apply.",
2352
+ bundle: {
2353
+ fileCount: bundle.files.length,
2354
+ totalBytes: bundle.files.reduce((n, f) => n + f.byteSize, 0),
2355
+ files: bundle.files.map(({ bytes: _bytes, ...f }) => f),
2356
+ routes: bundle.routes,
2357
+ skipped: bundle.skipped,
2358
+ },
2359
+ },
2360
+ warnings: bundle.warnings,
2361
+ ...(bundle.imageOptimization
2362
+ ? { imageOptimization: bundle.imageOptimization }
2363
+ : {}),
2364
+ };
2365
+ if (parsed.json)
2366
+ deps.stdout(`${JSON.stringify(plan, null, 2)}\n`);
2367
+ else
2368
+ deps.stdout(`plan: update ${id} (bundle-only; server checks pending)\nfiles: ${bundle.files.length}\n`);
2369
+ return 0;
2370
+ }
2022
2371
  const revision = artifactRevision(parsed.revision);
2023
2372
  if (revision === null) {
2024
- throw new Error("Usage: foleo update <id> <bundle-root> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json]");
2373
+ 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]");
2025
2374
  }
2026
2375
  const result = await publishBundle(file, deps, { family: "generic", id, etag: revision }, false, false, undefined, htmlWireOptions(parsed));
2027
2376
  writeResult(deps, result, parsed.json);
2028
2377
  return 0;
2029
2378
  }
2379
+ if (parsed.dryRun)
2380
+ throw new UsageError("--dry-run is only implemented for HTML bundle folders", "dry_run_unsupported", { operation: "update" });
2030
2381
  if (!file.toLowerCase().endsWith(".md")) {
2031
2382
  throw new Error("Unsupported update input. Use a .md file or an HTML site directory.");
2032
2383
  }
@@ -2041,36 +2392,66 @@ async function update(args, deps) {
2041
2392
  throw new UsageError("--revision requires an opaque Artifact ETag", "revision_invalid");
2042
2393
  }
2043
2394
  const markdown = await deps.readFile(file, "utf8");
2044
- const assets = await uploadMarkdownAssets(file, markdown, deps);
2045
2395
  const sourceId = await ownerArtifactSourceId(deps, id);
2046
2396
  const source = publishSourcePayload(sha256Utf8(markdown), sourceId);
2047
- const result = opaqueRevision !== null
2048
- ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2049
- method: "PUT",
2050
- body: {
2051
- sourceFormat: "markdown",
2052
- markdown,
2053
- source,
2054
- ...(assets
2055
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
2056
- : {}),
2057
- ...accessWideningField(parsed.acknowledgeAccessWidening),
2058
- },
2059
- headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
2060
- })
2061
- : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
2062
- method: "PUT",
2063
- body: {
2064
- markdown,
2065
- version: parsed.version,
2066
- source,
2067
- ...(assets
2068
- ? { uploadId: assets.uploadId, manifestHash: assets.manifestHash }
2069
- : {}),
2070
- ...accessWideningField(parsed.acknowledgeAccessWidening),
2071
- },
2072
- });
2073
- writeResult(deps, result, parsed.json);
2397
+ let assets = null;
2398
+ let result;
2399
+ for (let attempt = 0; attempt < 2; attempt++) {
2400
+ const reuseFrom = attempt === 0 ? id : undefined;
2401
+ try {
2402
+ assets = await uploadMarkdownAssets(file, markdown, deps, parsed.json, reuseFrom, id);
2403
+ result =
2404
+ opaqueRevision !== null
2405
+ ? await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2406
+ method: "PUT",
2407
+ body: {
2408
+ sourceFormat: "markdown",
2409
+ markdown,
2410
+ source,
2411
+ ...(assets
2412
+ ? {
2413
+ uploadId: assets.uploadId,
2414
+ manifestHash: assets.manifestHash,
2415
+ }
2416
+ : {}),
2417
+ ...accessWideningField(parsed.acknowledgeAccessWidening),
2418
+ },
2419
+ headers: artifactMutationHeaders(opaqueRevision, randomUUID()),
2420
+ })
2421
+ : await requestJson(deps, `/docs/${encodeURIComponent(id)}`, {
2422
+ method: "PUT",
2423
+ body: {
2424
+ markdown,
2425
+ version: parsed.version,
2426
+ source,
2427
+ ...(assets
2428
+ ? {
2429
+ uploadId: assets.uploadId,
2430
+ manifestHash: assets.manifestHash,
2431
+ }
2432
+ : {}),
2433
+ ...accessWideningField(parsed.acknowledgeAccessWidening),
2434
+ },
2435
+ headers: { "idempotency-key": randomUUID() },
2436
+ });
2437
+ break;
2438
+ }
2439
+ catch (error) {
2440
+ if (!reuseFrom ||
2441
+ !(error instanceof FoleoError) ||
2442
+ error.code !== "reuse_source_missing")
2443
+ throw error;
2444
+ deps.stderr("Reuse source missing; retrying once with a full upload.\n");
2445
+ }
2446
+ }
2447
+ writeResult(deps, {
2448
+ ...withImageReport(result, assets?.warnings ?? []),
2449
+ upload: assets?.upload ?? { uploaded: 0, reused: 0, bytesUploaded: 0 },
2450
+ }, parsed.json);
2451
+ if (!parsed.json) {
2452
+ const upload = assets?.upload ?? { uploaded: 0, reused: 0 };
2453
+ deps.stdout(`Uploaded ${upload.uploaded} of ${upload.uploaded + upload.reused} images (${upload.reused} reused).\n`);
2454
+ }
2074
2455
  return 0;
2075
2456
  }
2076
2457
  async function pathIsDirectory(path, deps) {
@@ -2212,10 +2593,27 @@ function liveDocAssetMediaType(path) {
2212
2593
  const extension = path.slice(path.lastIndexOf(".")).toLowerCase();
2213
2594
  return LIVE_DOC_ASSET_MEDIA_TYPES[extension] ?? null;
2214
2595
  }
2215
- async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2596
+ async function uploadMarkdownAssets(markdownPath, markdown, deps, json, reuseFrom, replaceEmptyFor) {
2216
2597
  const files = await scanMarkdownAssets(markdownPath, markdown, deps);
2217
- if (files.length === 0)
2218
- return null;
2598
+ const warnings = auditImages(files);
2599
+ reportHeavyImages(deps, warnings, false, json);
2600
+ if (files.length === 0) {
2601
+ if (!replaceEmptyFor)
2602
+ return null;
2603
+ // An omitted upload preserves the current attachments. Only request an
2604
+ // empty replacement when the owner read confirms there are attachments.
2605
+ let previous;
2606
+ try {
2607
+ previous = await requestJson(deps, `/artifacts/${encodeURIComponent(replaceEmptyFor)}/source/content?manifest=1`, { method: "GET", body: undefined });
2608
+ }
2609
+ catch (error) {
2610
+ if (error instanceof ApiRequestError && error.status === 404)
2611
+ return null;
2612
+ throw error;
2613
+ }
2614
+ if (!(typeof previous.fileCount === "number" && previous.fileCount > 1))
2615
+ return null;
2616
+ }
2219
2617
  const manifest = files.map(({ bytes: _bytes, ...file }) => file);
2220
2618
  // Same pacing and retry contract as the HTML bundle path: this loop hits the
2221
2619
  // same /v1/ fence and previously discarded the whole upload on one 429. The
@@ -2230,6 +2628,7 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2230
2628
  method: "POST",
2231
2629
  body: {
2232
2630
  kind: "live-doc-assets",
2631
+ ...(reuseFrom ? { reuseFrom } : {}),
2233
2632
  manifest,
2234
2633
  declaredBytes: manifest.reduce((n, file) => n + file.byteSize, 0),
2235
2634
  },
@@ -2254,7 +2653,16 @@ async function uploadMarkdownAssets(markdownPath, markdown, deps) {
2254
2653
  headers: { "idempotency-key": completeKey },
2255
2654
  });
2256
2655
  }, budget);
2257
- return { uploadId: upload.uploadId, manifestHash: upload.manifestHash };
2656
+ return {
2657
+ uploadId: upload.uploadId,
2658
+ manifestHash: upload.manifestHash,
2659
+ warnings,
2660
+ upload: {
2661
+ uploaded: upload.files.length,
2662
+ reused: files.length - upload.files.length,
2663
+ bytesUploaded: upload.files.reduce((n, plan) => n + files.find((file) => file.path === plan.path).byteSize, 0),
2664
+ },
2665
+ };
2258
2666
  }
2259
2667
  async function unpublish(args, deps) {
2260
2668
  const parsed = parseFlags(args);
@@ -2763,14 +3171,40 @@ async function deletionStatus(args, deps) {
2763
3171
  async function status(args, deps) {
2764
3172
  const parsed = parseFlags(args);
2765
3173
  const id = parsed.positionals[0];
2766
- if (!id || parsed.positionals.length !== 1) {
2767
- throw new Error("Usage: foleo status <id> [--json]");
3174
+ if (!id ||
3175
+ parsed.positionals.length > 2 ||
3176
+ (parsed.positionals[1] && parsed.sourcePath)) {
3177
+ throw new Error("Usage: foleo status <id> [<path> | --source <path>] [--json]");
2768
3178
  }
2769
3179
  const result = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2770
3180
  method: "GET",
2771
3181
  body: undefined,
2772
3182
  });
2773
- writeStatusResult(deps, result, parsed.json);
3183
+ const path = parsed.sourcePath ?? parsed.positionals[1];
3184
+ if (path && isRecord(result)) {
3185
+ const artifact = nestedRecord(result, "artifact") ?? result;
3186
+ const source = nestedRecord(artifact, "source");
3187
+ const remoteDigest = source ? stringField(source, "localDigest") : null;
3188
+ let localDrift = "unknown";
3189
+ if (remoteDigest) {
3190
+ const format = stringField(artifact, "sourceFormat") ??
3191
+ (source ? stringField(source, "sourceFormat") : null);
3192
+ let digest;
3193
+ if (format === "markdown") {
3194
+ const markdown = await deps.readFile(path, "utf8");
3195
+ digest = markdownLocalDigest(markdown, await scanMarkdownAssets(path, markdown, deps));
3196
+ }
3197
+ else if (format === "html") {
3198
+ digest = htmlLocalDigest((await scanBundle(path, deps)).files);
3199
+ }
3200
+ if (digest)
3201
+ localDrift = digest === remoteDigest ? "in_sync" : "local_changed";
3202
+ }
3203
+ writeStatusResult(deps, { ...result, localDrift }, parsed.json);
3204
+ }
3205
+ else {
3206
+ writeStatusResult(deps, result, parsed.json);
3207
+ }
2774
3208
  return 0;
2775
3209
  }
2776
3210
  async function list(args, deps) {
@@ -2875,6 +3309,213 @@ function environmentCommand(args, deps) {
2875
3309
  deps.stdout(`Environment: ${info.name}\nAPI: ${info.apiBase}\n`);
2876
3310
  return 0;
2877
3311
  }
3312
+ /** Download one revision completely before writing any destination files. */
3313
+ async function exportArtifact(args, deps) {
3314
+ const force = args.includes("--force");
3315
+ const parsed = parseFlags(args.filter((arg) => arg !== "--force"));
3316
+ if (parsed.positionals.length !== 2)
3317
+ throw new UsageError("Usage: foleo export <id> <dir> [--force] [--json]");
3318
+ const [id, directory] = parsed.positionals;
3319
+ const root = resolve(directory);
3320
+ const inspect = async (path) => {
3321
+ try {
3322
+ return await lstat(path);
3323
+ }
3324
+ catch (error) {
3325
+ if (isRecord(error) && error.code === "ENOENT")
3326
+ return null;
3327
+ throw error;
3328
+ }
3329
+ };
3330
+ const existing = await inspect(root);
3331
+ if (existing && (!existing.isDirectory() || existing.isSymbolicLink()))
3332
+ throw new LocalError("export_unsafe_path", "Export destination must be a directory, not a symlink.");
3333
+ if (existing && !force && (await readdir(root)).length)
3334
+ throw new LocalError("export_directory_not_empty", "Export destination is not empty. Use --force to overwrite matching files.");
3335
+ const discover = () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/source/content?manifest=1`, {
3336
+ method: "GET",
3337
+ body: undefined,
3338
+ });
3339
+ const source = await discover();
3340
+ const origin = new URL(apiBase(deps)).origin;
3341
+ // Source URLs are signed capabilities. Never forward the API bearer token.
3342
+ const download = async (url) => {
3343
+ const target = new URL(url);
3344
+ if (target.origin !== origin || target.pathname !== "/v1/source-downloads")
3345
+ throw new LocalError("export_invalid_manifest", "Invalid source download URL.");
3346
+ const response = await deps.fetch(target.href, { redirect: "error" });
3347
+ if (!response.ok)
3348
+ throw apiResponseError(response.status, await response.json().catch(() => null));
3349
+ return response;
3350
+ };
3351
+ const loadManifest = async (current) => {
3352
+ if (current.delivery.kind !== "manifest_url" ||
3353
+ !current.delivery.url ||
3354
+ !Number.isSafeInteger(current.fileCount) ||
3355
+ current.fileCount < 1 ||
3356
+ current.fileCount > 1000)
3357
+ throw new LocalError("export_invalid_manifest", "Invalid source manifest.");
3358
+ const files = [];
3359
+ const seen = new Set();
3360
+ let next = current.delivery.url;
3361
+ for (let page = 0; next && page < 10; page++) {
3362
+ const manifest = (await (await download(next)).json());
3363
+ if (manifest.id !== id ||
3364
+ manifest.sourceRevisionId !== current.sourceRevisionId ||
3365
+ manifest.fileCount !== current.fileCount ||
3366
+ !Array.isArray(manifest.files))
3367
+ throw new LocalError("export_invalid_manifest", "Source manifest changed during export.");
3368
+ for (const file of manifest.files) {
3369
+ if (typeof file.path !== "string" ||
3370
+ !file.path.startsWith("/") ||
3371
+ file.path.includes("\\") ||
3372
+ [...file.path].some((char) => char.charCodeAt(0) <= 31 || char.charCodeAt(0) === 127) ||
3373
+ file.path
3374
+ .slice(1)
3375
+ .split("/")
3376
+ .some((part) => !part || part === "." || part === "..") ||
3377
+ seen.has(file.path) ||
3378
+ !/^[a-f0-9]{64}$/.test(file.sha256) ||
3379
+ !Number.isSafeInteger(file.byteSize) ||
3380
+ file.byteSize < 0 ||
3381
+ file.byteSize > HTML_BUNDLE_MAX_FILE_BYTES ||
3382
+ typeof file.url !== "string")
3383
+ throw new LocalError("export_invalid_manifest", "Unsafe or invalid source file entry.");
3384
+ seen.add(file.path);
3385
+ files.push(file);
3386
+ }
3387
+ if (files.length > current.fileCount)
3388
+ throw new LocalError("export_invalid_manifest", "Source manifest has too many files.");
3389
+ next = manifest.nextUrl;
3390
+ }
3391
+ if (next ||
3392
+ files.length !== current.fileCount ||
3393
+ files.reduce((sum, file) => sum + file.byteSize, 0) >
3394
+ HTML_BUNDLE_MAX_BYTES)
3395
+ throw new LocalError("export_invalid_manifest", "Source manifest is incomplete or exceeds export limits.");
3396
+ return files;
3397
+ };
3398
+ const loadFreshManifest = async (initial) => {
3399
+ let current = initial;
3400
+ for (let refresh = 0;; refresh++) {
3401
+ if (current.sourceFormat !== source.sourceFormat ||
3402
+ current.sourceRevisionId !== source.sourceRevisionId ||
3403
+ current.contentHash !== source.contentHash ||
3404
+ current.fileCount !== source.fileCount)
3405
+ throw new LocalError("export_revision_changed", "Source changed while renewing download URLs. Restart export.");
3406
+ try {
3407
+ return await loadManifest(current);
3408
+ }
3409
+ catch (error) {
3410
+ if (!(error instanceof FoleoError) ||
3411
+ error.httpStatus !== 410 ||
3412
+ error.code !== "source_url_expired" ||
3413
+ refresh >= 3)
3414
+ throw error;
3415
+ current = await discover();
3416
+ }
3417
+ }
3418
+ };
3419
+ let files = await loadFreshManifest(source);
3420
+ const identity = (entries) => JSON.stringify(entries
3421
+ .map(({ path, sha256, byteSize, mediaType }) => ({
3422
+ path,
3423
+ sha256,
3424
+ byteSize,
3425
+ mediaType,
3426
+ }))
3427
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)));
3428
+ const originalIdentity = identity(files);
3429
+ const staging = await mkdtemp(join(tmpdir(), "foleo-export-"));
3430
+ try {
3431
+ for (let index = 0; index < files.length; index++) {
3432
+ let file = files[index];
3433
+ let response;
3434
+ // Refresh only the pending file's capabilities; verified staging files
3435
+ // survive refresh. Bound repeated expiry so a broken clock cannot loop.
3436
+ for (let refresh = 0;; refresh++) {
3437
+ try {
3438
+ response = await download(file.url);
3439
+ break;
3440
+ }
3441
+ catch (error) {
3442
+ if (!(error instanceof FoleoError) ||
3443
+ error.httpStatus !== 410 ||
3444
+ error.code !== "source_url_expired" ||
3445
+ refresh >= 3)
3446
+ throw error;
3447
+ const current = await discover();
3448
+ const renewed = await loadFreshManifest(current);
3449
+ if (current.sourceFormat !== source.sourceFormat ||
3450
+ current.sourceRevisionId !== source.sourceRevisionId ||
3451
+ current.contentHash !== source.contentHash ||
3452
+ identity(renewed) !== originalIdentity)
3453
+ throw new LocalError("export_revision_changed", "Source changed while renewing download URLs. Restart export.");
3454
+ const byPath = new Map(renewed.map((entry) => [entry.path, entry]));
3455
+ files = files.map((entry) => byPath.get(entry.path));
3456
+ file = files[index];
3457
+ }
3458
+ }
3459
+ const bytes = new Uint8Array(await response.arrayBuffer());
3460
+ if (bytes.byteLength !== file.byteSize ||
3461
+ createHash("sha256").update(bytes).digest("hex") !== file.sha256)
3462
+ throw new LocalError("export_hash_mismatch", `Source integrity check failed for ${file.path}.`);
3463
+ await writeFile(join(staging, String(index)), bytes);
3464
+ }
3465
+ await mkdir(root, { recursive: true });
3466
+ // Check each component: --force permits replacing regular files only.
3467
+ for (const file of files) {
3468
+ const parts = file.path.slice(1).split("/");
3469
+ let parent = root;
3470
+ for (const part of parts.slice(0, -1)) {
3471
+ parent = join(parent, part);
3472
+ try {
3473
+ await mkdir(parent);
3474
+ }
3475
+ catch (error) {
3476
+ if (!isRecord(error) || error.code !== "EEXIST")
3477
+ throw error;
3478
+ }
3479
+ const entry = await lstat(parent);
3480
+ if (entry.isSymbolicLink() || !entry.isDirectory())
3481
+ throw new LocalError("export_unsafe_path", "Export path contains a symlink or non-directory.");
3482
+ }
3483
+ const entry = await inspect(join(root, ...parts));
3484
+ if (entry &&
3485
+ (!force || !entry.isFile() || entry.isSymbolicLink() || entry.nlink > 1))
3486
+ throw new LocalError("export_unsafe_path", `Refusing to overwrite ${file.path}.`);
3487
+ }
3488
+ for (const [index, file] of files.entries()) {
3489
+ const handle = await open(join(root, file.path.slice(1)), constants.O_WRONLY |
3490
+ constants.O_CREAT |
3491
+ constants.O_NOFOLLOW |
3492
+ (force ? constants.O_TRUNC : constants.O_EXCL), 0o600);
3493
+ try {
3494
+ await handle.writeFile(await readFile(join(staging, String(index))));
3495
+ }
3496
+ finally {
3497
+ await handle.close();
3498
+ }
3499
+ }
3500
+ }
3501
+ finally {
3502
+ await rm(staging, { recursive: true, force: true });
3503
+ }
3504
+ const summary = {
3505
+ id,
3506
+ directory: root,
3507
+ sourceFormat: source.sourceFormat,
3508
+ sourceRevisionId: source.sourceRevisionId,
3509
+ fileCount: files.length,
3510
+ byteSize: files.reduce((sum, file) => sum + file.byteSize, 0),
3511
+ verified: true,
3512
+ exportNote: source.exportNote,
3513
+ };
3514
+ deps.stdout(parsed.json
3515
+ ? `${JSON.stringify(summary, null, 2)}\n`
3516
+ : `Exported ${files.length} files (${summary.byteSize} bytes) to ${root}; SHA-256 verified.\n${source.exportNote ?? ""}\n`);
3517
+ return 0;
3518
+ }
2878
3519
  async function requestJson(deps, path, init) {
2879
3520
  const credential = await resolveCredentialWithSource(deps);
2880
3521
  if (!credential)
@@ -2891,12 +3532,58 @@ async function requestJsonWithToken(deps, path, token, init) {
2891
3532
  "content-type": "application/json",
2892
3533
  ...init.headers,
2893
3534
  };
2894
- const response = await deps.fetch(`${apiBase(deps)}${path}`, {
2895
- method: init.method,
2896
- headers,
2897
- ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
2898
- });
2899
- const body = await response.json().catch(() => null);
3535
+ uploadRuns.get(deps)?.controller.signal.throwIfAborted();
3536
+ if (uploadRuns.has(deps) &&
3537
+ /^\/(?:artifacts|docs)(?:\/|$)/u.test(path) &&
3538
+ init.method !== "GET")
3539
+ uploadRuns.get(deps).submitted = true;
3540
+ const frozenBody = init.body === undefined ? undefined : JSON.stringify(init.body);
3541
+ const key = init.headers?.["idempotency-key"];
3542
+ const receiptWrite = key &&
3543
+ (init.method === "POST" || init.method === "PUT") &&
3544
+ /^\/(?:artifacts(?:\/html)?|docs)(?:\/[^/]+)?$/u.test(path);
3545
+ let response;
3546
+ let body;
3547
+ for (let retry = 0;; retry++) {
3548
+ try {
3549
+ response = await deps.fetch(`${apiBase(deps)}${path}`, {
3550
+ method: init.method,
3551
+ ...(uploadRuns.has(deps)
3552
+ ? { signal: uploadRuns.get(deps).controller.signal }
3553
+ : {}),
3554
+ headers,
3555
+ ...(frozenBody === undefined ? {} : { body: frozenBody }),
3556
+ });
3557
+ if (!receiptWrite ||
3558
+ (response.status !== 502 && response.status !== 504)) {
3559
+ if (response.ok && receiptWrite)
3560
+ body = await response.json();
3561
+ else
3562
+ body = await response.json().catch(() => null);
3563
+ break;
3564
+ }
3565
+ await response.body?.cancel();
3566
+ }
3567
+ catch (error) {
3568
+ // fetch throws TypeError for network loss; Node also exposes reset/socket
3569
+ // codes. Local validation/auth failures never enter this transport loop.
3570
+ if (!receiptWrite ||
3571
+ uploadRuns.get(deps)?.controller.signal.aborted ||
3572
+ !(error instanceof TypeError ||
3573
+ (isRecord(error) &&
3574
+ ["ECONNRESET", "ETIMEDOUT", "EPIPE", "UND_ERR_SOCKET"].includes(String(error.code)))))
3575
+ throw error;
3576
+ }
3577
+ if (retry >= 3)
3578
+ throw new LocalError("write_result_unknown", "The write may have succeeded, but its response could not be recovered.", {
3579
+ retryable: true,
3580
+ context: { idempotencyKey: key, method: init.method, path },
3581
+ 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.`,
3582
+ });
3583
+ deps.stderr(`Response lost; replaying the same write (attempt ${retry + 2}).\n`);
3584
+ await (deps.sleep ??
3585
+ ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(Math.min(4000, 500 * 2 ** retry));
3586
+ }
2900
3587
  if (RETRYABLE_STATUSES.has(response.status)) {
2901
3588
  // Thrown ahead of ApiRequestError so `withRateLimitRetry` can act on it. The
2902
3589
  // zone fence in front of this API answers with a Cloudflare error page rather
@@ -2907,6 +3594,11 @@ async function requestJsonWithToken(deps, path, token, init) {
2907
3594
  if (!response.ok) {
2908
3595
  throw new ApiRequestError(response.status, apiErrorCode(body, response.status), body);
2909
3596
  }
3597
+ if (path === "/uploads" &&
3598
+ isRecord(body) &&
3599
+ typeof body.uploadId === "string") {
3600
+ uploadRun(deps).sessions.add(body.uploadId);
3601
+ }
2910
3602
  return body;
2911
3603
  }
2912
3604
  class ApiRequestError extends FoleoError {
@@ -2924,19 +3616,43 @@ class ApiRequestError extends FoleoError {
2924
3616
  : null;
2925
3617
  super({
2926
3618
  code,
2927
- message: code === "matching_source_exists"
2928
- ? matchingSourceExistsMessage(body)
2929
- : code === "acknowledgement_required" &&
2930
- envelope?.field !== "acknowledgeLinkBreakage"
2931
- ? "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."
2932
- : code === "contained_profile_unavailable"
2933
- ? containedProfileUnavailableMessage(references ?? [])
2934
- : `Foleo API error: ${code}`,
3619
+ message: code === "bundle_new_files_limit" &&
3620
+ typeof envelope?.message === "string"
3621
+ ? envelope.message
3622
+ : code === "matching_source_exists"
3623
+ ? matchingSourceExistsMessage(body)
3624
+ : code === "acknowledgement_required" &&
3625
+ envelope?.field !== "acknowledgeLinkBreakage"
3626
+ ? "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."
3627
+ : code === "contained_profile_unavailable"
3628
+ ? containedProfileUnavailableMessage(references ?? [])
3629
+ : `Foleo API error: ${code}`,
2935
3630
  httpStatus: status,
2936
3631
  source: "api",
2937
3632
  retryable,
2938
3633
  ...(next === null ? {} : { next }),
2939
- ...(references === null ? {} : { context: { references } }),
3634
+ ...(["approval_required", "input_required"].includes(code) && envelope
3635
+ ? {
3636
+ next: `Open ${String(envelope.reviewUrl ?? "Foleo")} to review, then use foleo approval commit ${String(envelope.approvalId ?? "<id>")} --idempotency-key <key>.`,
3637
+ context: Object.fromEntries([
3638
+ "approvalId",
3639
+ "reviewUrl",
3640
+ "approvalReason",
3641
+ "targetType",
3642
+ "audiences",
3643
+ ]
3644
+ .filter((key) => envelope[key] !== undefined)
3645
+ .map((key) => [key, envelope[key]])),
3646
+ }
3647
+ : code === "bundle_new_files_limit" && envelope
3648
+ ? {
3649
+ context: Object.fromEntries(["limit", "count", "newFiles", "copiedFiles", "sharedObjects"]
3650
+ .filter((field) => envelope[field] !== undefined)
3651
+ .map((field) => [field, envelope[field]])),
3652
+ }
3653
+ : references === null
3654
+ ? {}
3655
+ : { context: { references } }),
2940
3656
  });
2941
3657
  this.name = "ApiRequestError";
2942
3658
  this.status = status;
@@ -3020,8 +3736,12 @@ allowReplay = false) {
3020
3736
  next: "Run `npx -y @foleo/cli login` or set FOLEO_TOKEN.",
3021
3737
  });
3022
3738
  const bytes = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
3739
+ uploadRuns.get(deps)?.controller.signal.throwIfAborted();
3023
3740
  const response = await deps.fetch(`${apiBase(deps)}${path}`, {
3024
3741
  method: "PUT",
3742
+ ...(uploadRuns.has(deps)
3743
+ ? { signal: uploadRuns.get(deps).controller.signal }
3744
+ : {}),
3025
3745
  headers: { authorization: `Bearer ${credential.token}`, ...headers },
3026
3746
  body: bytes,
3027
3747
  });
@@ -3258,6 +3978,26 @@ function loopbackSuccessBody() {
3258
3978
  function sha256Utf8(value) {
3259
3979
  return createHash("sha256").update(value, "utf8").digest("hex");
3260
3980
  }
3981
+ /** SHA-256 of UTF-8 JSON ["html-v1", sorted [path, sha256, byteSize] triples].
3982
+ * Paths are the upload scanner's root-relative POSIX paths, with leading slash.
3983
+ * Capture this before optimization: the uploaded manifest has different bytes.
3984
+ */
3985
+ export function htmlLocalDigest(files) {
3986
+ const sorted = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3987
+ return sha256Utf8(JSON.stringify([
3988
+ "html-v1",
3989
+ sorted.map(({ path, sha256, byteSize }) => [path, sha256, byteSize]),
3990
+ ]));
3991
+ }
3992
+ /** Must match the server's markdownLocalDigest, including preserved images. */
3993
+ export function markdownLocalDigest(markdown, images) {
3994
+ const sorted = [...images].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
3995
+ return sha256Utf8(JSON.stringify([
3996
+ "markdown-v1",
3997
+ markdown,
3998
+ sorted.map(({ path, sha256 }) => [path, sha256]),
3999
+ ]));
4000
+ }
3261
4001
  function publishSourcePayload(contentHash, sourceId) {
3262
4002
  return {
3263
4003
  provider: "local",
@@ -3366,6 +4106,8 @@ function writeResult(deps, result, json) {
3366
4106
  }
3367
4107
  if (result !== null && typeof result === "object" && "url" in result) {
3368
4108
  deps.stdout(`${String(result.url)}\n`);
4109
+ if ("unchanged" in result && result.unchanged === true)
4110
+ deps.stderr("Unchanged; the existing published version is current.\n");
3369
4111
  // The applied HTML runtime profile is chosen by the server; say which one
3370
4112
  // a human got. stderr, so stdout stays the bare URL it always was.
3371
4113
  const profile = stringField(result, "runtimeProfile");
@@ -3377,6 +4119,34 @@ function writeResult(deps, result, json) {
3377
4119
  }
3378
4120
  deps.stdout(`${JSON.stringify(result)}\n`);
3379
4121
  }
4122
+ /** Render the server's visibility descriptor; never infer capabilities from the id. */
4123
+ function writeSettingsResult(deps, result, json) {
4124
+ if (json || !isRecord(result) || !Array.isArray(result.visibilityOptions)) {
4125
+ writeResult(deps, result, json);
4126
+ return;
4127
+ }
4128
+ const settings = nestedRecord(result, "settings") ?? {};
4129
+ const options = result.visibilityOptions.filter(isRecord);
4130
+ const selected = options.find((option) => option.value === settings.visibility);
4131
+ const lines = [
4132
+ `Visibility: ${stringField(selected, "label") ?? settings.visibility ?? "-"}`,
4133
+ ];
4134
+ for (const option of options) {
4135
+ const disabled = option.available === false;
4136
+ lines.push(` ${String(option.label)} (${String(option.value)})${disabled ? " [disabled]" : ""}: ${String(option.audience)}`);
4137
+ if (disabled && typeof option.reason === "string")
4138
+ lines.push(` ${option.reason}`);
4139
+ if (option.widening === true)
4140
+ lines.push(" Access widening; existing connection policy or API-key acknowledgement rules apply.");
4141
+ }
4142
+ for (const [key, value] of Object.entries(settings)) {
4143
+ if (key !== "visibility")
4144
+ lines.push(`${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
4145
+ }
4146
+ if (typeof result.stateRevision === "number")
4147
+ lines.push(`State revision: ${result.stateRevision}`);
4148
+ deps.stdout(`${lines.join("\n")}\n`);
4149
+ }
3380
4150
  function writeStatusResult(deps, result, json) {
3381
4151
  if (json) {
3382
4152
  writeResult(deps, result, true);
@@ -3397,6 +4167,9 @@ function writeStatusResult(deps, result, json) {
3397
4167
  lines.push(`Version: ${statusRecord.version}`);
3398
4168
  if (typeof statusRecord.stateRevision === "number")
3399
4169
  lines.push(`State revision: ${statusRecord.stateRevision}`);
4170
+ const localDrift = stringField(result, "localDrift");
4171
+ if (localDrift)
4172
+ lines.push(`Local drift: ${localDrift}`);
3400
4173
  const revision = stringField(statusRecord, "etag");
3401
4174
  if (revision)
3402
4175
  lines.push(`Revision: ${revision}`);
@@ -3437,6 +4210,7 @@ function writeDeletionResult(deps, result, json) {
3437
4210
  }
3438
4211
  function parseFlags(args, options = {}) {
3439
4212
  const positionals = [];
4213
+ let sourcePath;
3440
4214
  let json = false;
3441
4215
  let title;
3442
4216
  let version;
@@ -3454,8 +4228,11 @@ function parseFlags(args, options = {}) {
3454
4228
  let publishSeparately = false;
3455
4229
  let allowDelete = false;
3456
4230
  let allowPurge = false;
4231
+ let allowWorkspaces = false;
4232
+ let allowWorkspaceSharing = false;
3457
4233
  let name;
3458
4234
  let dryRun = false;
4235
+ let optimizeImages;
3459
4236
  let previous;
3460
4237
  let acknowledgeLinkBreakage = false;
3461
4238
  let acknowledgeAccessWidening = false;
@@ -3480,6 +4257,14 @@ function parseFlags(args, options = {}) {
3480
4257
  throw new UsageError("--name requires a value", "name_missing");
3481
4258
  continue;
3482
4259
  }
4260
+ if (arg === "--optimize-images") {
4261
+ optimizeImages = true;
4262
+ continue;
4263
+ }
4264
+ if (arg === "--no-optimize-images") {
4265
+ optimizeImages = false;
4266
+ continue;
4267
+ }
3483
4268
  if (arg === "--dry-run") {
3484
4269
  dryRun = true;
3485
4270
  continue;
@@ -3511,6 +4296,12 @@ function parseFlags(args, options = {}) {
3511
4296
  throw new Error("--kind requires a value");
3512
4297
  continue;
3513
4298
  }
4299
+ if (arg === "--source") {
4300
+ sourcePath = args[++i];
4301
+ if (!sourcePath)
4302
+ throw new Error("--source requires a path");
4303
+ continue;
4304
+ }
3514
4305
  if (arg === "--format") {
3515
4306
  format = args[++i];
3516
4307
  if (!format)
@@ -3601,6 +4392,15 @@ function parseFlags(args, options = {}) {
3601
4392
  allowDelete = true;
3602
4393
  continue;
3603
4394
  }
4395
+ if (arg === "--allow-workspaces" || arg === "--allow-workspace-sharing") {
4396
+ if (!options.allowLoginScopeFlags)
4397
+ throw new UsageError(`${arg} is valid only with login`);
4398
+ if (arg === "--allow-workspaces")
4399
+ allowWorkspaces = true;
4400
+ else
4401
+ allowWorkspaceSharing = true;
4402
+ continue;
4403
+ }
3604
4404
  if (arg === "--allow-purge") {
3605
4405
  if (!options.allowLoginScopeFlags)
3606
4406
  throw new Error("--allow-purge is valid only with login");
@@ -3612,6 +4412,7 @@ function parseFlags(args, options = {}) {
3612
4412
  positionals.push(arg);
3613
4413
  }
3614
4414
  return {
4415
+ ...(sourcePath ? { sourcePath } : {}),
3615
4416
  positionals,
3616
4417
  json,
3617
4418
  ...(title !== undefined ? { title } : {}),
@@ -3630,8 +4431,11 @@ function parseFlags(args, options = {}) {
3630
4431
  publishSeparately,
3631
4432
  allowDelete,
3632
4433
  allowPurge,
4434
+ allowWorkspaces,
4435
+ allowWorkspaceSharing,
3633
4436
  ...(name === undefined ? {} : { name }),
3634
4437
  dryRun,
4438
+ optimizeImages,
3635
4439
  ...(previous === undefined ? {} : { previous }),
3636
4440
  acknowledgeLinkBreakage,
3637
4441
  acknowledgeAccessWidening,
@@ -3654,8 +4458,10 @@ function help() {
3654
4458
  return [
3655
4459
  "Usage:",
3656
4460
  " foleo --help",
3657
- " foleo login [--allow-purge] [--json]",
4461
+ " foleo login [--allow-purge] [--allow-workspaces] [--allow-workspace-sharing] [--json]",
3658
4462
  " foleo logout [--no-revoke] [--json]",
4463
+ " Workspace access is offered only to invited alpha accounts; browser consent starts unchecked.",
4464
+ " --allow-workspaces requests read + write; --allow-workspace-sharing requests share + read.",
3659
4465
  " foleo whoami [--json]",
3660
4466
  " foleo doctor [--json]",
3661
4467
  " foleo skill get|path",
@@ -3663,16 +4469,20 @@ function help() {
3663
4469
  " foleo environment [--json]",
3664
4470
  " foleo list [--kind <kind>] [--format <format>] [--runtime <class>] [--limit <n>] [--json]",
3665
4471
  " foleo get <id> [--json]",
4472
+ " foleo export <id> <dir> [--force] [--json] (source and assets; SHA-256 verified)",
3666
4473
  " foleo publish <path> [--title <title>] [--settings <json>] [--password-stdin] [--publish-separately] [--acknowledge-access-widening] [--json]",
3667
- " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--dry-run] [--json]",
3668
- " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--acknowledge-access-widening] [--json]",
4474
+ " foleo publish <dir> --accept-hosting-risk --name <label> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--dry-run] [--json]",
4475
+ " foleo update <id> <path> --revision <etag> [--runtime-profile auto|open|contained] [--optimize-images | --no-optimize-images] [--acknowledge-access-widening] [--dry-run] [--json]",
3669
4476
  " foleo update <id> <file.md> --version <version> [--acknowledge-access-widening] [--json] (compatibility)",
4477
+ " Identical updates may return unchanged: true; revision/ETag stay unchanged. Retry an interrupted request with the same idempotency key.",
4478
+ " Shared storage can reuse files from retained versions of the same artifact; legacy storage reuses only its live version.",
3670
4479
  " foleo name-check <label> [--json]",
3671
4480
  " foleo names [--artifact <id>] [--limit <n>] [--cursor <cursor>] [--json]",
3672
4481
  " foleo name attach <id> <label> [--revision <etag>] [--acknowledge-access-widening] [--dry-run] [--json]",
3673
4482
  " foleo name set <id> <label> --previous keep-as-alias|release [--revision <etag>] [--acknowledge-access-widening] [--dry-run] [--json]",
3674
4483
  " foleo name release <id> <label> --acknowledge-link-breakage [--revision <etag>] [--dry-run] [--json]",
3675
- " foleo status <id> [--json]",
4484
+ " foleo status <id> [<path>] [--json]",
4485
+ " foleo get <id> [--source <path>] [--json]",
3676
4486
  " foleo settings <id> [--json]",
3677
4487
  " foleo settings <id> --set k=v [--set k=v ...] [--password-stdin] --revision <etag> [--acknowledge-access-widening] [--json]",
3678
4488
  " foleo limits [--json]",
@@ -3702,6 +4512,12 @@ function help() {
3702
4512
  " The chosen name is the artifact's only address; there is no generated",
3703
4513
  " fallback, and the old generated a-<id> hosts no longer serve.",
3704
4514
  "",
4515
+ " HTML bundles: 300 new files per publish/update, 1,000 total with server reuse.",
4516
+ " Legacy storage copies every file and permits 300 total. See `foleo limits`.",
4517
+ " HTML bundle folders get responsive AVIF copies by default; --no-optimize-images opts out.",
4518
+ " Optimization runs locally; create dry-runs still probe name and access.",
4519
+ " HTML update dry-runs are local bundle plans without network.",
4520
+ " --optimize-images explicitly requires the macOS encoder (fails if unavailable).",
3705
4521
  " --dry-run plans an HTML publish without uploading, creating, or spending",
3706
4522
  " quota. It reports the resolved name and availability, url, title with its",
3707
4523
  " resolvedFrom source, visibility, routes, largestFiles and skipped[], the",
@@ -3730,6 +4546,11 @@ function help() {
3730
4546
  " name-check <label> is free and checks availability without publishing.",
3731
4547
  "",
3732
4548
  "Access control:",
4549
+ " Visibility labels: Private (private), Link (unlisted), Link + password",
4550
+ " (password), Public (public). Private: Only you and your organization.",
4551
+ " settings <id> lists all options; unavailable options are disabled with",
4552
+ " their reason. --json includes visibilityOptions and its widening flags.",
4553
+ " HTML Public is gated by the Public Suffix List (public_publish_gated).",
3733
4554
  " A Markdown document is unlisted (anyone with the link) or private (signed-in",
3734
4555
  " members of your Foleo organization, at the same URL): settings <id> --set",
3735
4556
  " visibility=private|unlisted --revision <etag>. Private to unlisted lets more",