@mediamonks/canopy-cli 0.7.51 → 0.7.52

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.
@@ -15,12 +15,44 @@ await canopy.blob.put("notes.txt", "hello canopy", { contentType: "text/plain" }
15
15
  await canopy.blob.put("avatars/arjan.png", file); // a File/Blob carries its own type
16
16
  ```
17
17
 
18
- `data` can be a `Blob` (including a `File`), an `ArrayBuffer`, or a `string`.
18
+ `data` can be a `Blob` (including a `File`), an `ArrayBuffer`, a `string`, or a
19
+ `ReadableStream` together with its `size` in bytes.
19
20
  The content type is resolved in order: the explicit `options.contentType`, then
20
21
  the `Blob`'s own `type`, then `application/octet-stream`. Keys are plain
21
22
  strings — use `/`-separated segments (`avatars/arjan.png`) so related files
22
23
  share a prefix you can `list()` later. Putting to an existing key overwrites it.
23
24
 
25
+ In your backend, a stream lets you store a file without holding it in memory
26
+ first, such as a response you fetched:
27
+
28
+ ```ts title="worker/index.ts"
29
+ const res = await fetch(renderUrl);
30
+ await canopy.blob.put("renders/layer.tif", res.body!, {
31
+ size: Number(res.headers.get("content-length")),
32
+ contentType: "image/tiff",
33
+ });
34
+ ```
35
+
36
+ ### How big a file can be
37
+
38
+ | Site | One file | Uploaded from a browser |
39
+ | -------------------- | ---------------- | ----------------------- |
40
+ | `main` and `staging` | up to **200 MB** | up to **100 MB** |
41
+ | `gcp-pilot` | up to **25 MB** | up to **25 MB** |
42
+
43
+ A browser upload (a page calling `put`, or a page using an
44
+ [upload link](#upload-links)) passes through the site's front door, which
45
+ stops at 100 MB. Your backend's own `put` doesn't, so for a file between 100
46
+ and 200 MB, upload it from the backend. Anything above the limit is refused
47
+ with `blob_too_large` (413), which tells you the limit in `maxBytes`, and
48
+ nothing is stored.
49
+
50
+ Files over 25 MB need two things: the upload must say how big it is (a `Blob`,
51
+ `File`, `ArrayBuffer` or `string` always does; a stream needs `size`), and the
52
+ project must have been
53
+ deployed since large files arrived. An older deploy answers `runtime_outdated`
54
+ (503) for big files until you redeploy; smaller files keep working.
55
+
24
56
  Every upload (and every `list` entry) is described by a `BlobObject`:
25
57
 
26
58
  | Field | Type | Meaning |
@@ -79,6 +111,86 @@ const avatars = await canopy.blob.list("avatars/");
79
111
  await canopy.blob.delete("notes.txt");
80
112
  ```
81
113
 
114
+ ## Upload links
115
+
116
+ ```ts
117
+ // uploadUrl(key, options?) → Promise<{ url: string; method: "PUT"; expiresAt: string }>
118
+ const link = await canopy.blob.uploadUrl("uploads/cv.pdf", {
119
+ contentType: "application/pdf", // the only type the upload may carry
120
+ maxBytes: 5_000_000, // the largest file it accepts
121
+ });
122
+ ```
123
+
124
+ An upload link lets someone else upload one file to one key, straight to your
125
+ project's storage, without signing in. Your backend usually makes it and hands
126
+ it to a page, so the backend decides what may be uploaded and where, while the
127
+ file itself never passes through it. Send a `PUT` of the file's bytes to `url`:
128
+
129
+ ```ts
130
+ await fetch(link.url, { method: "PUT", body: file, headers: { "content-type": file.type } });
131
+ ```
132
+
133
+ What a link allows is fixed when it's made:
134
+
135
+ - `expiresIn` — seconds until it stops working. 10 minutes unless you ask
136
+ otherwise, at most an hour.
137
+ - `maxBytes` — the largest upload it accepts, at most the site's
138
+ [file limit](#how-big-a-file-can-be).
139
+ - `contentType` — when set, only that type is accepted.
140
+ - `overwrite` — `false` (the default) means the link only creates the file:
141
+ once something is stored under the key, another upload gets `409
142
+ blob_exists`, so the link works once. Set `true` to let it replace an
143
+ existing file, as often as it's used until it expires.
144
+
145
+ A refused upload answers with an error code: `invalid_upload_link` (wrong key,
146
+ or a link that was changed), `upload_link_expired`, `blob_too_large` (413) or
147
+ `content_type_mismatch` (415). An upload through a link works at every
148
+ [browser access](#who-can-call-this-from-the-browser) level, so it pairs well
149
+ with **Read only** or **Off**: pages can't upload on their own, only where
150
+ your backend lets them. Making a link counts as an upload, so at those levels
151
+ only your backend can make one. Anyone holding a link can use it until it
152
+ expires, so keep it short-lived and give it to one person.
153
+
154
+ ### Example: your backend decides, the page uploads
155
+
156
+ ```ts title="worker/index.ts"
157
+ // The page asks for a link; the backend checks who is asking.
158
+ app.post("/api/sow-upload", async (c) => {
159
+ const canopy = createCanopy({ fetch: c.env.CANOPY.fetch.bind(c.env.CANOPY) });
160
+ const caller = c.env.CALLER;
161
+ if (!caller?.roles.includes("approver")) return c.json({ error: "forbidden" }, 403);
162
+ const key = `sow/${crypto.randomUUID()}.pdf`;
163
+ const link = await canopy.blob.uploadUrl(key, {
164
+ contentType: "application/pdf",
165
+ maxBytes: 10_000_000,
166
+ });
167
+ // Remember the key, so only links this backend made can be confirmed.
168
+ await canopy.db.collection("sows").insert({ key, by: caller.id, status: "uploading" });
169
+ return c.json({ key, url: link.url });
170
+ });
171
+
172
+ // Once the upload is done, the page says so and the backend records it.
173
+ app.post("/api/sow-uploaded", async (c) => {
174
+ const canopy = createCanopy({ fetch: c.env.CANOPY.fetch.bind(c.env.CANOPY) });
175
+ const { key } = await c.req.json<{ key: string }>();
176
+ const [sow] = await canopy.db.collection("sows").find({ where: { key, status: "uploading" } });
177
+ if (!sow) return c.json({ error: "unknown_upload" }, 404);
178
+ const file = await canopy.blob.get(key);
179
+ if (!file) return c.json({ error: "not_uploaded" }, 409);
180
+ await canopy.db.collection("sows").update(sow._id, { size: file.size, status: "review" });
181
+ return c.json({ ok: true });
182
+ });
183
+ ```
184
+
185
+ ```ts title="src/upload.ts"
186
+ const { key, url } = await (await fetch("/api/sow-upload", { method: "POST" })).json();
187
+ await fetch(url, { method: "PUT", body: file, headers: { "content-type": "application/pdf" } });
188
+ await fetch("/api/sow-uploaded", { method: "POST", body: JSON.stringify({ key }) });
189
+ ```
190
+
191
+ The platform doesn't tell your backend when an upload lands, which is why the
192
+ page reports back and the backend checks the file before trusting it.
193
+
82
194
  ## Who can call this from the browser
83
195
 
84
196
  Everything above works from a page as well as from your worker, so an upload
@@ -90,7 +202,8 @@ dashboard (or with [`canopy files access`](https://docs.canopy.website/cli/files
90
202
  do everything on this page.
91
203
  - **Read only** lets pages list and download files and make download links
92
204
  with `getUrl()`. `put()` and `delete()` from a page are refused, so changes
93
- have to come from the worker.
205
+ have to come from the worker, or through an [upload link](#upload-links) it
206
+ hands out.
94
207
  - **Off** means pages cannot touch files at all.
95
208
 
96
209
  This is separate from the database's [browser access](https://docs.canopy.website/sdk/database#who-can-call-this-from-the-browser),
@@ -126,5 +239,5 @@ async function onFileChange(event: React.ChangeEvent<HTMLInputElement>) {
126
239
  <input type="file" accept="image/*" onChange={onFileChange} />;
127
240
  ```
128
241
 
129
- Storage location and limits are covered in
130
- [Project data](https://docs.canopy.website/platform/project-data).
242
+ File size limits are [above](#how-big-a-file-can-be); the Files tab and
243
+ browser access are covered in [Project data](https://docs.canopy.website/platform/project-data).
package/dist/docs/sdk.md CHANGED
@@ -40,11 +40,11 @@ const canopy = createCanopy();
40
40
  // canopy.services
41
41
  ```
42
42
 
43
- | Option | Type | Default | What it does |
44
- | --------- | -------------- | -------------- | --------------------------------------------------------------------------------------------------------------------- |
45
- | `baseUrl` | `string` | `"/_api"` | Base URL of the platform data API. The default is same-origin, so it works untouched in the browser. |
46
- | `token` | `string` | none | A project-scoped `cnpy_` token sent as a bearer on every request — for scripts and CI running outside Canopy hosting. |
47
- | `fetch` | `typeof fetch` | global `fetch` | Override how requests are sent — a backend worker passes its platform service binding here. |
43
+ | Option | Type | Default | What it does |
44
+ | --------- | -------------- | -------------- | ---------------------------------------------------------------------------------------------------------------- |
45
+ | `baseUrl` | `string` | `"/_api"` | Base URL of the platform data API. The default is same-origin, so it works untouched in the browser. |
46
+ | `token` | `string` | none | A dev token sent as a bearer on every request — for a local script that reads the project's data while you work. |
47
+ | `fetch` | `typeof fetch` | global `fetch` | Override how requests are sent — a backend worker passes its platform service binding here. |
48
48
 
49
49
  In the browser no config is needed. In a backend worker (the `worker`
50
50
  template), the platform is reachable through the `CANOPY` service binding, so
@@ -58,18 +58,25 @@ app.get("/api/hello", async (c) => {
58
58
  });
59
59
  ```
60
60
 
61
- Outside Canopy hosting — a local Node script, a CI job — there is no session
62
- and no service binding. Mint a dev token (`canopy dev` does this for you, or
63
- `POST /control/v1/projects/:slug/dev-token`) and pass it with the platform's
64
- API host:
61
+ A local Node script has no session and no service binding. While you work,
62
+ it can use a dev token: `canopy dev` mints one for you (it lasts 12 hours and
63
+ needs your `canopy login`), or an editor can mint one with
64
+ `POST /control/v1/projects/:slug/dev-token`. Pass it with the platform's API
65
+ host:
65
66
 
66
67
  ```ts
67
68
  const canopy = createCanopy({
68
69
  baseUrl: "https://api.canopy.website",
69
- token: process.env.CANOPY_TOKEN, // a project-scoped cnpy_ token
70
+ token: process.env.CANOPY_DEV_TOKEN, // a dev token, valid for 12 hours
70
71
  });
71
72
  ```
72
73
 
74
+ A dev token isn't for CI or anything that runs unattended. To let a CI job,
75
+ script or app reach your project, give it a
76
+ [project key or personal token](https://docs.canopy.website/guides/access-tokens) and have it call your
77
+ project's own `/api` routes. Access tokens only work there, so don't pass one
78
+ to `createCanopy`.
79
+
73
80
  ## One instance, shared
74
81
 
75
82
  In the browser, create the client once and import it everywhere. The scaffolds
@@ -45,6 +45,26 @@ Run it on your own laptop.
45
45
  The `CANOPY_DEPLOY_TOKEN` was revoked or is wrong. Create a new one with
46
46
  `canopy token create` (or in the dashboard) and update your CI secret.
47
47
 
48
+ ## `token_invalid`, `token_expired`, `token_access_lost` (401)
49
+
50
+ An access token was refused on a project's `/api`. `token_invalid` means it's
51
+ unknown, revoked, or made for another project or channel; `token_expired`
52
+ means it's past its date, or a project key went 90 days without a call;
53
+ `token_access_lost` means its person lost access to the project or hasn't
54
+ signed in to Canopy for 30 days (signing in again fixes it). The full list is
55
+ in [Calling from apps and scripts](https://docs.canopy.website/guides/access-tokens#3-call-the-project).
56
+
57
+ ## `token_disabled` (401)
58
+
59
+ The project's owner turned access tokens off under **Settings → Access**.
60
+ Turning them back on revives every token that hasn't expired.
61
+
62
+ ## `credential_out_of_scope` (403)
63
+
64
+ A credential reached past what it may do: a deploy token outside its own
65
+ project's deploys, or a dev token on another project. See
66
+ [Which credential do I need?](https://docs.canopy.website/platform/credentials).
67
+
48
68
  ## `not_supported_on_target` (501)
49
69
 
50
70
  Some features are platform-target-specific: a site whose platform target
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-4SGn0Cy3.mjs";
1
+ import { t as version } from "./package-DBdEKZ6u.mjs";
2
2
  import { r as siteConfig } from "./site-BL5Ik-yj.mjs";
3
3
  import { i as latestKnownVersion, r as compareSemver } from "./version-check-CcsA1QjI.mjs";
4
4
  import { n as agentHeaders } from "./api-DmJrIsE7.mjs";
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-4SGn0Cy3.mjs";
1
+ import { t as version } from "./package-DBdEKZ6u.mjs";
2
2
  import { c as projectDirArgs, d as resolveProject, h as tryResolveProject, m as tryReadCanopyJson, r as siteConfig } from "./site-BL5Ik-yj.mjs";
3
3
  import { a as apiRequest, c as credentials, i as apiDownload, o as apiUpload, s as commonHeaders } from "./api-DmJrIsE7.mjs";
4
4
  import { r as reportErrors, t as formatDateTime } from "./ui-Ddw4d2Nn.mjs";
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "./package-4SGn0Cy3.mjs";
2
+ import { t as version } from "./package-DBdEKZ6u.mjs";
3
3
  import { i as siteHeaderLine, n as setInvocationProfile } from "./site-BL5Ik-yj.mjs";
4
4
  import { a as notifyOfUpdate, o as runRefresh } from "./version-check-CcsA1QjI.mjs";
5
5
  import { defineCommand, runMain } from "citty";
@@ -72,7 +72,7 @@ const main = defineCommand({
72
72
  projects: () => import("./projects-BEBYhy6k.mjs").then((m) => m.projectsCommand),
73
73
  delete: () => import("./projects-BEBYhy6k.mjs").then((m) => m.deleteCommand),
74
74
  rename: () => import("./rename-PIJmdzHk.mjs").then((m) => m.renameCommand),
75
- dev: () => import("./dev-DkaQjBTp.mjs").then((m) => m.devCommand),
75
+ dev: () => import("./dev-DSI3e4qP.mjs").then((m) => m.devCommand),
76
76
  deploy: () => import("./deploy-D8OZyhH8.mjs").then((m) => m.deployCommand),
77
77
  promote: () => import("./deploy-D8OZyhH8.mjs").then((m) => m.promoteCommand),
78
78
  staging: () => import("./staging-B9sjqvfh.mjs").then((m) => m.stagingCommand),
@@ -85,18 +85,18 @@ const main = defineCommand({
85
85
  roles: () => import("./roles-CXY226VM.mjs").then((m) => m.rolesCommand),
86
86
  members: () => import("./roles-CXY226VM.mjs").then((m) => m.membersCommand),
87
87
  schedule: () => import("./schedule-DJsclUxC.mjs").then((m) => m.scheduleCommand),
88
- feedback: () => import("./feedback-B6tqJ3cd.mjs").then((m) => m.feedbackCommand),
88
+ feedback: () => import("./feedback-XEIHbeor.mjs").then((m) => m.feedbackCommand),
89
89
  db: () => import("./db-D5SXZrp5.mjs").then((m) => m.dbCommand),
90
90
  files: () => import("./files-B7toJRlj.mjs").then((m) => m.filesCommand),
91
91
  usage: () => import("./usage-VMT75MZ4.mjs").then((m) => m.usageCommand),
92
92
  ai: () => import("./ai-BjnuSjmw.mjs").then((m) => m.aiCommand),
93
93
  open: () => import("./open-6ev_6m0p.mjs").then((m) => m.openCommand),
94
94
  browse: () => import("./browse-BPLWhoFI.mjs").then((m) => m.browseCommand),
95
- docs: () => import("./docs-CLgKBi8H.mjs").then((m) => m.docsCommand),
96
- skill: () => import("./skill-CY_4eqOD.mjs").then((m) => m.skillCommand),
97
- upgrade: () => import("./upgrade-Dxzb3e3r.mjs").then((m) => m.upgradeCommand),
95
+ docs: () => import("./docs-Od4duFhd.mjs").then((m) => m.docsCommand),
96
+ skill: () => import("./skill-3RZw4vSI.mjs").then((m) => m.skillCommand),
97
+ upgrade: () => import("./upgrade-Dy4XV7iP.mjs").then((m) => m.upgradeCommand),
98
98
  logs: () => import("./logs-DJWrL6ja.mjs").then((m) => m.logsCommand),
99
- mcp: () => import("./mcp-CWtqUFE3.mjs").then((m) => m.mcpCommand),
99
+ mcp: () => import("./mcp-misDO7O8.mjs").then((m) => m.mcpCommand),
100
100
  repo: () => import("./repo-CGTFmIWM.mjs").then((m) => m.repoCommand),
101
101
  template: () => import("./project-template-Dti_Mmnb.mjs").then((m) => m.templateCommand),
102
102
  audience: () => import("./audience-BSvOEbco.mjs").then((m) => m.audienceCommand)
@@ -1,10 +1,12 @@
1
1
  import { r as apiDataRequest } from "./api-DmJrIsE7.mjs";
2
- import { a as realtimeRouter, c as META_COLUMNS, l as blobRouter, n as WORKER_ATTEST_HEADER, o as dbRouter, s as hasPrivateNames } from "./src-DbqT3K2l.mjs";
3
- import { a as rewriteApiPath } from "./dev-DjK3Y8jb.mjs";
2
+ import { c as dbRouter, d as STREAMED_BLOB_BYTES, f as blobRouter, l as hasPrivateNames, p as isCreateOnly, s as realtimeRouter, t as WORKER_ATTEST_HEADER, u as META_COLUMNS } from "./src-UBUAqzqH.mjs";
3
+ import { a as rewriteApiPath } from "./dev-BnzJ8a1u.mjs";
4
4
  import { createRequire } from "node:module";
5
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
5
+ import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join, relative, sep } from "node:path";
7
7
  import { Hono } from "hono";
8
+ import { Readable } from "node:stream";
9
+ import { pipeline } from "node:stream/promises";
8
10
  //#region ../data-plane/src/db-access.ts
9
11
  /** The worker-only marker: `private_` at the start of a collection or table name. */
10
12
  const PRIVATE_PREFIX = "private_";
@@ -653,8 +655,9 @@ function createMemoryBlobBucket() {
653
655
  const objects = /* @__PURE__ */ new Map();
654
656
  return {
655
657
  async put(key, body, options) {
658
+ if (isCreateOnly(options?.onlyIf) && objects.has(key)) return null;
656
659
  objects.set(key, {
657
- body,
660
+ body: body instanceof ArrayBuffer ? body : await new Response(body).arrayBuffer(),
658
661
  meta: {
659
662
  contentType: options?.httpMetadata?.contentType,
660
663
  uploaded: (/* @__PURE__ */ new Date()).toISOString()
@@ -715,7 +718,14 @@ function createFsBlobBucket(root) {
715
718
  async put(key, body, options) {
716
719
  const path = dataPath(root, key);
717
720
  mkdirSync(dirname(path), { recursive: true });
718
- writeFileSync(path, Buffer.from(body));
721
+ const flag = isCreateOnly(options?.onlyIf) ? "wx" : "w";
722
+ try {
723
+ if (body instanceof ArrayBuffer) writeFileSync(path, Buffer.from(body), { flag });
724
+ else await pipeline(Readable.fromWeb(body), createWriteStream(path, { flags: flag }));
725
+ } catch (err) {
726
+ if (err.code === "EEXIST") return null;
727
+ throw err;
728
+ }
719
729
  writeFileSync(metaPath(root, key), `${JSON.stringify({
720
730
  contentType: options?.httpMetadata?.contentType,
721
731
  uploaded: (/* @__PURE__ */ new Date()).toISOString()
@@ -907,7 +917,8 @@ async function createSandbox(options) {
907
917
  prefix: ""
908
918
  }
909
919
  },
910
- signDownload: async () => "local"
920
+ signDownload: async () => "local",
921
+ maxBytes: () => STREAMED_BLOB_BYTES
911
922
  }));
912
923
  const realtimeHub = memoryRealtimeBroker();
913
924
  app.route("/data/v1", realtimeRouter({ context: async (c) => ownProject(c) ?? {
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-4SGn0Cy3.mjs";
1
+ import { t as version } from "./package-DBdEKZ6u.mjs";
2
2
  import { h as tryResolveProject, p as stagingUrl, r as siteConfig, u as projectUrl } from "./site-BL5Ik-yj.mjs";
3
3
  import { a as apiRequest, f as noticeRenamesOnly, l as currentSlug, t as ApiError } from "./api-DmJrIsE7.mjs";
4
4
  import { t as liveDevServer } from "./dev-server-file-Dk9pk4AR.mjs";
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.7.51";
2
+ var version = "0.7.52";
3
3
  //#endregion
4
4
  export { version as t };
@@ -118,7 +118,15 @@ and never go stale.
118
118
  only some roles may see in `private_` tables. Try other roles locally with
119
119
  `canopy dev --as-role <slug>`. Adding or removing people is the owner's call
120
120
  (`canopy members add|remove`) — confirm with the user first.
121
- - CI credentials: `canopy token create | list | revoke`
121
+ - Credentials (`canopy docs platform-credentials`): CI **deploys** use a linked
122
+ repository (`canopy repo link`, GitHub) or a deploy token (`canopy token
123
+ create | list | revoke`). Software that **calls the project's `/api`** — a
124
+ CI job, script, plugin or desktop app — uses an access token the owner
125
+ enables and makes in the dashboard (project key, or a person's personal
126
+ token; `canopy docs access-tokens`). The backend reads it on
127
+ `env.CALLER.token` and checks the project's scopes with `requireScope`; give
128
+ every `switch (env.CALLER.kind)` a refusing `default`. Never put any token in
129
+ the repository.
122
130
  - Git: `canopy repo show --json` (is there a repository, and its remote) ·
123
131
  `canopy repo create` · `canopy repo clone <slug>` · `canopy repo connect`
124
132
  (set up an existing folder). Then plain `git`: the CLI gives git
@@ -1,4 +1,4 @@
1
- import { t as version } from "./package-4SGn0Cy3.mjs";
1
+ import { t as version } from "./package-DBdEKZ6u.mjs";
2
2
  import { r as reportErrors } from "./ui-Ddw4d2Nn.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  import { cpSync, existsSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";