@mediamonks/canopy-cli 0.7.56 → 0.7.58

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.
Files changed (54) hide show
  1. package/dist/{ai-DDVTX_nO.mjs → ai-00f2Mgqh.mjs} +2 -2
  2. package/dist/{api-MIRoGsB6.mjs → api-fmc8CEMT.mjs} +4 -0
  3. package/dist/{audience-8U1dwxcU.mjs → audience-ByM1jUH3.mjs} +2 -2
  4. package/dist/{browse-CVBq2IB4.mjs → browse-CxwKuka0.mjs} +1 -1
  5. package/dist/{calls-Cnt16FiF.mjs → calls-DsbRjCcy.mjs} +2 -2
  6. package/dist/{db-CXeAa-Qy.mjs → db-BU-ni9fj.mjs} +3 -3
  7. package/dist/{deploy-C1mwXvJY.mjs → deploy-k2DzsLxO.mjs} +393 -17
  8. package/dist/dev-BtacZ4HE.mjs +2 -0
  9. package/dist/{dev--vOKyg1k.mjs → dev-qp1VRNM_.mjs} +6 -6
  10. package/dist/docs/cli-deploy.md +20 -3
  11. package/dist/docs/cli-download.md +1 -1
  12. package/dist/docs/cli-promote.md +2 -0
  13. package/dist/docs/cli-rollback.md +3 -1
  14. package/dist/docs/cli-staging.md +2 -0
  15. package/dist/docs/cli-versions.md +79 -0
  16. package/dist/docs/cli.md +2 -0
  17. package/dist/docs/index.json +6 -1
  18. package/dist/docs/platform-deploys-and-rollbacks.md +40 -5
  19. package/dist/docs/platform-project-data.md +7 -0
  20. package/dist/docs/static-serving.md +34 -2
  21. package/dist/{docs-DgMINV-7.mjs → docs-ZBBQi3uK.mjs} +3 -3
  22. package/dist/{egress-Cy3UBgEM.mjs → egress-Bzn2VKDe.mjs} +2 -2
  23. package/dist/{feedback-DymVKtj0.mjs → feedback-B0-6QTSh.mjs} +3 -3
  24. package/dist/{files-CYTMMRC0.mjs → files-CBbAtHIK.mjs} +2 -2
  25. package/dist/index.mjs +38 -37
  26. package/dist/{local-DCo1A00D.mjs → local-C1i2uhAf.mjs} +2 -2
  27. package/dist/{login-BpmefYHv.mjs → login-Baso-JE0.mjs} +2 -2
  28. package/dist/{logs-CWr7tRhN.mjs → logs-c76jVOhb.mjs} +2 -2
  29. package/dist/{mcp-D0TZcRce.mjs → mcp-DmcjX8Kn.mjs} +2 -2
  30. package/dist/{migrations-CkGa1pmn.mjs → migrations-ChafLorm.mjs} +1 -1
  31. package/dist/{open-D2WqNBiq.mjs → open-Doat726T.mjs} +1 -1
  32. package/dist/{package-BpSdSdZI.mjs → package-BzvVsyRl.mjs} +1 -1
  33. package/dist/project-template--mESzwea.mjs +2 -0
  34. package/dist/{project-template-DjbT9RRU.mjs → project-template-BnX47DpF.mjs} +2 -2
  35. package/dist/{projects-Dcq37hny.mjs → projects-DOqpkUVT.mjs} +4 -4
  36. package/dist/{rename-DTg_3_BJ.mjs → rename-RA_oYbRT.mjs} +2 -2
  37. package/dist/{repo-ZjkxQKwh.mjs → repo-DD3eK1P_.mjs} +2 -2
  38. package/dist/repo-DayXVvyj.mjs +2 -0
  39. package/dist/{roles-2dF7LkZB.mjs → roles-BS8-Gvv-.mjs} +2 -2
  40. package/dist/{roles-B5E2tfbN.mjs → roles-tqf4sYDM.mjs} +1 -1
  41. package/dist/{schedule-_u2Ab1WH.mjs → schedule-D8AQ8MVF.mjs} +2 -2
  42. package/dist/{secrets-H1bQRNBr.mjs → secrets-Bi7BYCla.mjs} +2 -2
  43. package/dist/skill/canopy/SKILL.md +8 -0
  44. package/dist/{skill-BHDQdPTC.mjs → skill-k3HLr7rK.mjs} +2 -2
  45. package/dist/{staging-BZJwA_iG.mjs → staging-BxG3Cffd.mjs} +2 -2
  46. package/dist/{token-BEV5lbld.mjs → token-bHdy_IoX.mjs} +2 -2
  47. package/dist/{ui-7cyGNbu5.mjs → ui-9f_lF2Ak.mjs} +1 -1
  48. package/dist/{upgrade-BYTMPnOF.mjs → upgrade-DkjbsYNs.mjs} +2 -2
  49. package/dist/{usage-iYp64st3.mjs → usage-DFs2TERV.mjs} +2 -2
  50. package/dist/versions-Cgw7sB3h.mjs +106 -0
  51. package/package.json +1 -1
  52. package/dist/dev-CCMeTwvP.mjs +0 -2
  53. package/dist/project-template-D-e33lix.mjs +0 -2
  54. package/dist/repo-C_gmPkLX.mjs +0 -2
@@ -1,5 +1,5 @@
1
- import { a as apiRequest, m as withContext } from "./api-MIRoGsB6.mjs";
2
- import { i as reportErrors } from "./ui-7cyGNbu5.mjs";
1
+ import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
2
+ import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  //#region src/ai.ts
5
5
  /**
@@ -226,6 +226,10 @@ const ERROR_COPY = {
226
226
  why: "branches are full git refs, and the staging branch must differ from the live one",
227
227
  fix: "Pass e.g. `--ref refs/heads/main --staging-ref refs/heads/develop`."
228
228
  },
229
+ version_expired: {
230
+ why: "version retention expired that version: its files are gone, so it can no longer be made live, staged, pinned or downloaded",
231
+ fix: "Pick a version that is still kept (`canopy versions` shows how many are), or rebuild it from source and deploy."
232
+ },
229
233
  slug_unchanged: {
230
234
  why: "the project already has that slug",
231
235
  fix: "Pass the new slug you want, e.g. `canopy rename my-new-name`."
@@ -1,6 +1,6 @@
1
1
  import { f as resolveProject, l as projectDirArgs, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-MIRoGsB6.mjs";
3
- import { i as reportErrors } from "./ui-7cyGNbu5.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
+ import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/audience.ts
@@ -1,5 +1,5 @@
1
1
  import { g as tryResolveProject, r as siteConfig } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, t as ApiError } from "./api-MIRoGsB6.mjs";
2
+ import { a as apiRequest, t as ApiError } from "./api-fmc8CEMT.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  //#region src/browse.ts
5
5
  /**
@@ -1,6 +1,6 @@
1
1
  import { f as resolveProject, l as projectDirArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-MIRoGsB6.mjs";
3
- import { i as reportErrors, n as formatDateTime } from "./ui-7cyGNbu5.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
+ import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/calls.ts
6
6
  /**
@@ -1,7 +1,7 @@
1
1
  import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext, r as apiDataRequest } from "./api-MIRoGsB6.mjs";
3
- import { a as requireTty, i as reportErrors, o as spinner$1, s as unwrap, t as confirmTypedSlug } from "./ui-7cyGNbu5.mjs";
4
- import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-CkGa1pmn.mjs";
2
+ import { a as apiRequest, m as withContext, r as apiDataRequest } from "./api-fmc8CEMT.mjs";
3
+ import { a as requireTty, i as reportErrors, o as spinner$1, s as unwrap, t as confirmTypedSlug } from "./ui-9f_lF2Ak.mjs";
4
+ import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-ChafLorm.mjs";
5
5
  import { defineCommand } from "citty";
6
6
  import { readFileSync, writeFileSync } from "node:fs";
7
7
  import * as p from "@clack/prompts";
@@ -1,7 +1,7 @@
1
1
  import { d as projectUrl, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, m as stagingUrl, r as siteConfig, s as parseVersionArg, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, d as githubActionsCredentials, i as apiDownload, l as currentSlug, m as withContext, p as onGithubActions, r as apiDataRequest, t as ApiError } from "./api-MIRoGsB6.mjs";
3
- import { i as reportErrors, n as formatDateTime, o as spinner$1, s as unwrap } from "./ui-7cyGNbu5.mjs";
4
- import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-CkGa1pmn.mjs";
2
+ import { a as apiRequest, d as githubActionsCredentials, i as apiDownload, l as currentSlug, m as withContext, p as onGithubActions, r as apiDataRequest, t as ApiError } from "./api-fmc8CEMT.mjs";
3
+ import { i as reportErrors, n as formatDateTime, o as spinner$1, s as unwrap } from "./ui-9f_lF2Ak.mjs";
4
+ import { n as migrateProject, r as readMigrationFiles, t as describeMigrateResult } from "./migrations-ChafLorm.mjs";
5
5
  import { builtinModules } from "node:module";
6
6
  import { defineCommand } from "citty";
7
7
  import { mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -10,6 +10,7 @@ import { join, relative, resolve } from "node:path";
10
10
  import { spawn } from "node:child_process";
11
11
  import * as p from "@clack/prompts";
12
12
  import * as esbuild from "esbuild";
13
+ import { createHash } from "node:crypto";
13
14
  //#region src/worker-bundle.ts
14
15
  /**
15
16
  * Bundle a project's `worker/` entry for deploy (G6).
@@ -149,6 +150,244 @@ const nodeBuiltins = {
149
150
  }
150
151
  };
151
152
  //#endregion
153
+ //#region src/media.ts
154
+ /**
155
+ * Site media for `canopy deploy` (OpenSpec site-media): folders of the build
156
+ * output, declared in canopy.json (`"media": ["mocks/"]`), that are stored once
157
+ * per project instead of in every version and served on the same URLs.
158
+ *
159
+ * Pure helpers here (rules, the split, suggestions, messages); the deploy
160
+ * command does the network part. The rules mirror the server's
161
+ * (apps/api/src/site-media.ts); the server stays authoritative.
162
+ */
163
+ /** Extensions site media may hold: data and media, never code. */
164
+ const MEDIA_EXTENSIONS = /* @__PURE__ */ new Set([
165
+ "json",
166
+ "csv",
167
+ "txt",
168
+ "png",
169
+ "jpg",
170
+ "jpeg",
171
+ "gif",
172
+ "webp",
173
+ "avif",
174
+ "ico",
175
+ "mp4",
176
+ "webm",
177
+ "mp3",
178
+ "wav",
179
+ "ogg",
180
+ "m4a",
181
+ "woff",
182
+ "woff2",
183
+ "glb",
184
+ "gltf",
185
+ "bin"
186
+ ]);
187
+ function isMediaFile(path) {
188
+ const file = path.split("/").at(-1) ?? "";
189
+ const dot = file.lastIndexOf(".");
190
+ return dot > 0 && MEDIA_EXTENSIONS.has(file.slice(dot + 1).toLowerCase());
191
+ }
192
+ /**
193
+ * Build output with a content hash in its name (Vite's `name-<8 chars>.ext`),
194
+ * same rule as the server's cache headers: such names change on every build,
195
+ * so they pile up in an additive store.
196
+ */
197
+ function looksHashed(path) {
198
+ const file = path.split("/").at(-1) ?? "";
199
+ const match = /-([A-Za-z0-9_-]{8})\.[A-Za-z0-9]+(?:\.map)?$/.exec(file);
200
+ return match !== null && /[0-9A-Z_-]/.test(match[1] ?? "");
201
+ }
202
+ /** canopy.json `media`, normalized like the server does it; throws on a bad entry. */
203
+ function normalizeMediaFolders(raw) {
204
+ if (raw === void 0 || raw === null) return [];
205
+ if (!Array.isArray(raw) || !raw.every((e) => typeof e === "string")) throw new Error("canopy.json \"media\" must be a list of folders, e.g. [\"mocks/\"].");
206
+ const cleaned = raw.map((entry) => {
207
+ const trimmed = entry.trim().replace(/^\.?\//, "").replace(/\/+$/, "");
208
+ if (trimmed === "" || trimmed.includes("\\") || trimmed.includes("\0") || trimmed.includes("//") || trimmed.split("/").some((seg) => seg === "" || seg === "." || seg === "..")) throw new Error(`canopy.json "media": "${entry}" is not a folder inside the build output (the root can't be media).`);
209
+ return `${trimmed}/`;
210
+ });
211
+ const unique = [...new Set(cleaned)].sort();
212
+ const folders = unique.filter((f) => !unique.some((g) => g !== f && f.startsWith(g)));
213
+ if (folders.length > 10) throw new Error(`canopy.json "media" lists ${folders.length} folders; the limit is 10.`);
214
+ return folders;
215
+ }
216
+ /** Version files and media files, by the declared folders. */
217
+ function splitMedia(files, folders) {
218
+ const bundle = [];
219
+ const media = [];
220
+ for (const file of files) (folders.some((f) => file.path.startsWith(f)) ? media : bundle).push(file);
221
+ return {
222
+ bundle,
223
+ media
224
+ };
225
+ }
226
+ const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
227
+ /**
228
+ * Folders that could be site media: the topmost folders (not the output root,
229
+ * not already declared) whose files are all data or media, at least 1 MB, and
230
+ * mostly not content-hashed build output. Largest first.
231
+ */
232
+ function mediaCandidates(files, declared = []) {
233
+ const stats = /* @__PURE__ */ new Map();
234
+ for (const file of files) {
235
+ const parts = file.path.split("/");
236
+ const ext = (parts.at(-1)?.split(".").at(-1) ?? "").toLowerCase();
237
+ for (let depth = 1; depth < parts.length; depth++) {
238
+ const folder = `${parts.slice(0, depth).join("/")}/`;
239
+ const s = stats.get(folder) ?? {
240
+ bytes: 0,
241
+ files: 0,
242
+ allMedia: true,
243
+ hashed: 0,
244
+ types: /* @__PURE__ */ new Set()
245
+ };
246
+ s.bytes += file.size;
247
+ s.files += 1;
248
+ s.allMedia &&= isMediaFile(file.path);
249
+ if (looksHashed(file.path)) s.hashed += 1;
250
+ s.types.add(ext);
251
+ stats.set(folder, s);
252
+ }
253
+ }
254
+ const qualifies = (folder) => {
255
+ const s = stats.get(folder);
256
+ return s !== void 0 && s.allMedia && s.bytes >= 1048576 && s.hashed * 2 < s.files && !declared.some((d) => folder.startsWith(d) || d.startsWith(folder));
257
+ };
258
+ const out = [];
259
+ for (const [folder, s] of stats) {
260
+ if (!qualifies(folder)) continue;
261
+ const parent = folder.slice(0, folder.slice(0, -1).lastIndexOf("/") + 1);
262
+ if (parent !== "" && qualifies(parent)) continue;
263
+ out.push({
264
+ folder,
265
+ bytes: s.bytes,
266
+ files: s.files,
267
+ types: [...s.types].sort()
268
+ });
269
+ }
270
+ return out.sort((a, b) => b.bytes - a.bytes || a.folder.localeCompare(b.folder));
271
+ }
272
+ /**
273
+ * The fewest of the largest candidates that bring the version under both
274
+ * limits, or null when even all of them are not enough.
275
+ */
276
+ function candidatesToFit(candidates, version, limits) {
277
+ const fits = (bytes, count) => (limits.maxTotalBytes === void 0 || bytes <= limits.maxTotalBytes) && (limits.maxFiles === void 0 || count <= limits.maxFiles);
278
+ let { bytes, files } = version;
279
+ const picked = [];
280
+ for (const candidate of candidates) {
281
+ if (fits(bytes, files)) break;
282
+ picked.push(candidate);
283
+ bytes -= candidate.bytes;
284
+ files -= candidate.files;
285
+ }
286
+ return fits(bytes, files) ? picked : null;
287
+ }
288
+ const formatSize = (bytes) => bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : bytes >= 1024 ** 2 ? `${(bytes / 1024 ** 2).toFixed(1)} MB` : `${Math.max(0, Math.round(bytes / 1024))} kB`;
289
+ /** The sentence every media suggestion carries, so an agent weighs it. */
290
+ const NOT_VERSIONED = "Media is not versioned: rollbacks and pinned versions serve the current files.";
291
+ /** The `canopy.json` snippet that declares `folders` (plus any already declared). */
292
+ function mediaSnippet(folders, declared = []) {
293
+ return `"media": ${JSON.stringify([...declared, ...folders])}`;
294
+ }
295
+ /** Lines naming the candidates: folder, size, files, types. */
296
+ function describeCandidates(candidates) {
297
+ const width = Math.max(...candidates.map((c) => c.folder.length));
298
+ return candidates.map((c) => ` ${c.folder.padEnd(width)} ${formatSize(c.bytes).padStart(9)} ${String(c.files).padStart(5)} files ${c.types.join(", ")}`);
299
+ }
300
+ /**
301
+ * The soft hint: the version has reached SUGGEST_AT_SHARE of a limit and
302
+ * there are folders that could move out of it. Null otherwise.
303
+ */
304
+ function mediaHint(candidates, version, limits, declared = []) {
305
+ if (candidates.length === 0) return null;
306
+ const share = Math.max(limits.maxTotalBytes ? version.bytes / limits.maxTotalBytes : 0, limits.maxFiles ? version.files / limits.maxFiles : 0);
307
+ if (share < .3) return null;
308
+ return [
309
+ ` hint: this version is ${formatSize(version.bytes)} in ${version.files} files (${Math.round(share * 100)}% of the deploy limit).`,
310
+ " These folders could be site media (stored once, not part of every version):",
311
+ ...describeCandidates(candidates),
312
+ ` Add to canopy.json: ${mediaSnippet(candidates.map((c) => c.folder), declared)}`,
313
+ ` ${NOT_VERSIONED}`
314
+ ].join("\n");
315
+ }
316
+ /** Text added to the over-limit refusal: what to move, or why moving won't do. */
317
+ function overLimitAdvice(candidates, version, limits, declared = []) {
318
+ if (candidates.length === 0) return "Bundle/minify assets or drop what isn't served, then redeploy.";
319
+ const picked = candidatesToFit(candidates, version, limits);
320
+ if (!picked) return [
321
+ "Even moving every data and media folder to site media would not bring it under the limit:",
322
+ ...describeCandidates(candidates),
323
+ "Bundle/minify assets or drop what isn't served, then redeploy."
324
+ ].join("\n");
325
+ return [
326
+ "Move these folders to site media (stored once, not part of every version):",
327
+ ...describeCandidates(picked),
328
+ `Add to canopy.json: ${mediaSnippet(picked.map((c) => c.folder), declared)}`,
329
+ NOT_VERSIONED
330
+ ].join("\n");
331
+ }
332
+ /** What to upload and what it adds up to, against the stored manifest. */
333
+ function planMedia(local, manifest, opts) {
334
+ const stored = new Map(manifest.map((f) => [f.path, f]));
335
+ const localPaths = new Set(local.map((f) => f.path));
336
+ const upload = [];
337
+ const blocked = [];
338
+ let unchanged = 0;
339
+ for (const file of local) {
340
+ const sha256 = sha256Hex(file.data);
341
+ const remote = stored.get(file.path);
342
+ if (remote?.sha256 === sha256) unchanged++;
343
+ else if (remote && opts.createOnly) blocked.push(file.path);
344
+ else upload.push({
345
+ ...file,
346
+ sha256
347
+ });
348
+ }
349
+ const stale = manifest.filter((f) => !localPaths.has(f.path)).map((f) => f.path);
350
+ const prunes = opts.prune && !opts.createOnly;
351
+ let bytes = 0;
352
+ let files = 0;
353
+ for (const remote of manifest) {
354
+ if (prunes && !localPaths.has(remote.path)) continue;
355
+ const replacing = upload.find((u) => u.path === remote.path);
356
+ bytes += replacing ? replacing.data.byteLength : remote.size;
357
+ files += 1;
358
+ }
359
+ for (const u of upload) if (!stored.has(u.path)) {
360
+ bytes += u.data.byteLength;
361
+ files += 1;
362
+ }
363
+ return {
364
+ upload,
365
+ unchanged,
366
+ stale,
367
+ blocked,
368
+ projectedBytes: bytes,
369
+ projectedFiles: files
370
+ };
371
+ }
372
+ /** Why the media plan breaks the limits, or null. */
373
+ function mediaLimitError(plan, limits) {
374
+ const big = plan.upload.find((f) => f.data.byteLength > limits.maxFileBytes);
375
+ if (big) return `Site media file ${big.path} is ${formatSize(big.data.byteLength)}; one file may be at most ${formatSize(limits.maxFileBytes)} on this site.`;
376
+ if (plan.projectedFiles > limits.maxFiles) return `Site media would hold ${plan.projectedFiles} files; the limit is ${limits.maxFiles}. Drop files or run with --prune-media to remove stored ones that are gone locally.`;
377
+ if (plan.projectedBytes > limits.maxBytes) return `Site media would hold ${formatSize(plan.projectedBytes)}; this project's limit is ${formatSize(limits.maxBytes)}. Run with --prune-media to remove stored files that are gone locally, or ask a Canopy admin to raise it.`;
378
+ return null;
379
+ }
380
+ /** The lines a deploy prints about its media sync. */
381
+ function describeMediaSync(plan, pruned, opts) {
382
+ const kept = plan.projectedBytes;
383
+ const lines = [` media: ${plan.upload.length} uploaded, ${plan.unchanged} unchanged, ${formatSize(kept)} stored`];
384
+ if (plan.blocked.length > 0) lines.push(` ${plan.blocked.length} changed media files were not replaced: this token deploys only to staging, and media is shared with live:`, ...plan.blocked.slice(0, 10).map((path) => ` ${path}`));
385
+ if (pruned.length > 0) lines.push(` pruned ${pruned.length} stored media files no longer in the build:`, ...pruned.slice(0, 20).map((path) => ` ${path}`), ...pruned.length > 20 ? [` … and ${pruned.length - 20} more`] : []);
386
+ else if (!opts.prune && plan.stale.length > 0) lines.push(` ${plan.stale.length} stored media files are no longer in the build; --prune-media removes them.`);
387
+ else if (opts.prune && opts.createOnly && plan.stale.length > 0) lines.push(" --prune-media skipped: this token deploys only to staging and can't delete media.");
388
+ return lines;
389
+ }
390
+ //#endregion
152
391
  //#region src/deploy.ts
153
392
  /**
154
393
  * canopy deploy — build (optional), then the signed-upload flow
@@ -226,6 +465,11 @@ const deployCommand = defineCommand({
226
465
  default: false,
227
466
  description: "Deploy to the project's staging channel (created on first use, database cloned from live)"
228
467
  },
468
+ "prune-media": {
469
+ type: "boolean",
470
+ default: false,
471
+ description: "Delete stored site media files that are no longer in the build (canopy.json media)"
472
+ },
229
473
  worker: {
230
474
  type: "boolean",
231
475
  default: true,
@@ -271,6 +515,25 @@ const deployCommand = defineCommand({
271
515
  data
272
516
  });
273
517
  }
518
+ const mediaFolders = normalizeMediaFolders(config.media);
519
+ const { bundle, media } = splitMedia(files, mediaFolders);
520
+ for (const folder of mediaFolders) if (!media.some((f) => f.path.startsWith(folder))) p.log.warn(`canopy.json "media": ${folder} is not in the build output; nothing to upload from it.`);
521
+ const notMedia = media.filter((f) => !isMediaFile(f.path)).map((f) => f.path);
522
+ if (notMedia.length > 0) throw new Error([
523
+ "Site media holds data and media files only (JSON, CSV, text, images, video, audio, fonts, 3D models). These can't be media:",
524
+ ...notMedia.slice(0, 20).map((path) => ` ${path}`),
525
+ ...notMedia.length > 20 ? [` … and ${notMedia.length - 20} more`] : [],
526
+ "Move them out of the media folders, or take the folder out of canopy.json \"media\"."
527
+ ].join("\n"));
528
+ for (const folder of mediaFolders) {
529
+ const inFolder = media.filter((f) => f.path.startsWith(folder));
530
+ if (inFolder.length > 0 && inFolder.filter((f) => looksHashed(f.path)).length * 2 >= inFolder.length) p.log.warn(`${folder} holds mostly content-hashed build output. Their names change on every build, and site media keeps old files until you deploy with --prune-media.`);
531
+ }
532
+ const bundleBytes = bundle.reduce((sum, f) => sum + f.data.byteLength, 0);
533
+ const candidates = mediaCandidates(bundle.map((f) => ({
534
+ path: f.path,
535
+ size: f.data.byteLength
536
+ })), mediaFolders);
274
537
  let workerBytes = null;
275
538
  if (config.worker && !args.worker) p.log.warn(`Skipping the backend (${config.worker}) — deploying the frontend only.`);
276
539
  if (config.worker && args.worker) {
@@ -289,22 +552,64 @@ const deployCommand = defineCommand({
289
552
  const spin = spinner$1();
290
553
  const workerNote = workerBytes ? " + worker" : "";
291
554
  const channelNote = channel === "staging" ? " [staging]" : "";
292
- spin.start(`Deploying ${files.length} files${workerNote} (${(total / 1024).toFixed(0)} kB) → ${slug}${channelNote}`);
555
+ const mediaNote = media.length > 0 ? ` + ${media.length} media files (${formatSize(total - bundleBytes - (workerBytes?.byteLength ?? 0))})` : "";
556
+ spin.start(`Deploying ${bundle.length} files${workerNote} (${(bundleBytes / 1024).toFixed(0)} kB)${mediaNote} → ${slug}${channelNote}`);
557
+ let mediaReport = [];
293
558
  let result;
294
559
  let migrateResult;
295
560
  let stagingCreated = false;
561
+ let retentionHint = null;
562
+ let limitsSeen = {};
296
563
  try {
297
- const { upload } = await withContext(apiRequest("POST", `/projects/${slug}/deploys`, {
564
+ const { upload, retention } = await withContext(apiRequest("POST", `/projects/${slug}/deploys`, {
298
565
  worker: workerBytes !== null,
299
- channel
566
+ channel,
567
+ ...mediaFolders.length > 0 && { media: mediaFolders }
300
568
  }, { headers: source }), { action: `deploy "${slug}"` });
301
569
  stagingCreated = upload.stagingCreated === true;
302
- const overLimit = bundleLimitError(files, upload);
570
+ limitsSeen = {
571
+ maxTotalBytes: upload.maxTotalBytes,
572
+ maxFiles: upload.maxFiles
573
+ };
574
+ retentionHint = retentionHintLine(retention);
575
+ const overLimit = bundleLimitError(bundle, upload);
303
576
  if (overLimit) {
304
577
  spin.error("Deploy refused — nothing was uploaded.");
305
- throw new Error(overLimit);
578
+ throw new Error(`${overLimit}\n${overLimitAdvice(candidates, {
579
+ bytes: bundleBytes,
580
+ files: bundle.length
581
+ }, upload, mediaFolders)}`);
582
+ }
583
+ if (mediaFolders.length > 0 && !upload.media) {
584
+ spin.error("Deploy refused — nothing was uploaded.");
585
+ throw new Error("This site doesn't support site media yet. Take \"media\" out of canopy.json to deploy those folders as part of the version.");
586
+ }
587
+ if (upload.media) {
588
+ spin.message(`Checking site media → ${slug}`);
589
+ const plan = planMedia(media, (await mediaManifest(upload.grant)).files, {
590
+ prune: args["prune-media"],
591
+ createOnly: upload.media.createOnly
592
+ });
593
+ const mediaError = mediaLimitError(plan, upload.media);
594
+ if (mediaError) {
595
+ spin.error("Deploy refused — nothing was uploaded.");
596
+ throw new Error(mediaError);
597
+ }
598
+ if (plan.upload.length > 0) {
599
+ spin.message(`Uploading ${plan.upload.length} site media files (${formatSize(plan.upload.reduce((n, f) => n + f.data.byteLength, 0))}) → ${slug}`);
600
+ await uploadMedia(upload.grant, plan.upload);
601
+ }
602
+ let pruned = [];
603
+ if (args["prune-media"] && plan.stale.length > 0 && !upload.media.createOnly) {
604
+ await deleteMedia(upload.grant, plan.stale);
605
+ pruned = plan.stale;
606
+ }
607
+ mediaReport = describeMediaSync(plan, pruned, {
608
+ prune: args["prune-media"],
609
+ createOnly: upload.media.createOnly
610
+ });
306
611
  }
307
- const uploads = [...files, ...workerBytes ? [{
612
+ const uploads = [...bundle, ...workerBytes ? [{
308
613
  path: WORKER_BUNDLE_PATH,
309
614
  data: workerBytes
310
615
  }] : []];
@@ -333,8 +638,26 @@ const deployCommand = defineCommand({
333
638
  console.log(` happy with it? \`canopy promote\` makes v${result.version} live`);
334
639
  } else spin.stop(`Live: ${projectUrl(currentSlug(slug))} (v${result.version})${backend}`);
335
640
  if (migrateResult !== void 0) for (const line of describeMigrateResult(migrateResult)) console.log(` ${line}`);
641
+ for (const line of mediaReport) console.log(line);
642
+ const hint = mediaHint(candidates, {
643
+ bytes: bundleBytes,
644
+ files: bundle.length
645
+ }, {
646
+ maxTotalBytes: limitsSeen.maxTotalBytes,
647
+ maxFiles: limitsSeen.maxFiles
648
+ }, mediaFolders);
649
+ if (hint) console.log(`\n${hint}`);
650
+ if (retentionHint) console.log(`\n${retentionHint}`);
336
651
  })
337
652
  });
653
+ /**
654
+ * The retention hint a deploy prints when the platform sends one: a project
655
+ * without version retention that has grown large (deploy-retention). One
656
+ * block, worded so an agent reading the output can pass it on.
657
+ */
658
+ function retentionHintLine(retention) {
659
+ return retention?.hint ? ` hint: ${retention.hint}` : null;
660
+ }
338
661
  const promoteCommand = defineCommand({
339
662
  meta: {
340
663
  name: "promote",
@@ -395,11 +718,11 @@ const UPLOAD_CONCURRENCY = 8;
395
718
  * that states no limits isn't checked here; completion still enforces them.
396
719
  */
397
720
  function bundleLimitError(files, limits) {
398
- if (limits.maxFiles !== void 0 && files.length > limits.maxFiles) return `This deploy has ${files.length} files; the limit is ${limits.maxFiles}. Bundle/minify assets or drop what isn't served, then redeploy.`;
721
+ if (limits.maxFiles !== void 0 && files.length > limits.maxFiles) return `This deploy has ${files.length} files; the limit is ${limits.maxFiles}.`;
399
722
  const bytes = files.reduce((sum, f) => sum + f.data.byteLength, 0);
400
723
  if (limits.maxTotalBytes !== void 0 && bytes > limits.maxTotalBytes) {
401
724
  const mb = (n) => `${(n / 1024 / 1024).toFixed(1)} MB`;
402
- return `This deploy is ${mb(bytes)}; the limit is ${mb(limits.maxTotalBytes)}. Move large images or fonts to file storage, then redeploy.`;
725
+ return `This deploy is ${mb(bytes)}; the limit is ${mb(limits.maxTotalBytes)}.`;
403
726
  }
404
727
  return null;
405
728
  }
@@ -440,17 +763,36 @@ function skipMessage(code, slug) {
440
763
  const host = server ? new URL(server).host : void 0;
441
764
  return `"${slug}" is not linked to this repository, so this run deployed nothing. The project owner can link it with \`canopy repo link ${repo ? `${host && host !== "github.com" ? `${host}/` : ""}${repo}` : "<owner/name>"}\`, or set a CANOPY_DEPLOY_TOKEN secret.`;
442
765
  }
766
+ const PUT_ATTEMPTS = 3;
767
+ /**
768
+ * One upload PUT, tried again when the connection drops. Node's fetch speaks
769
+ * HTTP/2 to the edge, and with several uploads in flight a stream is now and
770
+ * then reset (ERR_HTTP2_STREAM_ERROR) on a different file each time. An HTTP
771
+ * answer, refusal or not, is returned as is: only network failures retry.
772
+ * Re-sending is safe: an upload replaces the same key with the same bytes.
773
+ */
774
+ async function putWithRetry(url, headers, data, what) {
775
+ for (let attempt = 1;; attempt++) try {
776
+ return await fetch(url, {
777
+ method: "PUT",
778
+ headers,
779
+ body: Buffer.from(data)
780
+ });
781
+ } catch (err) {
782
+ if (attempt >= PUT_ATTEMPTS) {
783
+ const cause = err.cause;
784
+ throw new Error(`${what} failed after ${PUT_ATTEMPTS} tries: ${cause?.code ?? cause?.message ?? err.message}.`);
785
+ }
786
+ await new Promise((resolve) => setTimeout(resolve, 500 * attempt));
787
+ }
788
+ }
443
789
  /** PUT each file to /data/v1/uploads/<grant> — the grant is the credential. */
444
790
  async function uploadFiles(grant, files) {
445
791
  const { apiUrl } = siteConfig();
446
792
  const queue = [...files];
447
793
  async function worker() {
448
794
  for (let file = queue.shift(); file; file = queue.shift()) {
449
- const url = `${apiUrl}/data/v1/uploads/${encodeURIComponent(grant)}?path=${encodeURIComponent(file.path)}`;
450
- const res = await fetch(url, {
451
- method: "PUT",
452
- body: Buffer.from(file.data)
453
- });
795
+ const res = await putWithRetry(`${apiUrl}/data/v1/uploads/${encodeURIComponent(grant)}?path=${encodeURIComponent(file.path)}`, {}, file.data, `Upload of ${file.path}`);
454
796
  if (!res.ok) {
455
797
  const payload = await res.json().catch(() => ({}));
456
798
  throw new Error(`Upload of ${file.path} failed (HTTP ${res.status}${payload.error ? `, ${payload.error}` : ""}).`);
@@ -459,11 +801,45 @@ async function uploadFiles(grant, files) {
459
801
  }
460
802
  await Promise.all(Array.from({ length: UPLOAD_CONCURRENCY }, worker));
461
803
  }
804
+ /** The project's stored media, under the deploy's grant. */
805
+ async function mediaManifest(grant) {
806
+ const { apiUrl } = siteConfig();
807
+ const res = await fetch(`${apiUrl}/data/v1/media/${encodeURIComponent(grant)}/manifest`);
808
+ if (!res.ok) throw new Error(`Reading the site media manifest failed (HTTP ${res.status}).`);
809
+ return await res.json();
810
+ }
811
+ /** PUT each new or changed media file with its hash; the store refuses a mismatch. */
812
+ async function uploadMedia(grant, files) {
813
+ const { apiUrl } = siteConfig();
814
+ const queue = [...files];
815
+ async function worker() {
816
+ for (let file = queue.shift(); file; file = queue.shift()) {
817
+ const res = await putWithRetry(`${apiUrl}/data/v1/media/${encodeURIComponent(grant)}?path=${encodeURIComponent(file.path)}`, { "x-canopy-sha256": file.sha256 }, file.data, `Site media upload of ${file.path} (${formatSize(file.data.byteLength)})`);
818
+ if (!res.ok) {
819
+ const payload = await res.json().catch(() => ({}));
820
+ throw new Error(`Site media upload of ${file.path} failed (HTTP ${res.status}${payload.error ? `, ${payload.error}` : ""})${payload.detail ? `: ${payload.detail}` : "."}`);
821
+ }
822
+ }
823
+ }
824
+ await Promise.all(Array.from({ length: UPLOAD_CONCURRENCY }, worker));
825
+ }
826
+ /** --prune-media: delete stored media that's gone from the build, 1000 per call. */
827
+ async function deleteMedia(grant, paths) {
828
+ const { apiUrl } = siteConfig();
829
+ for (let i = 0; i < paths.length; i += 1e3) {
830
+ const res = await fetch(`${apiUrl}/data/v1/media/${encodeURIComponent(grant)}/delete`, {
831
+ method: "POST",
832
+ headers: { "content-type": "application/json" },
833
+ body: JSON.stringify({ paths: paths.slice(i, i + 1e3) })
834
+ });
835
+ if (!res.ok) throw new Error(`Pruning site media failed (HTTP ${res.status}).`);
836
+ }
837
+ }
462
838
  /** Show the deploy history and ask which version to act on. */
463
839
  async function pickVersion(deploys, live, message, initial) {
464
840
  return unwrap(await p.select({
465
841
  message,
466
- options: deploys.map((deploy) => ({
842
+ options: deploys.filter((deploy) => !deploy.expired).map((deploy) => ({
467
843
  value: deploy.version,
468
844
  label: `v${deploy.version} ${formatDateTime(deploy.created_at)} (${deploy.source})`,
469
845
  hint: deploy.version === live ? "live" : void 0
@@ -0,0 +1,2 @@
1
+ import { n as devCommand } from "./dev-qp1VRNM_.mjs";
2
+ export { devCommand };
@@ -1,9 +1,9 @@
1
1
  import { c as projectDialect, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, r as siteConfig } from "./site-BcZ0LOvm.mjs";
2
2
  import { r as stampWorkerHeaders, t as WORKER_ATTEST_HEADER } from "./src-DpjA-a59.mjs";
3
- import { a as apiRequest, m as withContext, t as ApiError } from "./api-MIRoGsB6.mjs";
4
- import { i as reportErrors, n as formatDateTime } from "./ui-7cyGNbu5.mjs";
5
- import { r as readMigrationFiles } from "./migrations-CkGa1pmn.mjs";
6
- import { s as parseAppRoleFlag } from "./roles-2dF7LkZB.mjs";
3
+ import { a as apiRequest, m as withContext, t as ApiError } from "./api-fmc8CEMT.mjs";
4
+ import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
5
+ import { r as readMigrationFiles } from "./migrations-ChafLorm.mjs";
6
+ import { s as parseAppRoleFlag } from "./roles-BS8-Gvv-.mjs";
7
7
  import { n as writeDevServerRecord } from "./dev-server-file-Dk9pk4AR.mjs";
8
8
  import { createRequire } from "node:module";
9
9
  import { defineCommand } from "citty";
@@ -326,7 +326,7 @@ async function devRemote(flags, slug) {
326
326
  async function devLocal(flags, slug) {
327
327
  let dump;
328
328
  if (flags.pull) {
329
- const { fetchProjectDump } = await import("./local-DCo1A00D.mjs");
329
+ const { fetchProjectDump } = await import("./local-C1i2uhAf.mjs");
330
330
  console.log(`Pulling a fresh export of ${slug}${flags.staging ? " [staging]" : ""}…`);
331
331
  dump = await fetchProjectDump(slug, flags.staging ? "staging" : "live");
332
332
  }
@@ -343,7 +343,7 @@ async function devLocal(flags, slug) {
343
343
  }
344
344
  const workerAttest = randomBytes(24).toString("base64url");
345
345
  const devRoles = await resolveDevRoles(slug, flags.asRoles);
346
- const { createSandbox } = await import("./local-DCo1A00D.mjs");
346
+ const { createSandbox } = await import("./local-C1i2uhAf.mjs");
347
347
  const sandbox = await createSandbox({
348
348
  slug,
349
349
  persistDir: join(flags.dir, ".canopy", "local"),
@@ -20,6 +20,7 @@ canopy deploy --project my-app ./out
20
20
  - `--build` / `--no-build` — run the `canopy.json` build command first (default on). Use `--no-build` when the output is already built, e.g. a CI step that built earlier.
21
21
  - `--migrate` / `--no-migrate` — apply pending schema migrations before the new version goes live (default on; only does anything when `canopy.json` configures a `"migrations"` directory — see the [migrations guide](https://docs.canopy.website/guides/migrations)).
22
22
  - `--staging` — deploy to the project's [staging channel](https://docs.canopy.website/guides/staging) instead of live: created on first use with a copy of the live database, served at `staging-dot-<slug>`, promoted with [canopy promote](https://docs.canopy.website/cli/promote). Pending migrations apply to the _staging_ database (the rehearsal). Not to be confused with `--profile staging`, which picks a whole different site.
23
+ - `--prune-media` — delete stored [site media](https://docs.canopy.website/guides/static-serving#site-media) files that are no longer in the build, including folders you took out of `canopy.json`. Without it, site media only grows. The CLI prints how many it removed and which.
23
24
  - `--profile <site>` / `CANOPY_PROFILE` — which site to deploy to (`main`, `staging`, …). Always pass it explicitly when the target matters; a `canopy.json` profile pin is the fallback.
24
25
 
25
26
  ## How it works
@@ -27,12 +28,28 @@ canopy deploy --project my-app ./out
27
28
  1. **Build.** If `canopy.json` has a `build` command and you didn't pass `--no-build`, it runs in the project directory with your shell; a non-zero exit aborts the deploy.
28
29
  2. **Collect files.** Everything under the `dist` directory from `canopy.json` (default: the project directory itself) is gathered, skipping `canopy.json`, `README.md`, `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.DS_Store`, and any dot-directories plus `.git`, `node_modules`, and `.claude`. An empty or missing output directory is an error.
29
30
  3. **Bundle the backend (if any).** When `canopy.json` names a `worker` entry, that backend code is bundled into a single file (dependencies included) and ships in the same version as the static files — frontend and backend always move together.
30
- 4. **Upload.** The files upload in parallel; the new version is staged alongside the old one, so the live site keeps serving until everything has arrived.
31
- 5. **Migrate (if configured).** With a `"migrations"` directory in `canopy.json`, pending schema migrations apply now — after the bundle is staged, before the version flips — so the incoming code never runs against the old schema. The platform stores an automatic pre-migrate snapshot first. If a migration fails, the deploy aborts and the live version is unchanged; the error names the snapshot to restore if needed.
32
- 6. **Go live.** The platform validates the staged version and switches the site over to it in one step. The upload must contain an `index.html` at the top level — the deploy is rejected otherwise — so double-check `dist` points at the folder that actually holds `index.html`. On success the CLI prints the live URL and version number (plus the backend service URL for worker projects).
31
+ 4. **Site media (if declared).** Folders listed in `canopy.json` `"media"` don't go into the version. The CLI compares them with what the project already stores and uploads only new and changed files; unchanged ones cost nothing. They are live as soon as they are uploaded. One line reports what happened, e.g. `media: 3 uploaded, 3,255 unchanged, 175 MB stored`.
32
+ 5. **Upload.** The files upload in parallel; the new version is staged alongside the old one, so the live site keeps serving until everything has arrived.
33
+ 6. **Migrate (if configured).** With a `"migrations"` directory in `canopy.json`, pending schema migrations apply now — after the bundle is staged, before the version flips — so the incoming code never runs against the old schema. The platform stores an automatic pre-migrate snapshot first. If a migration fails, the deploy aborts and the live version is unchanged; the error names the snapshot to restore if needed.
34
+ 7. **Go live.** The platform validates the staged version and switches the site over to it in one step. The upload must contain an `index.html` at the top level — the deploy is rejected otherwise — so double-check `dist` points at the folder that actually holds `index.html`. On success the CLI prints the live URL and version number (plus the backend service URL for worker projects).
33
35
 
34
36
  Deploys are versioned and immutable: nothing overwrites an old version, so [canopy rollback](https://docs.canopy.website/cli/rollback) can always take you back.
35
37
 
38
+ ## Site media
39
+
40
+ A folder of large data or media that rarely changes, such as Storybook mock data or demo video, can be stored once per project instead of in every version:
41
+
42
+ ```json
43
+ {
44
+ "dist": "storybook-static",
45
+ "media": ["mocks/", "demo-assets/"]
46
+ }
47
+ ```
48
+
49
+ The folders are paths inside the build output. Their files keep their URLs (`/mocks/users.json`), and don't count toward the deploy limit. They may hold data and media only: JSON, CSV, text, images, video, audio, fonts and 3D models. A folder with HTML, JavaScript, CSS or SVG in it is refused before anything uploads. **Media is not versioned:** a rollback or a pinned version serves the current files, and it is shared with the staging channel.
50
+
51
+ The CLI suggests folders for you. When the version reaches 30% of the deploy limit, the deploy ends with a hint naming the folders that could move and the exact `"media"` line to add. When it is over the limit, the refusal names the folders that would bring it under. The CLI never edits `canopy.json` itself. See [Site media](https://docs.canopy.website/guides/static-serving#site-media) for limits and details.
52
+
36
53
  **CI.** In GitHub Actions, `canopy deploy` needs no secret and no `canopy login`: with `permissions: id-token: write` in the workflow, it proves which repository and branch the run comes from and deploys a project [linked](https://docs.canopy.website/cli/repo) to that repository. A run on the project's staging branch deploys to staging without `--staging`. An unlinked project, or one whose CI deploys are off, skips the deploy with a warning instead of failing. Elsewhere, set `CANOPY_DEPLOY_TOKEN` to a project-scoped deploy token (from [canopy token create](https://docs.canopy.website/cli/token)); it wins over the linked repository when both are there. Deploys from GitHub Actions are tagged with their source in the deploy history. See [CI deploys](https://docs.canopy.website/guides/ci).
37
54
 
38
55
  ## Examples