@mediamonks/canopy-cli 0.7.57 → 0.7.59

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-00f2Mgqh.mjs → ai-4Mr9FbLU.mjs} +2 -2
  2. package/dist/{api-fmc8CEMT.mjs → api-CpG-9WSe.mjs} +13 -1
  3. package/dist/{audience-ByM1jUH3.mjs → audience-BXXdvGC_.mjs} +3 -3
  4. package/dist/{browse-CxwKuka0.mjs → browse-BegddW9V.mjs} +2 -2
  5. package/dist/{calls-DsbRjCcy.mjs → calls-NFUccBaQ.mjs} +3 -3
  6. package/dist/{db-BU-ni9fj.mjs → db-DIxujtt1.mjs} +13 -6
  7. package/dist/{deploy-7tgGJZUK.mjs → deploy-Bp5DMp_U.mjs} +381 -16
  8. package/dist/{dev-qp1VRNM_.mjs → dev-AkM6kLVb.mjs} +9 -9
  9. package/dist/dev-pj6lLjMR.mjs +2 -0
  10. package/dist/{dev-worker-7tqL9UFi.mjs → dev-worker-DEK8fOgz.mjs} +18 -1
  11. package/dist/docs/cli-deploy.md +20 -3
  12. package/dist/docs/cli-dev.md +1 -1
  13. package/dist/docs/data.md +18 -0
  14. package/dist/docs/migrations.md +22 -0
  15. package/dist/docs/platform-deploys-and-rollbacks.md +3 -0
  16. package/dist/docs/platform-project-data.md +7 -0
  17. package/dist/docs/sdk-database.md +51 -0
  18. package/dist/docs/static-serving.md +34 -2
  19. package/dist/{docs-hcHwEc6n.mjs → docs-F0GxdMrn.mjs} +4 -4
  20. package/dist/{egress-Bzn2VKDe.mjs → egress-Dwq-d6cB.mjs} +3 -3
  21. package/dist/{feedback-COujxFBV.mjs → feedback-ClCjUP3z.mjs} +4 -4
  22. package/dist/{files-CBbAtHIK.mjs → files-CUPtGcuZ.mjs} +3 -3
  23. package/dist/index.mjs +39 -39
  24. package/dist/{local-C1i2uhAf.mjs → local-CFxKguzg.mjs} +54 -19
  25. package/dist/{login-Baso-JE0.mjs → login-CP1fO_AH.mjs} +3 -3
  26. package/dist/{logs-c76jVOhb.mjs → logs-BwqG7lYU.mjs} +3 -3
  27. package/dist/{mcp-aWskwkXw.mjs → mcp-CnTfFA0U.mjs} +3 -3
  28. package/dist/{migrations-ChafLorm.mjs → migrations-DJrRnU7X.mjs} +2 -2
  29. package/dist/{open-Doat726T.mjs → open-5JLHiz_J.mjs} +2 -2
  30. package/dist/{package-BpOFa8Qi.mjs → package-tnyqU_dN.mjs} +1 -1
  31. package/dist/{project-template-BnX47DpF.mjs → project-template-CsTOpPto.mjs} +3 -3
  32. package/dist/project-template-xNjGs9ty.mjs +2 -0
  33. package/dist/{projects-DOqpkUVT.mjs → projects-DCFn4zcq.mjs} +6 -6
  34. package/dist/{rename-RA_oYbRT.mjs → rename-OeOI97da.mjs} +3 -3
  35. package/dist/repo-BW7dDQZL.mjs +2 -0
  36. package/dist/{repo-DD3eK1P_.mjs → repo-CIEG53hP.mjs} +3 -3
  37. package/dist/{roles-tqf4sYDM.mjs → roles-2Pkqiwrx.mjs} +1 -1
  38. package/dist/{roles-BS8-Gvv-.mjs → roles-BCJWHeGq.mjs} +3 -3
  39. package/dist/{schedule-D8AQ8MVF.mjs → schedule-Cy-7IFy5.mjs} +3 -3
  40. package/dist/{secrets-Bi7BYCla.mjs → secrets-Cgte8mvq.mjs} +3 -3
  41. package/dist/{site-BcZ0LOvm.mjs → site-Bz-fEyKS.mjs} +1 -1
  42. package/dist/skill/canopy/SKILL.md +3 -0
  43. package/dist/{skill-984KseKb.mjs → skill-CoPNcCaM.mjs} +2 -2
  44. package/dist/{src-DpjA-a59.mjs → src-Dlg7aeRj.mjs} +250 -23
  45. package/dist/{staging-BxG3Cffd.mjs → staging-D6-Ojy39.mjs} +3 -3
  46. package/dist/{token-bHdy_IoX.mjs → token-yAj7pF78.mjs} +3 -3
  47. package/dist/{ui-9f_lF2Ak.mjs → ui-BUeiY_zZ.mjs} +1 -1
  48. package/dist/{upgrade-DhK_PlAN.mjs → upgrade-CLFrKuJS.mjs} +2 -2
  49. package/dist/{usage-DFs2TERV.mjs → usage-BXPm04tk.mjs} +3 -3
  50. package/dist/{versions-Cgw7sB3h.mjs → versions-C204ivt9.mjs} +3 -3
  51. package/package.json +1 -1
  52. package/dist/dev-BtacZ4HE.mjs +0 -2
  53. package/dist/project-template--mESzwea.mjs +0 -2
  54. package/dist/repo-DayXVvyj.mjs +0 -2
@@ -0,0 +1,2 @@
1
+ import { o as repoCommand } from "./repo-CIEG53hP.mjs";
2
+ export { repoCommand };
@@ -1,6 +1,6 @@
1
- import { a as parseGithubRemote, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, o as parseRepositoryArg, r as siteConfig, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, f as noticeRenamesOnly, m as withContext, n as agentHeaders, u as followRename } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, n as formatDateTime, s as unwrap, t as confirmTypedSlug } from "./ui-9f_lF2Ak.mjs";
1
+ import { a as parseGithubRemote, f as resolveProject, h as tryReadCanopyJson, l as projectDirArgs, o as parseRepositoryArg, r as siteConfig, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, f as noticeRenamesOnly, m as withContext, n as agentHeaders, u as followRename } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime, s as unwrap, t as confirmTypedSlug } from "./ui-BUeiY_zZ.mjs";
4
4
  import { a as parseCredentialInput, i as helperCommand, o as runCredentialHelper, r as fileTokenCache, t as RepoCredentialError } from "./repo-credential-CNDRM-tG.mjs";
5
5
  import { defineCommand } from "citty";
6
6
  import { existsSync, realpathSync } from "node:fs";
@@ -1,2 +1,2 @@
1
- import { c as rolesCommand, o as membersCommand } from "./roles-BS8-Gvv-.mjs";
1
+ import { c as rolesCommand, o as membersCommand } from "./roles-BCJWHeGq.mjs";
2
2
  export { membersCommand, rolesCommand };
@@ -1,6 +1,6 @@
1
- import { d as projectUrl, f as resolveProject, l as projectDirArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { a as requireTty, i as reportErrors, s as unwrap } from "./ui-9f_lF2Ak.mjs";
1
+ import { d as projectUrl, f as resolveProject, l as projectDirArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { a as requireTty, i as reportErrors, s as unwrap } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/roles.ts
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.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";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/schedule.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, l as projectDirArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, n as formatDateTime, s as unwrap } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, l as projectDirArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime, s as unwrap } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/secrets.ts
@@ -1,4 +1,4 @@
1
- import { f as STAGING_LABEL_PREFIX } from "./src-DpjA-a59.mjs";
1
+ import { f as STAGING_LABEL_PREFIX } from "./src-Dlg7aeRj.mjs";
2
2
  import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join, resolve } from "node:path";
@@ -221,6 +221,9 @@ Non-interactive: `canopy create "My App" --template spa`. **When unsure between
221
221
  restores.
222
222
  - **Deploys are public.** `canopy deploy` makes a version live. Confirm before
223
223
  deploying unless the user clearly asked you to.
224
+ - **Site media isn't versioned.** When a deploy suggests moving a folder to
225
+ `canopy.json` `"media"`, do it only for data or media that rarely changes,
226
+ or when the user agrees: a rollback keeps serving the current media.
224
227
  - **Version retention deletes old versions.** When a deploy prints a retention
225
228
  hint, pass it on to the user and ask before running
226
229
  `canopy versions retention on`: expired versions can no longer be rolled
@@ -1,5 +1,5 @@
1
- import { t as version } from "./package-BpOFa8Qi.mjs";
2
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
1
+ import { t as version } from "./package-tnyqU_dN.mjs";
2
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  import { cpSync, existsSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
@@ -353,6 +353,45 @@ const HOST_LABEL_SEPARATOR = "-dot-";
353
353
  /** A staging-channel label starts with this (also the channel qualifier on signed blob scopes). */
354
354
  const STAGING_LABEL_PREFIX = `staging${HOST_LABEL_SEPARATOR}`;
355
355
  //#endregion
356
+ //#region ../data-plane/src/batch.ts
357
+ /** Statements one batch may hold, on every host. */
358
+ const BATCH_MAX_STATEMENTS = 1e3;
359
+ /** A batch that may not run: not an array, a bad entry, or over the cap. */
360
+ var InvalidBatch = class extends Error {};
361
+ function isScalar$1(value) {
362
+ return value === null || [
363
+ "string",
364
+ "number",
365
+ "boolean"
366
+ ].includes(typeof value);
367
+ }
368
+ /**
369
+ * The statements, checked: an array of at most BATCH_MAX_STATEMENTS entries,
370
+ * each with a non-empty string `sql` and scalar `params`. Throws InvalidBatch
371
+ * naming the first problem, so nothing runs.
372
+ */
373
+ function validateBatch(input) {
374
+ if (!Array.isArray(input)) throw new InvalidBatch("statements must be an array");
375
+ if (input.length > 1e3) throw new InvalidBatch(`a batch holds at most ${BATCH_MAX_STATEMENTS} statements (got ${input.length})`);
376
+ return input.map((entry, i) => {
377
+ const s = entry;
378
+ if (!s || typeof s !== "object" || typeof s.sql !== "string" || s.sql.trim() === "") throw new InvalidBatch(`statement ${i}: expected { sql: string, params?: [] }`);
379
+ const params = s.params ?? [];
380
+ if (!Array.isArray(params) || !params.every(isScalar$1)) throw new InvalidBatch(`statement ${i}: params must be string/number/boolean/null values`);
381
+ return {
382
+ sql: s.sql,
383
+ params
384
+ };
385
+ });
386
+ }
387
+ /**
388
+ * `rowCount` as `query` reports it: returned rows when there are any, else
389
+ * the rows the statement changed (pg parity).
390
+ */
391
+ function rowCountOf(rows, changes) {
392
+ return rows.length > 0 ? rows.length : changes ?? 0;
393
+ }
394
+ //#endregion
356
395
  //#region ../data-plane/src/dialect.ts
357
396
  /** Platform-managed fields map to real columns instead of JSON extraction. */
358
397
  const META_COLUMNS = {
@@ -608,6 +647,48 @@ function dbRouter(config) {
608
647
  truncated
609
648
  });
610
649
  });
650
+ db.post("/db/sql/batch", async (c) => {
651
+ const resolved = await resolve(c);
652
+ if (resolved instanceof Response) return resolved;
653
+ const body = await c.req.json().catch(() => null);
654
+ let statements;
655
+ try {
656
+ statements = validateBatch(body?.statements);
657
+ } catch (err) {
658
+ if (!(err instanceof InvalidBatch)) throw err;
659
+ return c.json({
660
+ error: "invalid_batch",
661
+ detail: err.message
662
+ }, 400);
663
+ }
664
+ const verdict = await config.guard?.(c, {
665
+ kind: "sql",
666
+ readonly: false
667
+ }, resolved);
668
+ if (verdict instanceof Response) return verdict;
669
+ if (verdict?.readonly === true) return c.json({
670
+ error: "browser_db_access",
671
+ detail: verdict.refusal
672
+ }, 403);
673
+ const { store } = resolved;
674
+ if (!store.batch) return c.json({
675
+ error: "not_supported",
676
+ detail: "this host has no batch support"
677
+ }, 501);
678
+ if (statements.length === 0) return c.json({ results: [] });
679
+ const results = await store.batch(statements.map((s) => ({
680
+ sql: s.sql,
681
+ params: s.params ?? []
682
+ }))).catch((err) => err);
683
+ if (results instanceof Error) return c.json({
684
+ error: "sql_error",
685
+ detail: results.message
686
+ }, 400);
687
+ return c.json({ results: results.map((r) => ({
688
+ rows: r.results,
689
+ rowCount: rowCountOf(r.results, r.meta.changes)
690
+ })) });
691
+ });
611
692
  db.get("/db/schema", async (c) => {
612
693
  const resolved = await resolve(c);
613
694
  if (resolved instanceof Response) return resolved;
@@ -842,9 +923,9 @@ function gate(c, ctx) {
842
923
  detail: "realtime is turned off for this project — a Canopy admin can turn it on for you"
843
924
  }, 403);
844
925
  }
845
- const encoder = new TextEncoder();
846
- const frame = (event, data) => encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
847
- const KEEPALIVE = encoder.encode(": keep-alive\n\n");
926
+ const encoder$1 = new TextEncoder();
927
+ const frame = (event, data) => encoder$1.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
928
+ const KEEPALIVE = encoder$1.encode(": keep-alive\n\n");
848
929
  function realtimeRouter(config) {
849
930
  const realtime = new Hono();
850
931
  const random = config.random ?? Math.random;
@@ -969,7 +1050,7 @@ function realtimeRouter(config) {
969
1050
  detail: "send a JSON body of the form { \"data\": … }"
970
1051
  }, 400);
971
1052
  const data = body.data;
972
- const bytes = encoder.encode(JSON.stringify(data)).byteLength;
1053
+ const bytes = encoder$1.encode(JSON.stringify(data)).byteLength;
973
1054
  if (bytes > 4096) return c.json({
974
1055
  error: "message_too_large",
975
1056
  detail: `message data is ${bytes} bytes; the limit is ${REALTIME_MAX_DATA_BYTES}. Send an id and load the rest from the database`
@@ -1034,6 +1115,17 @@ const ACTING_AGENT_HEADER = "x-canopy-acting-agent";
1034
1115
  const ACTING_ROLES_HEADER = "x-canopy-acting-roles";
1035
1116
  /** An access-token call (project-access-tokens): the token's description, base64url JSON. */
1036
1117
  const TOKEN_HEADER = "x-canopy-token";
1118
+ const UTF8_PREFIX = /^utf-8''/i;
1119
+ /** Free text from a header value: decoded when `UTF-8''`-prefixed, else as-is. */
1120
+ function decodeHeaderText(raw) {
1121
+ const value = raw?.trim() || "";
1122
+ if (!UTF8_PREFIX.test(value)) return value;
1123
+ try {
1124
+ return decodeURIComponent(value.slice(7)).trim();
1125
+ } catch {
1126
+ return value;
1127
+ }
1128
+ }
1037
1129
  /**
1038
1130
  * Gateway-stamped identity, for the backend's own env.USER / env.CALLER —
1039
1131
  * never relayed upstream by `CANOPY.fetch` (stampWorkerHeaders).
@@ -1072,8 +1164,8 @@ function readUser(headers) {
1072
1164
  const roles = rolesFromHeaders(headers);
1073
1165
  return {
1074
1166
  sub,
1075
- email: header(headers, USER_EMAIL_HEADER),
1076
- name: header(headers, USER_NAME_HEADER),
1167
+ email: decodeHeaderText(headers.get(USER_EMAIL_HEADER)),
1168
+ name: decodeHeaderText(headers.get(USER_NAME_HEADER)),
1077
1169
  ...roles && { roles }
1078
1170
  };
1079
1171
  }
@@ -1112,8 +1204,8 @@ function readPersonCaller(headers) {
1112
1204
  return {
1113
1205
  kind,
1114
1206
  id,
1115
- email: header(headers, IDENTITY_EMAIL_HEADER),
1116
- name: header(headers, IDENTITY_NAME_HEADER),
1207
+ email: decodeHeaderText(headers.get(IDENTITY_EMAIL_HEADER)),
1208
+ name: decodeHeaderText(headers.get(IDENTITY_NAME_HEADER)),
1117
1209
  agent: headers.get(CALLER_HEADER) === "agent",
1118
1210
  ...roles && { roles },
1119
1211
  token: token?.kind === "personal" ? token : null
@@ -1286,8 +1378,50 @@ const CREDENTIAL_HANDLE_HEADER = "x-canopy-credential-handle";
1286
1378
  // Workers Logs flattens console args and drops an Error's message line —
1287
1379
  // log the stack as a plain string (its first line is "Error: <message>") so
1288
1380
  // the entry matches what Node's console shows on GCP.
1381
+ function stackText(err) {
1382
+ if (!(err instanceof Error)) return String(err);
1383
+ const stack = err.stack ? String(err.stack) : "";
1384
+ // Keep the "Name: message" line even when a stack leaves it out.
1385
+ const head = String(err);
1386
+ return stack.includes(err.message) ? stack : stack ? head + "\n" + stack : head;
1387
+ }
1388
+
1289
1389
  function describeError(err) {
1290
- return err && err.stack ? String(err.stack) : String(err);
1390
+ let text = err && err.stack ? stackText(err) : String(err);
1391
+ // D1 and fetch errors carry the underlying reason as the cause.
1392
+ let cause = err instanceof Error ? err.cause : undefined;
1393
+ for (let depth = 0; cause !== undefined && cause !== null && depth < 5; depth++) {
1394
+ text += "\nCaused by: " + stackText(cause);
1395
+ cause = cause instanceof Error ? cause.cause : undefined;
1396
+ }
1397
+ return text;
1398
+ }
1399
+
1400
+ function describeLogArg(arg) {
1401
+ if (arg instanceof Error) return describeError(arg);
1402
+ if (typeof arg === "string") return arg;
1403
+ try {
1404
+ const json = JSON.stringify(arg);
1405
+ return json === undefined ? String(arg) : json;
1406
+ } catch {
1407
+ return String(arg);
1408
+ }
1409
+ }
1410
+
1411
+ // The same goes for the bundle's own console calls: console.error(err) or
1412
+ // console.error("msg", err) would lose the message, so a call that passes an
1413
+ // Error is collapsed into one string first. Calls without an Error keep their
1414
+ // args as-is (structured logs stay structured).
1415
+ if (!globalThis.__canopyConsolePatched) {
1416
+ globalThis.__canopyConsolePatched = true;
1417
+ for (const level of ["log", "info", "warn", "error", "debug"]) {
1418
+ const original = console[level];
1419
+ if (typeof original !== "function") continue;
1420
+ console[level] = function (...args) {
1421
+ if (!args.some((arg) => arg instanceof Error)) return original.apply(this, args);
1422
+ return original.call(this, args.map(describeLogArg).join(" "));
1423
+ };
1424
+ }
1291
1425
  }
1292
1426
 
1293
1427
  // Transcribed from IDENTITY_STAMP_HEADERS in @mediamonks/canopy-data-plane.
@@ -1311,6 +1445,19 @@ const IDENTITY_STAMP_HEADERS = [
1311
1445
  "x-canopy-token",
1312
1446
  ];
1313
1447
 
1448
+ // Free text (names, emails) — transcribed from decodeHeaderText in
1449
+ // caller-headers.ts: text that isn't plain ASCII arrives as UTF-8'' plus
1450
+ // percent-encoded UTF-8; anything else reads as-is.
1451
+ function textHeader(headers, name) {
1452
+ const value = (headers.get(name) || "").trim();
1453
+ if (!/^utf-8''/i.test(value)) return value;
1454
+ try {
1455
+ return decodeURIComponent(value.slice(7)).trim();
1456
+ } catch {
1457
+ return value;
1458
+ }
1459
+ }
1460
+
1314
1461
  // App roles (project-roles) — transcribed from rolesFromHeaders in
1315
1462
  // caller-headers.ts: undefined without the header (an older gateway), so the
1316
1463
  // property stays absent rather than [].
@@ -1329,8 +1476,8 @@ function userFromHeaders(headers) {
1329
1476
  const roles = rolesFromHeaders(headers);
1330
1477
  return {
1331
1478
  sub,
1332
- email: (headers.get("x-canopy-user-email") || "").trim(),
1333
- name: (headers.get("x-canopy-user-name") || "").trim(),
1479
+ email: textHeader(headers, "x-canopy-user-email"),
1480
+ name: textHeader(headers, "x-canopy-user-name"),
1334
1481
  ...(roles && { roles }),
1335
1482
  };
1336
1483
  }
@@ -1350,8 +1497,8 @@ function projectCallerFromHeaders(headers, id) {
1350
1497
  ? {
1351
1498
  kind: actingKind,
1352
1499
  id: actingId,
1353
- email: (headers.get("x-canopy-acting-email") || "").trim(),
1354
- name: (headers.get("x-canopy-acting-name") || "").trim(),
1500
+ email: textHeader(headers, "x-canopy-acting-email"),
1501
+ name: textHeader(headers, "x-canopy-acting-name"),
1355
1502
  agent: headers.get("x-canopy-acting-agent") === "1",
1356
1503
  roles: (headers.get("x-canopy-acting-roles") || "")
1357
1504
  .split(",")
@@ -1364,7 +1511,7 @@ function projectCallerFromHeaders(headers, id) {
1364
1511
  id,
1365
1512
  project,
1366
1513
  channel,
1367
- name: (headers.get("x-canopy-identity-name") || "").trim() || project,
1514
+ name: textHeader(headers, "x-canopy-identity-name") || project,
1368
1515
  email: "",
1369
1516
  agent: false,
1370
1517
  roles: [],
@@ -1416,7 +1563,7 @@ function callerFromHeaders(headers) {
1416
1563
  kind: "key",
1417
1564
  id,
1418
1565
  email: "",
1419
- name: (headers.get("x-canopy-identity-name") || "").trim() || token.name,
1566
+ name: textHeader(headers, "x-canopy-identity-name") || token.name,
1420
1567
  agent: false,
1421
1568
  roles: [],
1422
1569
  token,
@@ -1427,8 +1574,8 @@ function callerFromHeaders(headers) {
1427
1574
  return {
1428
1575
  kind,
1429
1576
  id,
1430
- email: (headers.get("x-canopy-identity-email") || "").trim(),
1431
- name: (headers.get("x-canopy-identity-name") || "").trim(),
1577
+ email: textHeader(headers, "x-canopy-identity-email"),
1578
+ name: textHeader(headers, "x-canopy-identity-name"),
1432
1579
  agent: headers.get("x-canopy-caller") === "agent",
1433
1580
  ...(roles && { roles }),
1434
1581
  token: token && token.kind === "personal" ? token : null,
@@ -1587,6 +1734,37 @@ function createCanopyFetch(apiUrl, inboundHeaders, upstream) {
1587
1734
  // canopy.db.dialect() (D15): raw SQL is the target's own. D1 carries no
1588
1735
  // dialect, so it reads as sqlite; the Google Cloud runtime's binding says
1589
1736
  // postgres.
1737
+ // pg parity: returned rows for reads, affected rows for writes.
1738
+ function dbResult(res) {
1739
+ const rows = (res && res.results) || [];
1740
+ const changes = res && res.meta && typeof res.meta.changes === "number" ? res.meta.changes : 0;
1741
+ return { rows, rowCount: rows.length > 0 ? rows.length : changes };
1742
+ }
1743
+
1744
+ // The batch contract (data-plane batch.ts validateBatch, kept equal by a
1745
+ // test): an array of at most this many { sql, params } entries, checked
1746
+ // before anything runs.
1747
+ const BATCH_MAX_STATEMENTS = 1000;
1748
+ function checkBatch(statements) {
1749
+ if (!Array.isArray(statements)) throw new Error("statements must be an array");
1750
+ if (statements.length > BATCH_MAX_STATEMENTS) {
1751
+ throw new Error(
1752
+ "a batch holds at most " + BATCH_MAX_STATEMENTS + " statements (got " + statements.length + ")",
1753
+ );
1754
+ }
1755
+ return statements.map((s, i) => {
1756
+ if (!s || typeof s !== "object" || typeof s.sql !== "string" || s.sql.trim() === "") {
1757
+ throw new Error("statement " + i + ": expected { sql: string, params?: [] }");
1758
+ }
1759
+ const params = s.params == null ? [] : s.params;
1760
+ const scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
1761
+ if (!Array.isArray(params) || !params.every(scalar)) {
1762
+ throw new Error("statement " + i + ": params must be string/number/boolean/null values");
1763
+ }
1764
+ return { sql: s.sql, params };
1765
+ });
1766
+ }
1767
+
1590
1768
  function wrapDb(d1) {
1591
1769
  if (!d1) return null;
1592
1770
  return {
@@ -1596,10 +1774,15 @@ function wrapDb(d1) {
1596
1774
  .prepare(text)
1597
1775
  .bind(...(params || []))
1598
1776
  .all();
1599
- const rows = res.results || [];
1600
- const changes = res.meta && typeof res.meta.changes === "number" ? res.meta.changes : 0;
1601
- // pg parity: returned rows for reads, affected rows for writes.
1602
- return { rows, rowCount: rows.length > 0 ? rows.length : changes };
1777
+ return dbResult(res);
1778
+ },
1779
+ // One round trip, all-or-nothing (worker-db-batch): D1's batch() is one
1780
+ // transaction; the Google Cloud facade runs it as one on its side.
1781
+ async batch(statements) {
1782
+ const checked = checkBatch(statements);
1783
+ if (checked.length === 0) return [];
1784
+ const results = await d1.batch(checked.map((s) => d1.prepare(s.sql).bind(...s.params)));
1785
+ return results.map(dbResult);
1603
1786
  },
1604
1787
  };
1605
1788
  }
@@ -1981,9 +2164,14 @@ export default {
1981
2164
  // gateway forwards /api/* alone), and the raw binding never leaves this
1982
2165
  // closure: the bundle still sees only env.DB. The marker header lets the
1983
2166
  // caller tell this route apart from a bundle that answered the same path
1984
- // under an older shim, which never saw it.
2167
+ // under an older shim, which never saw it. x-canopy-db-batch marks a shim
2168
+ // that takes { sql, params } entries in "statements" (worker-db-batch).
1985
2169
  if (url.pathname === "/__canopy/db" && request.method === "POST") {
1986
- const dbHeaders = { "content-type": "application/json", "x-canopy-db": "1" };
2170
+ const dbHeaders = {
2171
+ "content-type": "application/json",
2172
+ "x-canopy-db": "1",
2173
+ "x-canopy-db-batch": "1",
2174
+ };
1987
2175
  const d1 = env.__CANOPY_DB;
1988
2176
  if (!d1) {
1989
2177
  return new Response(JSON.stringify({ error: "no_database" }), {
@@ -2005,6 +2193,35 @@ export default {
2005
2193
  headers: dbHeaders,
2006
2194
  });
2007
2195
  }
2196
+ // Parameterised statements ({ sql, params } entries): one atomic batch,
2197
+ // every statement's result back — canopy-data's POST /db/batch.
2198
+ if (statements && statements.some((s) => typeof s !== "string")) {
2199
+ let checked;
2200
+ try {
2201
+ checked = checkBatch(statements);
2202
+ } catch (err) {
2203
+ return new Response(
2204
+ JSON.stringify({ error: "invalid_batch", detail: err instanceof Error ? err.message : String(err) }),
2205
+ { status: 400, headers: dbHeaders },
2206
+ );
2207
+ }
2208
+ try {
2209
+ const batch =
2210
+ checked.length === 0
2211
+ ? []
2212
+ : await d1.batch(checked.map((s) => d1.prepare(s.sql).bind(...s.params)));
2213
+ const out = batch.map((r) => ({
2214
+ results: r.results || [],
2215
+ meta: { changes: r.meta && typeof r.meta.changes === "number" ? r.meta.changes : 0 },
2216
+ }));
2217
+ return new Response(JSON.stringify({ batch: out }), { headers: dbHeaders });
2218
+ } catch (err) {
2219
+ return new Response(
2220
+ JSON.stringify({ error: "sql_error", detail: err instanceof Error ? err.message : String(err) }),
2221
+ { status: 400, headers: dbHeaders },
2222
+ );
2223
+ }
2224
+ }
2008
2225
  try {
2009
2226
  let res;
2010
2227
  if (statements) {
@@ -2154,4 +2371,14 @@ export default {
2154
2371
  };
2155
2372
  `;
2156
2373
  //#endregion
2374
+ //#region ../data-plane/src/sqlite-dump.ts
2375
+ /** The platform's own doc-store index: restore and the staging clone rebuild it. */
2376
+ const DOC_STORE_FTS = "_canopy_docs_fts";
2377
+ new Set([
2378
+ "insert",
2379
+ "delete",
2380
+ "update"
2381
+ ].map((op) => `${DOC_STORE_FTS}_${op}`));
2382
+ new TextEncoder();
2383
+ //#endregion
2157
2384
  export { readPersonCaller as a, dbRouter as c, HOST_LABEL_SEPARATOR as d, STAGING_LABEL_PREFIX as f, isCreateOnly as h, CALLER_HEADER as i, hasPrivateNames as l, blobRouter as m, redactCanopyCredentials as n, readUser as o, STREAMED_BLOB_BYTES as p, stampWorkerHeaders as r, realtimeRouter as s, WORKER_ATTEST_HEADER as t, META_COLUMNS as u };
@@ -1,6 +1,6 @@
1
- import { d as projectUrl, f as resolveProject, m as stagingUrl, s as parseVersionArg, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { a as requireTty, i as reportErrors, n as formatDateTime, o as spinner$1, s as unwrap, t as confirmTypedSlug } from "./ui-9f_lF2Ak.mjs";
1
+ import { d as projectUrl, f as resolveProject, m as stagingUrl, s as parseVersionArg, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { a as requireTty, i as reportErrors, n as formatDateTime, o as spinner$1, s as unwrap, t as confirmTypedSlug } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/staging.ts
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, l as projectDirArgs, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors, n as formatDateTime } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, l as projectDirArgs, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors, n as formatDateTime } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  const tokenCommand = defineCommand({
6
6
  meta: {
@@ -1,4 +1,4 @@
1
- import { t as ApiError } from "./api-fmc8CEMT.mjs";
1
+ import { t as ApiError } from "./api-CpG-9WSe.mjs";
2
2
  import { spawn } from "node:child_process";
3
3
  import { cancel, isCancel, spinner, text } from "@clack/prompts";
4
4
  //#region src/ui.ts
@@ -1,5 +1,5 @@
1
1
  import { t as PACKAGE_NAME } from "./version-check-CcsA1QjI.mjs";
2
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
2
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
3
3
  import { defineCommand } from "citty";
4
4
  import { spawn } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
@@ -112,7 +112,7 @@ const upgradeCommand = defineCommand({
112
112
  const spec = `${PACKAGE_NAME}@${args.version ?? "latest"}`;
113
113
  const command = pmCommand(pm);
114
114
  const cmd = installArgs(pm, spec);
115
- const { skillInstalled } = await import("./skill-984KseKb.mjs");
115
+ const { skillInstalled } = await import("./skill-CoPNcCaM.mjs");
116
116
  const { homedir } = await import("node:os");
117
117
  const refreshGlobal = skillInstalled(homedir());
118
118
  const refreshRepo = process.cwd() !== homedir() && skillInstalled(process.cwd());
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { i as reportErrors } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { i as reportErrors } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  //#region src/usage.ts
6
6
  /**
@@ -1,6 +1,6 @@
1
- import { f as resolveProject, u as projectFlagArgs } from "./site-BcZ0LOvm.mjs";
2
- import { a as apiRequest, m as withContext } from "./api-fmc8CEMT.mjs";
3
- import { a as requireTty, i as reportErrors, s as unwrap } from "./ui-9f_lF2Ak.mjs";
1
+ import { f as resolveProject, u as projectFlagArgs } from "./site-Bz-fEyKS.mjs";
2
+ import { a as apiRequest, m as withContext } from "./api-CpG-9WSe.mjs";
3
+ import { a as requireTty, i as reportErrors, s as unwrap } from "./ui-BUeiY_zZ.mjs";
4
4
  import { defineCommand } from "citty";
5
5
  import * as p from "@clack/prompts";
6
6
  //#region src/versions.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mediamonks/canopy-cli",
3
- "version": "0.7.57",
3
+ "version": "0.7.59",
4
4
  "description": "Canopy CLI — create, develop and deploy Canopy projects.",
5
5
  "bin": {
6
6
  "canopy": "./dist/index.mjs"
@@ -1,2 +0,0 @@
1
- import { n as devCommand } from "./dev-qp1VRNM_.mjs";
2
- export { devCommand };
@@ -1,2 +0,0 @@
1
- import { a as templateCommand } from "./project-template-BnX47DpF.mjs";
2
- export { templateCommand };
@@ -1,2 +0,0 @@
1
- import { o as repoCommand } from "./repo-DD3eK1P_.mjs";
2
- export { repoCommand };