orqevio 1.0.2 → 1.1.0

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 (194) hide show
  1. package/dist/web/assets/{AccessKeyReveal-D8iaHAmc.js → AccessKeyReveal-DBMDUyjA.js} +2 -2
  2. package/dist/web/assets/AccessRows-C-Jn-MrD.js +1 -0
  3. package/dist/web/assets/ActivityList-BCthFm2C.js +1 -0
  4. package/dist/web/assets/AgentsPage-C0SAIziE.js +1 -0
  5. package/dist/web/assets/Attachments-w5KikYPZ.js +215 -0
  6. package/dist/web/assets/Avatar-BcMhQMeL.js +1 -0
  7. package/dist/web/assets/BoardPage-CTE1631b.js +1 -0
  8. package/dist/web/assets/{Button-Btbho6sH.js → Button-ClwM2Rw6.js} +1 -1
  9. package/dist/web/assets/CardItem-BK2PGymN.js +5 -0
  10. package/dist/web/assets/Checkbox-I7UAluqN.js +1 -0
  11. package/dist/web/assets/ColorPicker-D3xHu4M1.js +1 -0
  12. package/dist/web/assets/ConsentPage-bIA7yHuZ.js +1 -0
  13. package/dist/web/assets/CopyButton-BjA1b29F.js +1 -0
  14. package/dist/web/assets/DocPage-DcF8R9CQ.js +1 -0
  15. package/dist/web/assets/{EmptyState-BK-MD-22.js → EmptyState-DMW8GdU_.js} +1 -1
  16. package/dist/web/assets/Field-oe5EHMEz.js +1 -0
  17. package/dist/web/assets/HomePage-Dlpg4r_w.js +1 -0
  18. package/dist/web/assets/Menu--S2cHUj4.js +1 -0
  19. package/dist/web/assets/PageHeader-BeJqOSzf.js +1 -0
  20. package/dist/web/assets/Popover-MlZiOWxh.js +1 -0
  21. package/dist/web/assets/ProjectPage-BAwijKJr.js +1 -0
  22. package/dist/web/assets/ProjectSettingsDialog-DSp3JA2z.js +1 -0
  23. package/dist/web/assets/{Segmented-CF8X5UQP.js → Segmented-DDptqKTZ.js} +1 -1
  24. package/dist/web/assets/SettingsPage-Bot3OWuP.js +1 -0
  25. package/dist/web/assets/States-ss8YCX3J.js +1 -0
  26. package/dist/web/assets/TokenCard-B9gn2tQA.js +1 -0
  27. package/dist/web/assets/{Trans-CZ4Nv-G9.js → Trans-Cpev0SXN.js} +1 -1
  28. package/dist/web/assets/TrashPage-BQ4vCVb9.js +1 -0
  29. package/dist/web/assets/VaultPage-BlXfdUw7.js +3 -0
  30. package/dist/web/assets/actions-DTIyi0mf.js +1 -0
  31. package/dist/web/assets/{activity-C7wpXysw.js → activity-6zHhcitv.js} +1 -1
  32. package/dist/web/assets/{activity-CaibDu14.js → activity-CWpwjlzR.js} +1 -1
  33. package/dist/web/assets/{activity-BkftiStp.js → activity-CdqdeoxV.js} +1 -1
  34. package/dist/web/assets/{activity-CFR4UTGM.js → activity-DGUXp5QL.js} +1 -1
  35. package/dist/web/assets/activity-Yp9xRGgk.js +1 -0
  36. package/dist/web/assets/{activity-BHGI6Z2D.js → activity-ZNUvkr3p.js} +1 -1
  37. package/dist/web/assets/{activity-Cp8KuBts.js → activity-_4kW2ZJ_.js} +1 -1
  38. package/dist/web/assets/{activity-ayIU9KmV.js → activity-mAare-yB.js} +1 -1
  39. package/dist/web/assets/agents-3HUiV4tV.js +1 -0
  40. package/dist/web/assets/agents-CJMhiUW3.js +1 -0
  41. package/dist/web/assets/agents-CjiLfJS9.js +1 -0
  42. package/dist/web/assets/agents-DwUimfIe.js +1 -0
  43. package/dist/web/assets/agents-R0c_yDCD.js +1 -0
  44. package/dist/web/assets/agents-c6F7y9Af.js +1 -0
  45. package/dist/web/assets/agents-sA8xOJfc.js +1 -0
  46. package/dist/web/assets/{arrow-up-right-xXLe7dy5.js → arrow-up-right-CirWuKKd.js} +1 -1
  47. package/dist/web/assets/boards-BTAHuwCR.js +1 -0
  48. package/dist/web/assets/boards-CKwJtefi.js +1 -0
  49. package/dist/web/assets/boards-CeiIWYk-.js +1 -0
  50. package/dist/web/assets/boards-DSTXu61F.js +1 -0
  51. package/dist/web/assets/boards-DkyiWQSW.js +1 -0
  52. package/dist/web/assets/boards-hABacqWX.js +1 -0
  53. package/dist/web/assets/boards-mFQFxBPQ.js +1 -0
  54. package/dist/web/assets/check-B8DqgyOr.js +1 -0
  55. package/dist/web/assets/chevron-right-BXOWYq-U.js +1 -0
  56. package/dist/web/assets/{clock-BRq3Eqj4.js → clock-B_VxvAAa.js} +1 -1
  57. package/dist/web/assets/confirm-D9CmdABH.js +41 -0
  58. package/dist/web/assets/docs-BiIxmBdC.js +1 -0
  59. package/dist/web/assets/docs-CZq019Fr.js +1 -0
  60. package/dist/web/assets/docs-CctrfBzG.js +1 -0
  61. package/dist/web/assets/docs-CxyPUV8q.js +1 -0
  62. package/dist/web/assets/docs-DvgTX1bm.js +1 -0
  63. package/dist/web/assets/docs-NO6PWaeN.js +1 -0
  64. package/dist/web/assets/docs-wmJ1fgqN.js +1 -0
  65. package/dist/web/assets/{download-CcY7y-p1.js → download-CG4Kvbuv.js} +1 -1
  66. package/dist/web/assets/{errors-BjhuCALu.js → errors-CJTyAPcw.js} +1 -1
  67. package/dist/web/assets/{errors-Bj5m9UTT.js → errors-DcAK3Axg.js} +1 -1
  68. package/dist/web/assets/{errors-DCKVrh2b.js → errors-DfqPLtND.js} +1 -1
  69. package/dist/web/assets/{errors-x1B7DZKj.js → errors-Dy51ouo4.js} +1 -1
  70. package/dist/web/assets/{errors-DTeT1QaQ.js → errors-Z5PDTKIL.js} +1 -1
  71. package/dist/web/assets/{errors-hqibHHps.js → errors-ezWDkBsu.js} +1 -1
  72. package/dist/web/assets/{errors-CbK3TofU.js → errors-tpMDhE_P.js} +1 -1
  73. package/dist/web/assets/{eye-0AAym_Rc.js → eye-DOmrZizG.js} +1 -1
  74. package/dist/web/assets/{file-plus-dA3dSRUX.js → file-plus-Do0kXuaQ.js} +1 -1
  75. package/dist/web/assets/{folder-open-Ewe1HrNf.js → folder-open-dQd_UG6z.js} +1 -1
  76. package/dist/web/assets/format-ClqopOxc.js +1 -0
  77. package/dist/web/assets/history-BR28CO2x.js +1 -0
  78. package/dist/web/assets/history-BuXL4ZO8.js +1 -0
  79. package/dist/web/assets/history-CBSq8sT_.js +1 -0
  80. package/dist/web/assets/history-CUFddWVE.js +1 -0
  81. package/dist/web/assets/history-Cpw0AAmb.js +1 -0
  82. package/dist/web/assets/history-DXLLakuK.js +1 -0
  83. package/dist/web/assets/history-DpSejrKr.js +1 -0
  84. package/dist/web/assets/index-B2GZPn61.js +14 -0
  85. package/dist/web/assets/index-B6GX5zxU.css +2 -0
  86. package/dist/web/assets/{lock-keyhole-D9nhFofN.js → lock-keyhole-BW42UXDZ.js} +1 -1
  87. package/dist/web/assets/paperclip-Jdvar28f.js +1 -0
  88. package/dist/web/assets/{pencil-BLKUFMJd.js → pencil-D9DAny5h.js} +1 -1
  89. package/dist/web/assets/plus-D07TzhmN.js +1 -0
  90. package/dist/web/assets/queries-CNpEWLps.js +64 -0
  91. package/dist/web/assets/realtime-CUI9Wfs8.js +1 -0
  92. package/dist/web/assets/rotate-ccw-CILtVOFP.js +1 -0
  93. package/dist/web/assets/{search-DMRKd8Cr.js → search-vXSGUzpg.js} +1 -1
  94. package/dist/web/assets/{session-BAxO2EgV.js → session-DIDP5B07.js} +1 -1
  95. package/dist/web/assets/settings-BDfqTbHE.js +1 -0
  96. package/dist/web/assets/settings-BW0zBLJn.js +1 -0
  97. package/dist/web/assets/settings-BYv1UcVK.js +1 -0
  98. package/dist/web/assets/settings-C7vmkddK.js +1 -0
  99. package/dist/web/assets/settings-CK3tlBqd.js +1 -0
  100. package/dist/web/assets/settings-CWBjLZeX.js +1 -0
  101. package/dist/web/assets/settings-R-xZf6BT.js +1 -0
  102. package/dist/web/assets/shell-BDp_dyvw.js +1 -0
  103. package/dist/web/assets/shell-C6TGc8Za.js +1 -0
  104. package/dist/web/assets/shell-CFZKdSNl.js +1 -0
  105. package/dist/web/assets/shell-CtEP2nnE.js +1 -0
  106. package/dist/web/assets/shell-DKm9aLr8.js +1 -0
  107. package/dist/web/assets/shell-DKu6Snuz.js +1 -0
  108. package/dist/web/assets/shell-DhehnO0K.js +1 -0
  109. package/dist/web/assets/{shield-exclamation-point-TzY-81Bq.js → shield-exclamation-point-BLDMJINf.js} +1 -1
  110. package/dist/web/assets/{square-kanban-ly6jmUnZ.js → square-kanban-B3kmSSml.js} +1 -1
  111. package/dist/web/assets/sticky-note-BPVTTfp2.js +1 -0
  112. package/dist/web/assets/tag-DqhP3wln.js +1 -0
  113. package/dist/web/assets/trash-BJO-DupK.js +1 -0
  114. package/dist/web/assets/trash-BQQD171k.js +1 -0
  115. package/dist/web/assets/trash-Bxu4b7lw.js +1 -0
  116. package/dist/web/assets/trash-CyqM_Llh.js +1 -0
  117. package/dist/web/assets/trash-DFqgqLEp.js +1 -0
  118. package/dist/web/assets/{trash-CJAi39PH.js → trash-DTgTEaHd.js} +1 -1
  119. package/dist/web/assets/trash-lAGOyPXd.js +1 -0
  120. package/dist/web/assets/trash-mj787YHq.js +1 -0
  121. package/dist/web/assets/trash-pWFmQnYh.js +1 -0
  122. package/dist/web/assets/{triangle-exclamation-point-CxY_KMDD.js → triangle-exclamation-point-B5Cq1xJs.js} +1 -1
  123. package/dist/web/assets/{workspace-CUnAQ10Q.js → workspace-CBlyhMjO.js} +1 -1
  124. package/dist/web/index.html +35 -33
  125. package/dist/worker/index.js +1979 -214
  126. package/package.json +1 -1
  127. package/dist/web/assets/AccessRows-unT7pvaN.js +0 -1
  128. package/dist/web/assets/ActivityList-5kkQfKan.js +0 -1
  129. package/dist/web/assets/AgentsPage-CJYPGW11.js +0 -1
  130. package/dist/web/assets/Attachments-W-66xscM.js +0 -214
  131. package/dist/web/assets/Avatar-Ds47Du6D.js +0 -1
  132. package/dist/web/assets/BoardPage-BzP18JZ2.js +0 -1
  133. package/dist/web/assets/CardItem-DOZjD-y4.js +0 -5
  134. package/dist/web/assets/Checkbox-DYleqiFb.js +0 -1
  135. package/dist/web/assets/ColorPicker-C67TVWyM.js +0 -1
  136. package/dist/web/assets/ConsentPage-DdmIld0a.js +0 -1
  137. package/dist/web/assets/CopyButton-BSygyOA8.js +0 -1
  138. package/dist/web/assets/DocPage-Bou9VU1o.js +0 -1
  139. package/dist/web/assets/Field-BzrGz77l.js +0 -41
  140. package/dist/web/assets/HomePage-B4r2hsLa.js +0 -1
  141. package/dist/web/assets/Menu-B2IsRarH.js +0 -1
  142. package/dist/web/assets/PageHeader-DQFfF3dC.js +0 -1
  143. package/dist/web/assets/Popover-CABN9JQJ.js +0 -1
  144. package/dist/web/assets/ProjectPage-Oz1y-22_.js +0 -1
  145. package/dist/web/assets/ProjectSettingsDialog-C1CyAGKv.js +0 -1
  146. package/dist/web/assets/SettingsPage-D8jrBXVO.js +0 -1
  147. package/dist/web/assets/States-B9aFGoJ7.js +0 -1
  148. package/dist/web/assets/TokenCard-Bca8a7bs.js +0 -1
  149. package/dist/web/assets/VaultPage-CbnaGof3.js +0 -3
  150. package/dist/web/assets/actions-CuhPuiCb.js +0 -1
  151. package/dist/web/assets/activity-jMyOg6vJ.js +0 -1
  152. package/dist/web/assets/agents-B2XabUwG.js +0 -1
  153. package/dist/web/assets/agents-COJYAQfq.js +0 -1
  154. package/dist/web/assets/agents-D7tpgjuk.js +0 -1
  155. package/dist/web/assets/agents-DJ-oR1WA.js +0 -1
  156. package/dist/web/assets/agents-DLrh2pf6.js +0 -1
  157. package/dist/web/assets/agents-DMp1p8Qv.js +0 -1
  158. package/dist/web/assets/agents-D_gfLGIh.js +0 -1
  159. package/dist/web/assets/boards-BfXxNbjL.js +0 -1
  160. package/dist/web/assets/boards-BysuKeCh.js +0 -1
  161. package/dist/web/assets/boards-BzBkr2as.js +0 -1
  162. package/dist/web/assets/boards-C4m0VqXK.js +0 -1
  163. package/dist/web/assets/boards-CiHbxckf.js +0 -1
  164. package/dist/web/assets/boards-oiLnHcBl.js +0 -1
  165. package/dist/web/assets/boards-uxzlybUT.js +0 -1
  166. package/dist/web/assets/bot-C4jQSYTS.js +0 -1
  167. package/dist/web/assets/check-BE-kG6EN.js +0 -1
  168. package/dist/web/assets/docs-1w1qMhXT.js +0 -1
  169. package/dist/web/assets/docs-BDzOa1yl.js +0 -1
  170. package/dist/web/assets/docs-BrgMwu04.js +0 -1
  171. package/dist/web/assets/docs-CMM1mWDN.js +0 -1
  172. package/dist/web/assets/docs-D4GytCg-.js +0 -1
  173. package/dist/web/assets/docs-WZJP9ehA.js +0 -1
  174. package/dist/web/assets/docs-lc4Fuqxy.js +0 -1
  175. package/dist/web/assets/format-DFP4kHwY.js +0 -1
  176. package/dist/web/assets/index-BwlT1VPI.css +0 -2
  177. package/dist/web/assets/index-De_HhHxO.js +0 -14
  178. package/dist/web/assets/plus-Bfyl1Cnf.js +0 -1
  179. package/dist/web/assets/queries-DnrECs2M.js +0 -64
  180. package/dist/web/assets/realtime-CMHYgQ_y.js +0 -1
  181. package/dist/web/assets/settings-BPFNhdWr.js +0 -1
  182. package/dist/web/assets/settings-BWaFf59A.js +0 -1
  183. package/dist/web/assets/settings-CAp-i3rq.js +0 -1
  184. package/dist/web/assets/settings-DClD_ufE.js +0 -1
  185. package/dist/web/assets/settings-DN08srMi.js +0 -1
  186. package/dist/web/assets/settings-DOoufuYZ.js +0 -1
  187. package/dist/web/assets/settings-zS8H2ZNY.js +0 -1
  188. package/dist/web/assets/shell-BBK5NJFB.js +0 -1
  189. package/dist/web/assets/shell-BJfYCj5Q.js +0 -1
  190. package/dist/web/assets/shell-BJoyar8n.js +0 -1
  191. package/dist/web/assets/shell-BiFljnPL.js +0 -1
  192. package/dist/web/assets/shell-CkAa8NM5.js +0 -1
  193. package/dist/web/assets/shell-FiDu6Ti9.js +0 -1
  194. package/dist/web/assets/shell-a4R2bNYB.js +0 -1
@@ -7823,6 +7823,23 @@ __name(securityHeaders, "securityHeaders");
7823
7823
  // ../../packages/shared/src/colors.ts
7824
7824
  var PALETTE = ["tomato", "amber", "lime", "jade", "teal", "cobalt", "iris", "rose", "slate"];
7825
7825
 
7826
+ // ../../packages/shared/src/diff.ts
7827
+ var splitLines = /* @__PURE__ */ __name((text2) => text2 === "" ? [] : text2.split("\n"), "splitLines");
7828
+ function lineStats(before, after) {
7829
+ const counts = /* @__PURE__ */ new Map();
7830
+ for (const line of splitLines(before)) counts.set(line, (counts.get(line) ?? 0) + 1);
7831
+ let added = 0;
7832
+ for (const line of splitLines(after)) {
7833
+ const left = counts.get(line) ?? 0;
7834
+ if (left > 0) counts.set(line, left - 1);
7835
+ else added++;
7836
+ }
7837
+ let removed = 0;
7838
+ for (const left of counts.values()) removed += left;
7839
+ return { added, removed };
7840
+ }
7841
+ __name(lineStats, "lineStats");
7842
+
7826
7843
  // ../../packages/shared/src/links.ts
7827
7844
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
7828
7845
  function extractReferences(markdown) {
@@ -28259,7 +28276,7 @@ function date4(params) {
28259
28276
  __name(date4, "date");
28260
28277
 
28261
28278
  // ../../packages/shared/src/scopes.ts
28262
- var SCOPES = ["tasks:read", "tasks:write", "docs:read", "docs:write"];
28279
+ var SCOPES = ["tasks:read", "tasks:write", "docs:read", "docs:write", "organize"];
28263
28280
 
28264
28281
  // ../../packages/shared/src/schemas.ts
28265
28282
  var id = external_exports.uuid();
@@ -28340,12 +28357,14 @@ var pageUpdateInput = external_exports.object({
28340
28357
  baseVersion: external_exports.number().int().min(1).optional()
28341
28358
  });
28342
28359
  var pageMoveInput = external_exports.object({ parentId: id.nullable(), index });
28360
+ var attachmentMoveInput = external_exports.object({ cardId: id.optional(), pageId: id.optional() }).refine((v) => v.cardId === void 0 !== (v.pageId === void 0), { message: "Send either cardId or pageId" });
28343
28361
  var tokenCreateInput = external_exports.object({
28344
28362
  name: name(60),
28345
28363
  workspaceId: id,
28346
28364
  scopes: external_exports.array(external_exports.enum(SCOPES)).min(1, "Select at least one permission"),
28347
28365
  expiresInDays: external_exports.union([external_exports.literal(30), external_exports.literal(90), external_exports.literal(365)]).nullable()
28348
28366
  });
28367
+ var tokenUpdateInput = external_exports.object({ organize: external_exports.boolean() });
28349
28368
  var b64 = external_exports.string().regex(/^[A-Za-z0-9+/=_-]+$/).max(4096);
28350
28369
  var kdfSchema = external_exports.object({
28351
28370
  algorithm: external_exports.literal("argon2id"),
@@ -28371,10 +28390,64 @@ var oauthDecisionInput = oauthRequestInput.extend({
28371
28390
  /** Revoke this application's earlier access to the workspace once the new one is created. */
28372
28391
  replace: external_exports.boolean().optional()
28373
28392
  });
28393
+ var undoInput = external_exports.object({
28394
+ ids: external_exports.array(id).min(1).max(500).optional(),
28395
+ since: id.optional(),
28396
+ conflicts: external_exports.enum(["ask", "skip", "force"]).default("ask"),
28397
+ /** Only say what would happen: nothing is undone. */
28398
+ dryRun: external_exports.boolean().default(false)
28399
+ }).refine((v) => v.ids === void 0 !== (v.since === void 0), { message: "Send either ids or since" });
28374
28400
 
28375
28401
  // ../../packages/shared/src/types.ts
28376
28402
  var INSTALL_KINDS = ["cli", "button", "docker", "source", "cloudflare"];
28377
28403
  var installKind = /* @__PURE__ */ __name((value, fallback) => INSTALL_KINDS.includes(value ?? "") ? value : fallback, "installKind");
28404
+ var TRASH_KINDS = ["project", "board", "column", "card", "page", "attachment", "label", "checklist", "checklist_item", "link"];
28405
+ var TRASH_DAYS = 30;
28406
+ var HISTORY_KINDS = [
28407
+ "page.created",
28408
+ "page.title",
28409
+ "page.icon",
28410
+ "page.content",
28411
+ "page.moved",
28412
+ "page.deleted",
28413
+ "page.restored",
28414
+ "card.created",
28415
+ "card.title",
28416
+ "card.description",
28417
+ "card.due",
28418
+ "card.labels",
28419
+ "card.moved",
28420
+ "card.archived",
28421
+ "card.deleted",
28422
+ "card.restored",
28423
+ "card.linked",
28424
+ "card.unlinked",
28425
+ "checklist.created",
28426
+ "checklist.title",
28427
+ "checklist.deleted",
28428
+ "checklist.restored",
28429
+ "item.created",
28430
+ "item.text",
28431
+ "item.done",
28432
+ "item.deleted",
28433
+ "item.restored",
28434
+ "attachment.created",
28435
+ "attachment.deleted",
28436
+ "attachment.restored",
28437
+ "attachment.moved"
28438
+ ];
28439
+ var HISTORY_TEXT_KINDS = /* @__PURE__ */ new Set([
28440
+ "page.title",
28441
+ "page.icon",
28442
+ "page.content",
28443
+ "card.title",
28444
+ "card.description",
28445
+ "card.due",
28446
+ "checklist.title",
28447
+ "item.text"
28448
+ ]);
28449
+ var HISTORY_BODY_KINDS = /* @__PURE__ */ new Set(["page.content", "card.description"]);
28450
+ var HISTORY_DAYS = 30;
28378
28451
 
28379
28452
  // ../../packages/shared/src/uploads.ts
28380
28453
  var UPLOAD_NAME_HEADER = "X-File-Name";
@@ -31353,6 +31426,43 @@ var PrimaryKey2 = class {
31353
31426
  };
31354
31427
 
31355
31428
  // ../../node_modules/.pnpm/drizzle-orm@0.45.4_@cloudflare+workers-types@5.20261112.1_@types+better-sqlite3@9.6.0_@_b16c6a9aefdb6a18eed9dad740d7653e/node_modules/drizzle-orm/sqlite-core/utils.js
31429
+ function getTableConfig(table) {
31430
+ const columns2 = Object.values(table[SQLiteTable.Symbol.Columns]);
31431
+ const indexes = [];
31432
+ const checks = [];
31433
+ const primaryKeys = [];
31434
+ const uniqueConstraints = [];
31435
+ const foreignKeys = Object.values(table[SQLiteTable.Symbol.InlineForeignKeys]);
31436
+ const name2 = table[Table.Symbol.Name];
31437
+ const extraConfigBuilder = table[SQLiteTable.Symbol.ExtraConfigBuilder];
31438
+ if (extraConfigBuilder !== void 0) {
31439
+ const extraConfig = extraConfigBuilder(table[SQLiteTable.Symbol.Columns]);
31440
+ const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig);
31441
+ for (const builder of Object.values(extraValues)) {
31442
+ if (is(builder, IndexBuilder)) {
31443
+ indexes.push(builder.build(table));
31444
+ } else if (is(builder, CheckBuilder)) {
31445
+ checks.push(builder.build(table));
31446
+ } else if (is(builder, UniqueConstraintBuilder2)) {
31447
+ uniqueConstraints.push(builder.build(table));
31448
+ } else if (is(builder, PrimaryKeyBuilder2)) {
31449
+ primaryKeys.push(builder.build(table));
31450
+ } else if (is(builder, ForeignKeyBuilder2)) {
31451
+ foreignKeys.push(builder.build(table));
31452
+ }
31453
+ }
31454
+ }
31455
+ return {
31456
+ columns: columns2,
31457
+ indexes,
31458
+ foreignKeys,
31459
+ checks,
31460
+ primaryKeys,
31461
+ uniqueConstraints,
31462
+ name: name2
31463
+ };
31464
+ }
31465
+ __name(getTableConfig, "getTableConfig");
31356
31466
  function extractUsedTable(table) {
31357
31467
  if (is(table, SQLiteTable)) {
31358
31468
  return [`${table[Table.Symbol.BaseName]}`];
@@ -36395,6 +36505,7 @@ __export(schema_exports, {
36395
36505
  checklists: () => checklists,
36396
36506
  columns: () => columns,
36397
36507
  copyState: () => copyState,
36508
+ history: () => history,
36398
36509
  instance: () => instance,
36399
36510
  labels: () => labels,
36400
36511
  oauthCodes: () => oauthCodes,
@@ -36402,6 +36513,8 @@ __export(schema_exports, {
36402
36513
  pages: () => pages,
36403
36514
  projects: () => projects,
36404
36515
  sessions: () => sessions,
36516
+ trash: () => trash,
36517
+ trashRows: () => trashRows,
36405
36518
  users: () => users,
36406
36519
  vaultItems: () => vaultItems,
36407
36520
  vaults: () => vaults,
@@ -36717,6 +36830,72 @@ var activity = sqliteTable(
36717
36830
  index2("activity_token_idx").on(t.actorTokenId, t.createdAt)
36718
36831
  ]
36719
36832
  );
36833
+ var trash = sqliteTable(
36834
+ "trash",
36835
+ {
36836
+ id: id2(),
36837
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
36838
+ kind: text("kind", { enum: TRASH_KINDS }).notNull(),
36839
+ /** The id the item had (for a link, `<cardId>:<pageId>`). */
36840
+ entityId: text("entity_id").notNull(),
36841
+ title: text("title").notNull(),
36842
+ /** Where it was, for people: "Project › Board › Column". */
36843
+ location: text("location").notNull().default(""),
36844
+ contents: text("contents", { mode: "json" }).$type().notNull().$defaultFn(() => ({})),
36845
+ /** Size of the attachments it holds. */
36846
+ bytes: integer2("bytes").notNull().default(0),
36847
+ actorKind: text("actor_kind", { enum: ["user", "agent"] }).notNull(),
36848
+ actorUserId: text("actor_user_id").references(() => users.id, { onDelete: "set null" }),
36849
+ actorTokenId: text("actor_token_id").references(() => apiTokens.id, { onDelete: "set null" }),
36850
+ actorName: text("actor_name").notNull(),
36851
+ deletedAt: timestamp("deleted_at").notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
36852
+ expiresAt: timestamp("expires_at").notNull()
36853
+ },
36854
+ (t) => [index2("trash_workspace_idx").on(t.workspaceId, t.deletedAt), index2("trash_expires_idx").on(t.expiresAt)]
36855
+ );
36856
+ var trashRows = sqliteTable(
36857
+ "trash_rows",
36858
+ {
36859
+ /** Also the order in which the rows are inserted back: what holds something comes before it. */
36860
+ id: integer2("id").primaryKey(),
36861
+ trashId: text("trash_id").notNull().references(() => trash.id, { onDelete: "cascade" }),
36862
+ tableName: text("table_name").notNull(),
36863
+ /** The row exactly as stored, column by column. */
36864
+ data: text("data", { mode: "json" }).$type().notNull(),
36865
+ /** For attachments: their file stays in storage until the entry leaves the trash. */
36866
+ storageKey: text("storage_key")
36867
+ },
36868
+ (t) => [index2("trash_rows_trash_idx").on(t.trashId, t.id), index2("trash_rows_storage_idx").on(t.storageKey)]
36869
+ );
36870
+ var history = sqliteTable(
36871
+ "history",
36872
+ {
36873
+ id: id2(),
36874
+ workspaceId: text("workspace_id").notNull().references(() => workspaces.id, { onDelete: "cascade" }),
36875
+ entityType: text("entity_type", { enum: ["page", "card"] }).notNull(),
36876
+ entityId: text("entity_id").notNull(),
36877
+ kind: text("kind", { enum: HISTORY_KINDS }).notNull(),
36878
+ subjectId: text("subject_id"),
36879
+ before: text("before"),
36880
+ after: text("after"),
36881
+ meta: text("meta", { mode: "json" }).$type().notNull().$defaultFn(() => ({})),
36882
+ actorKind: text("actor_kind", { enum: ["user", "agent"] }).notNull(),
36883
+ actorUserId: text("actor_user_id").references(() => users.id, { onDelete: "set null" }),
36884
+ actorTokenId: text("actor_token_id").references(() => apiTokens.id, { onDelete: "set null" }),
36885
+ actorName: text("actor_name").notNull(),
36886
+ batchId: text("batch_id").notNull(),
36887
+ createdAt: createdAt(),
36888
+ updatedAt: updatedAt()
36889
+ },
36890
+ (t) => [
36891
+ index2("history_entity_idx").on(t.entityId, t.updatedAt),
36892
+ index2("history_subject_idx").on(t.subjectId),
36893
+ index2("history_user_idx").on(t.actorUserId, t.updatedAt),
36894
+ index2("history_token_idx").on(t.actorTokenId, t.updatedAt),
36895
+ index2("history_updated_idx").on(t.updatedAt),
36896
+ index2("history_batch_idx").on(t.batchId)
36897
+ ]
36898
+ );
36720
36899
  var vaults = sqliteTable("vaults", {
36721
36900
  userId: text("user_id").primaryKey().references(() => users.id, { onDelete: "cascade" }),
36722
36901
  kdf: text("kdf", { mode: "json" }).$type(),
@@ -36747,6 +36926,117 @@ function parse3(schema, data) {
36747
36926
  }
36748
36927
  __name(parse3, "parse");
36749
36928
 
36929
+ // src/services/tokens.ts
36930
+ var TOKEN_PREFIX = "orq_";
36931
+ function consistentScopes(requested) {
36932
+ const set2 = new Set(requested);
36933
+ if (set2.has("tasks:write")) set2.add("tasks:read");
36934
+ if (set2.has("docs:write")) set2.add("docs:read");
36935
+ if (!set2.has("tasks:write") && !set2.has("docs:write")) set2.delete("organize");
36936
+ return SCOPES.filter((s) => set2.has(s));
36937
+ }
36938
+ __name(consistentScopes, "consistentScopes");
36939
+ var toTokenDTO = /* @__PURE__ */ __name((t, workspaceName) => ({
36940
+ id: t.id,
36941
+ name: t.name,
36942
+ workspaceId: t.workspaceId,
36943
+ workspaceName,
36944
+ prefix: t.prefix,
36945
+ scopes: t.scopes.filter((s) => SCOPES.includes(s)),
36946
+ createdAt: t.createdAt.toISOString(),
36947
+ lastUsedAt: t.lastUsedAt?.toISOString() ?? null,
36948
+ expiresAt: t.expiresAt?.toISOString() ?? null,
36949
+ revokedAt: t.revokedAt?.toISOString() ?? null,
36950
+ oauth: t.oauthClientId ? { clientId: t.oauthClientId, redirectUri: t.oauthRedirectUri ?? "" } : null
36951
+ }), "toTokenDTO");
36952
+ var TokenService = class {
36953
+ constructor(deps, access) {
36954
+ this.deps = deps;
36955
+ this.access = access;
36956
+ }
36957
+ deps;
36958
+ access;
36959
+ static {
36960
+ __name(this, "TokenService");
36961
+ }
36962
+ lastTouched = /* @__PURE__ */ new Map();
36963
+ async list(actor) {
36964
+ this.access.requireUser(actor);
36965
+ const rows = await this.deps.db.select({ token: apiTokens, workspaceName: workspaces.name }).from(apiTokens).innerJoin(workspaces, eq(workspaces.id, apiTokens.workspaceId)).where(eq(apiTokens.userId, actor.userId)).orderBy(desc(apiTokens.createdAt));
36966
+ return rows.map((r) => toTokenDTO(r.token, r.workspaceName));
36967
+ }
36968
+ async create(actor, input2) {
36969
+ this.access.requireUser(actor);
36970
+ const data = parse3(tokenCreateInput, input2);
36971
+ await this.access.workspace(actor, data.workspaceId);
36972
+ const token = `${TOKEN_PREFIX}${randomToken(32)}`;
36973
+ const scopes = consistentScopes(data.scopes);
36974
+ const [row] = await this.deps.db.insert(apiTokens).values({
36975
+ userId: actor.userId,
36976
+ workspaceId: data.workspaceId,
36977
+ name: data.name,
36978
+ tokenHash: sha2562(token),
36979
+ prefix: token.slice(0, 12),
36980
+ scopes,
36981
+ expiresAt: data.expiresInDays ? new Date(Date.now() + data.expiresInDays * 864e5) : null
36982
+ }).returning();
36983
+ const [w] = await this.deps.db.select({ name: workspaces.name }).from(workspaces).where(eq(workspaces.id, data.workspaceId));
36984
+ return { ...toTokenDTO(row, w.name), token };
36985
+ }
36986
+ /**
36987
+ * Lets a token or an OAuth connection delete and move things, or stops it. Tokens made before
36988
+ * this permission existed don't have it until their owner turns it on.
36989
+ */
36990
+ async update(actor, tokenId, input2) {
36991
+ this.access.requireUser(actor);
36992
+ const { organize } = parse3(tokenUpdateInput, input2);
36993
+ const [current] = await this.deps.db.select({ token: apiTokens, workspaceName: workspaces.name }).from(apiTokens).innerJoin(workspaces, eq(workspaces.id, apiTokens.workspaceId)).where(and(eq(apiTokens.id, tokenId), eq(apiTokens.userId, actor.userId), isNull(apiTokens.revokedAt)));
36994
+ if (!current) throw notFound("Token");
36995
+ const known = current.token.scopes.filter((s) => SCOPES.includes(s));
36996
+ if (organize && !known.includes("tasks:write") && !known.includes("docs:write")) throw badRequest("Only a token that can make changes can also delete and move");
36997
+ const scopes = consistentScopes(organize ? [...known, "organize"] : known.filter((s) => s !== "organize"));
36998
+ const [row] = await this.deps.db.update(apiTokens).set({ scopes }).where(eq(apiTokens.id, tokenId)).returning();
36999
+ return toTokenDTO(row, current.workspaceName);
37000
+ }
37001
+ async revoke(actor, tokenId) {
37002
+ this.access.requireUser(actor);
37003
+ const [row] = await this.deps.db.update(apiTokens).set({ revokedAt: /* @__PURE__ */ new Date() }).where(and(eq(apiTokens.id, tokenId), eq(apiTokens.userId, actor.userId), isNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
37004
+ if (!row) throw notFound("Token");
37005
+ }
37006
+ /** Resolves a bearer token into an agent actor, or null if invalid, expired, revoked or orphaned. */
37007
+ async authenticate(token) {
37008
+ if (!token.startsWith(TOKEN_PREFIX) || token.length > 100) return null;
37009
+ const now = /* @__PURE__ */ new Date();
37010
+ const [row] = await this.deps.db.select({ token: apiTokens }).from(apiTokens).innerJoin(
37011
+ workspaceMembers,
37012
+ and(eq(workspaceMembers.workspaceId, apiTokens.workspaceId), eq(workspaceMembers.userId, apiTokens.userId))
37013
+ ).where(
37014
+ and(
37015
+ eq(apiTokens.tokenHash, sha2562(token)),
37016
+ isNull(apiTokens.revokedAt),
37017
+ or(isNull(apiTokens.expiresAt), gt(apiTokens.expiresAt, now))
37018
+ )
37019
+ ).limit(1);
37020
+ return row ? this.actorFor(row.token, now) : null;
37021
+ }
37022
+ /** The agent acting with a valid token (or OAuth grant); records when it was last used. */
37023
+ async actorFor(t, now) {
37024
+ const last = this.lastTouched.get(t.id) ?? 0;
37025
+ if (now.getTime() - last > 6e4) {
37026
+ this.lastTouched.set(t.id, now.getTime());
37027
+ await this.deps.db.update(apiTokens).set({ lastUsedAt: now }).where(eq(apiTokens.id, t.id));
37028
+ }
37029
+ return {
37030
+ kind: "agent",
37031
+ userId: t.userId,
37032
+ tokenId: t.id,
37033
+ name: t.name,
37034
+ workspaceId: t.workspaceId,
37035
+ scopes: new Set(t.scopes.filter((s) => SCOPES.includes(s)))
37036
+ };
37037
+ }
37038
+ };
37039
+
36750
37040
  // src/services/oauth.ts
36751
37041
  var ACCESS_PREFIX = "orqat_";
36752
37042
  var REFRESH_PREFIX = "orqrt_";
@@ -36838,13 +37128,7 @@ function hostOf(uri) {
36838
37128
  }
36839
37129
  }
36840
37130
  __name(hostOf, "hostOf");
36841
- function withReads(scopes) {
36842
- const set2 = new Set([...scopes].filter((s) => SCOPES.includes(s)));
36843
- if (set2.has("tasks:write")) set2.add("tasks:read");
36844
- if (set2.has("docs:write")) set2.add("docs:read");
36845
- return SCOPES.filter((s) => set2.has(s));
36846
- }
36847
- __name(withReads, "withReads");
37131
+ var withReads = /* @__PURE__ */ __name((scopes) => consistentScopes([...scopes].filter((s) => SCOPES.includes(s))), "withReads");
36848
37132
  function withParams(uri, values) {
36849
37133
  const url2 = new URL(uri);
36850
37134
  for (const [key, value] of Object.entries(values)) if (value !== void 0) url2.searchParams.set(key, value);
@@ -37396,15 +37680,20 @@ function rethrowLength(error62) {
37396
37680
  throw error62;
37397
37681
  }
37398
37682
  __name(rethrowLength, "rethrowLength");
37683
+ var ownerOf = /* @__PURE__ */ __name((row) => row.pageId ? { entityType: "page", entityId: row.pageId } : { entityType: "card", entityId: row.cardId }, "ownerOf");
37399
37684
  var AttachmentService = class {
37400
- constructor(deps, access, activity2) {
37685
+ constructor(deps, access, activity2, trash2, history2) {
37401
37686
  this.deps = deps;
37402
37687
  this.access = access;
37403
37688
  this.activity = activity2;
37689
+ this.trash = trash2;
37690
+ this.history = history2;
37404
37691
  }
37405
37692
  deps;
37406
37693
  access;
37407
37694
  activity;
37695
+ trash;
37696
+ history;
37408
37697
  static {
37409
37698
  __name(this, "AttachmentService");
37410
37699
  }
@@ -37437,7 +37726,7 @@ var AttachmentService = class {
37437
37726
  this.closed = false;
37438
37727
  }
37439
37728
  async store(actor, target, file2) {
37440
- this.access.requireUser(actor);
37729
+ this.access.requireScope(actor, target.pageId ? "docs:write" : "tasks:write");
37441
37730
  if (/^multipart\/form-data/i.test(file2.type)) {
37442
37731
  throw new AppError(415, "raw_upload_required", "Send the file itself as the request body, with its name in the X-File-Name header");
37443
37732
  }
@@ -37468,48 +37757,98 @@ var AttachmentService = class {
37468
37757
  const { head, stream } = await peek(file2.body.pipeThrough(exactLength(file2.size)), 12).catch(rethrowLength);
37469
37758
  const mimeType = sniff(head, file2.type.split(";")[0].trim().toLowerCase());
37470
37759
  await this.deps.storage.put(storageKey, stream, file2.size, mimeType).catch(rethrowLength);
37471
- const [row] = await this.deps.db.insert(attachments).values({
37472
- id: id3,
37473
- workspaceId,
37474
- pageId: target.pageId ?? null,
37475
- cardId: target.pageId ? null : target.cardId ?? null,
37476
- filename: safeFilename(file2.name),
37477
- mimeType,
37478
- size: file2.size,
37479
- storageKey,
37480
- createdByUserId: actor.userId
37481
- }).returning();
37482
- await this.activity.emit(workspaceId, { action: "attachment.created", actor: { kind: "user", id: actor.userId, name: actor.name }, ...event });
37760
+ const row = this.deps.db.transaction((tx) => {
37761
+ const row2 = tx.insert(attachments).values({
37762
+ id: id3,
37763
+ workspaceId,
37764
+ pageId: target.pageId ?? null,
37765
+ cardId: target.pageId ? null : target.cardId ?? null,
37766
+ filename: safeFilename(file2.name),
37767
+ mimeType,
37768
+ size: file2.size,
37769
+ storageKey,
37770
+ createdByUserId: actor.userId
37771
+ }).returning().get();
37772
+ this.history.record(tx, actor, workspaceId, { ...ownerOf(row2), kind: "attachment.created", subjectId: row2.id, meta: { name: row2.filename } });
37773
+ return row2;
37774
+ });
37775
+ await this.activity.emit(workspaceId, { action: "attachment.created", actor: actorRef(actor), ...event });
37483
37776
  return toAttachmentDTO(row);
37484
37777
  }
37485
37778
  async open(actor, attachmentId) {
37486
- this.access.requireUser(actor);
37487
37779
  const [row] = await this.deps.db.select().from(attachments).where(eq(attachments.id, attachmentId));
37488
37780
  if (!row) throw notFound("Attachment");
37781
+ this.access.requireScope(actor, row.pageId ? "docs:read" : "tasks:read");
37489
37782
  await this.access.workspace(actor, row.workspaceId);
37490
37783
  const body = await this.deps.storage.stream(row.storageKey);
37491
37784
  if (!body) throw notFound("Attachment");
37492
37785
  return { meta: row, inline: INLINE_IMAGES.has(row.mimeType), body };
37493
37786
  }
37787
+ /** To the trash. Agents need write access to where it is, and to be allowed to delete and move. */
37494
37788
  async remove(actor, attachmentId) {
37495
- this.access.requireUser(actor);
37789
+ this.access.requireScope(actor, "organize");
37496
37790
  const [row] = await this.deps.db.select().from(attachments).where(eq(attachments.id, attachmentId));
37497
37791
  if (!row) throw notFound("Attachment");
37792
+ this.access.requireScope(actor, row.pageId ? "docs:write" : "tasks:write");
37498
37793
  await this.access.workspace(actor, row.workspaceId);
37499
- await this.deps.db.delete(attachments).where(eq(attachments.id, attachmentId));
37500
- await this.deps.storage.delete(row.storageKey);
37794
+ const trashId = this.deps.db.transaction((tx) => {
37795
+ const trashId2 = this.trash.move(tx, actor, row.workspaceId, { kind: "attachment", id: attachmentId });
37796
+ this.history.record(tx, actor, row.workspaceId, { ...ownerOf(row), kind: "attachment.deleted", subjectId: attachmentId, meta: { name: row.filename, trashId: trashId2 } });
37797
+ return trashId2;
37798
+ });
37501
37799
  await this.activity.emit(row.workspaceId, {
37502
37800
  action: "attachment.deleted",
37503
- actor: { kind: "user", id: actor.userId, name: actor.name },
37801
+ actor: actorRef(actor),
37504
37802
  ...row.pageId ? { pageId: row.pageId } : {},
37505
37803
  ...row.cardId ? { cardId: row.cardId } : {}
37506
37804
  });
37805
+ return trashId;
37507
37806
  }
37508
- async sweepOrphans() {
37509
- return this.deps.storage.sweep(async (key) => {
37510
- const [row] = await this.deps.db.select({ id: attachments.id }).from(attachments).where(eq(attachments.storageKey, key)).limit(1);
37511
- return Boolean(row);
37807
+ /**
37808
+ * Moves an attachment to another card or page of the same workspace. Agents need write access
37809
+ * to both places, and to be allowed to delete and move.
37810
+ */
37811
+ async move(actor, attachmentId, input2) {
37812
+ this.access.requireScope(actor, "organize");
37813
+ const target = parse3(attachmentMoveInput, input2);
37814
+ const [row] = await this.deps.db.select().from(attachments).where(eq(attachments.id, attachmentId));
37815
+ if (!row) throw notFound("Attachment");
37816
+ this.access.requireScope(actor, row.pageId ? "docs:write" : "tasks:write");
37817
+ this.access.requireScope(actor, target.pageId ? "docs:write" : "tasks:write");
37818
+ await this.access.workspace(actor, row.workspaceId);
37819
+ const to = target.pageId ? this.deps.db.select({ id: pages.id, title: pages.title, workspaceId: pages.workspaceId, projectId: pages.projectId }).from(pages).where(eq(pages.id, target.pageId)).get() : this.deps.db.select({ id: cards.id, title: cards.title, workspaceId: cards.workspaceId, boardId: cards.boardId }).from(cards).where(eq(cards.id, target.cardId)).get();
37820
+ if (!to || to.workspaceId !== row.workspaceId) throw notFound(target.pageId ? "Page" : "Card");
37821
+ const before = { cardId: row.cardId, pageId: row.pageId };
37822
+ const after = { cardId: target.cardId ?? null, pageId: target.pageId ?? null };
37823
+ if (before.cardId === after.cardId && before.pageId === after.pageId) return toAttachmentDTO(row);
37824
+ const title = /* @__PURE__ */ __name((place) => place.pageId ? this.deps.db.select({ title: pages.title }).from(pages).where(eq(pages.id, place.pageId)).get()?.title ?? "" : this.deps.db.select({ title: cards.title }).from(cards).where(eq(cards.id, place.cardId ?? "")).get()?.title ?? "", "title");
37825
+ const moved = this.deps.db.transaction((tx) => {
37826
+ const moved2 = tx.update(attachments).set(after).where(eq(attachments.id, attachmentId)).returning().get();
37827
+ const change = { kind: "attachment.moved", subjectId: attachmentId, before, after, meta: { name: row.filename, from: title(before), to: title(after) } };
37828
+ this.history.record(tx, actor, row.workspaceId, { ...ownerOf(row), ...change });
37829
+ this.history.record(tx, actor, row.workspaceId, { ...ownerOf(after), ...change });
37830
+ return moved2;
37512
37831
  });
37832
+ for (const place of [row, after]) {
37833
+ const event = place.pageId ? { pageId: place.pageId } : { cardId: place.cardId };
37834
+ await this.activity.emit(row.workspaceId, { action: "attachment.moved", actor: actorRef(actor), ...event });
37835
+ }
37836
+ return toAttachmentDTO(moved);
37837
+ }
37838
+ /**
37839
+ * Whether an attachment or one in the trash uses a stored file. Both are checked in one
37840
+ * statement: a restore moves the file's reference from the trash back to the attachments, and
37841
+ * a check in two steps could miss it in both.
37842
+ */
37843
+ usesFile(storageKey) {
37844
+ return Boolean(
37845
+ this.deps.db.get(sql`SELECT 1 AS used WHERE EXISTS (SELECT 1 FROM attachments WHERE storage_key = ${storageKey})
37846
+ OR EXISTS (SELECT 1 FROM trash_rows WHERE storage_key = ${storageKey})`)
37847
+ );
37848
+ }
37849
+ /** Removes stored files that neither an attachment nor one in the trash still uses. */
37850
+ async sweepOrphans() {
37851
+ return this.deps.storage.sweep(async (key) => this.usesFile(key));
37513
37852
  }
37514
37853
  };
37515
37854
 
@@ -37869,11 +38208,12 @@ __name(positionAt, "positionAt");
37869
38208
 
37870
38209
  // src/services/pages.ts
37871
38210
  var MAX_TREE_DEPTH = 1e5;
38211
+ var pageTree = /* @__PURE__ */ __name((roots) => sql`WITH RECURSIVE tree(id, depth) AS (
38212
+ SELECT id, 0 FROM pages WHERE ${roots}
38213
+ UNION ALL SELECT p.id, t.depth + 1 FROM pages p JOIN tree t ON p.parent_id = t.id WHERE t.depth < ${MAX_TREE_DEPTH}
38214
+ )`, "pageTree");
37872
38215
  function deletePageTrees(db, roots) {
37873
- const tree = sql`WITH RECURSIVE tree(id, depth) AS (
37874
- SELECT id, 0 FROM pages WHERE ${roots}
37875
- UNION ALL SELECT p.id, t.depth + 1 FROM pages p JOIN tree t ON p.parent_id = t.id WHERE t.depth < ${MAX_TREE_DEPTH}
37876
- )`;
38216
+ const tree = pageTree(roots);
37877
38217
  const deepest = db.get(sql`${tree} SELECT max(depth) AS depth FROM tree`)?.depth ?? null;
37878
38218
  if (deepest === null) return;
37879
38219
  for (let depth = deepest; depth >= 0; depth--) {
@@ -37892,14 +38232,18 @@ var toNode = /* @__PURE__ */ __name((p) => ({
37892
38232
  }), "toNode");
37893
38233
  var siblingsOf = /* @__PURE__ */ __name((projectId, parentId) => and(eq(pages.projectId, projectId), parentId ? eq(pages.parentId, parentId) : isNull(pages.parentId)), "siblingsOf");
37894
38234
  var PageService = class {
37895
- constructor(deps, access, activity2) {
38235
+ constructor(deps, access, activity2, trash2, history2) {
37896
38236
  this.deps = deps;
37897
38237
  this.access = access;
37898
38238
  this.activity = activity2;
38239
+ this.trash = trash2;
38240
+ this.history = history2;
37899
38241
  }
37900
38242
  deps;
37901
38243
  access;
37902
38244
  activity;
38245
+ trash;
38246
+ history;
37903
38247
  static {
37904
38248
  __name(this, "PageService");
37905
38249
  }
@@ -37946,6 +38290,8 @@ var PageService = class {
37946
38290
  updatedByTokenId: actor.kind === "agent" ? actor.tokenId : null
37947
38291
  }).returning().get();
37948
38292
  if (data.content) this.syncMentions(tx, row);
38293
+ this.history.record(tx, actor, row.workspaceId, { entityType: "page", entityId: row.id, kind: "page.created", meta: { title: row.title } });
38294
+ if (data.content) this.history.record(tx, actor, row.workspaceId, { entityType: "page", entityId: row.id, kind: "page.content", before: "", after: row.content });
37949
38295
  return row;
37950
38296
  });
37951
38297
  await this.activity.record(
@@ -38044,6 +38390,8 @@ var PageService = class {
38044
38390
  throw badRequest("baseVersion is required when updating content");
38045
38391
  }
38046
38392
  const page = this.deps.db.transaction((tx) => {
38393
+ const prev = tx.select({ title: pages.title, icon: pages.icon, content: pages.content }).from(pages).where(eq(pages.id, pageId)).get();
38394
+ if (!prev) throw notFound("Page");
38047
38395
  const patch = {
38048
38396
  updatedAt: /* @__PURE__ */ new Date(),
38049
38397
  updatedByUserId: actor.userId,
@@ -38062,6 +38410,10 @@ var PageService = class {
38062
38410
  throw conflict("This page was modified since you loaded it", { currentVersion: latest?.version ?? null });
38063
38411
  }
38064
38412
  if (data.content !== void 0) this.syncMentions(tx, row);
38413
+ const change = /* @__PURE__ */ __name((kind, before, after) => this.history.record(tx, actor, row.workspaceId, { entityType: "page", entityId: pageId, kind, before, after }), "change");
38414
+ if (data.title !== void 0) change("page.title", prev.title, row.title);
38415
+ if (data.icon !== void 0) change("page.icon", prev.icon, row.icon);
38416
+ if (data.content !== void 0) change("page.content", prev.content, row.content);
38065
38417
  return row;
38066
38418
  });
38067
38419
  const structural = data.title !== void 0 && data.title !== current.title || data.icon !== void 0 && data.icon !== current.icon;
@@ -38086,8 +38438,21 @@ var PageService = class {
38086
38438
  ) SELECT id FROM sub`);
38087
38439
  if (descendants.some((r) => r.id === parentId)) throw badRequest("A page cannot be moved inside itself");
38088
38440
  }
38089
- const position2 = positionAt(this.deps.db, pages, siblingsOf(page.projectId, parentId), index3, pageId);
38090
- await this.deps.db.update(pages).set({ parentId, position: position2 }).where(eq(pages.id, pageId));
38441
+ this.deps.db.transaction((tx) => {
38442
+ const prev = tx.select({ parentId: pages.parentId }).from(pages).where(eq(pages.id, pageId)).get();
38443
+ const position2 = positionAt(tx, pages, siblingsOf(page.projectId, parentId), index3, pageId);
38444
+ tx.update(pages).set({ parentId, position: position2 }).where(eq(pages.id, pageId)).run();
38445
+ if (!prev || prev.parentId === parentId) return;
38446
+ const title = /* @__PURE__ */ __name((id3) => id3 ? tx.select({ title: pages.title }).from(pages).where(eq(pages.id, id3)).get()?.title ?? "" : null, "title");
38447
+ this.history.record(tx, actor, page.workspaceId, {
38448
+ entityType: "page",
38449
+ entityId: pageId,
38450
+ kind: "page.moved",
38451
+ before: { projectId: page.projectId, parentId: prev.parentId },
38452
+ after: { projectId: page.projectId, parentId },
38453
+ meta: { from: title(prev.parentId), to: title(parentId) }
38454
+ });
38455
+ });
38091
38456
  await this.activity.record(
38092
38457
  actor,
38093
38458
  page.workspaceId,
@@ -38096,15 +38461,20 @@ var PageService = class {
38096
38461
  );
38097
38462
  }
38098
38463
  async remove(actor, pageId) {
38099
- this.access.requireUser(actor);
38464
+ this.access.requireScope(actor, "organize");
38100
38465
  const page = await this.load(actor, pageId, "docs:write");
38101
- this.deps.db.transaction((tx) => deletePageTrees(tx, sql`${pages.id} = ${pageId}`));
38466
+ const trashId = this.deps.db.transaction((tx) => {
38467
+ const trashId2 = this.trash.move(tx, actor, page.workspaceId, { kind: "page", id: pageId });
38468
+ this.history.record(tx, actor, page.workspaceId, { entityType: "page", entityId: pageId, kind: "page.deleted", meta: { trashId: trashId2 } });
38469
+ return trashId2;
38470
+ });
38102
38471
  await this.activity.record(
38103
38472
  actor,
38104
38473
  page.workspaceId,
38105
38474
  { action: "page.deleted", entityType: "page", entityId: pageId, summary: page.title },
38106
38475
  { pageId, projectId: page.projectId, structure: true }
38107
38476
  );
38477
+ return trashId;
38108
38478
  }
38109
38479
  /** Keeps `mention` links in sync with the card references found in the page body. Runs inside the save transaction. */
38110
38480
  syncMentions(db, page) {
@@ -38129,6 +38499,9 @@ var toUserDTO = /* @__PURE__ */ __name((u) => ({
38129
38499
  }), "toUserDTO");
38130
38500
  var UNINSTALLED_KEY = "uninstalled";
38131
38501
  var UNINSTALL_ORDER = [
38502
+ history,
38503
+ trashRows,
38504
+ trash,
38132
38505
  cardLabels,
38133
38506
  checklistItems,
38134
38507
  checklists,
@@ -38652,6 +39025,16 @@ async function json2(c) {
38652
39025
  }
38653
39026
  }
38654
39027
  __name(json2, "json");
39028
+ function historyPage(c) {
39029
+ const before = new Date(c.req.query("before") ?? "");
39030
+ const limit2 = Number(c.req.query("limit"));
39031
+ return {
39032
+ before: Number.isNaN(before.getTime()) ? void 0 : before,
39033
+ beforeId: c.req.query("beforeId") || void 0,
39034
+ limit: Number.isFinite(limit2) && limit2 > 0 ? limit2 : void 0
39035
+ };
39036
+ }
39037
+ __name(historyPage, "historyPage");
38655
39038
  function createApi(env) {
38656
39039
  const api = new Hono3();
38657
39040
  const loginLimiter = new RateLimiter(10, 15 * 60 * 1e3);
@@ -38731,6 +39114,12 @@ function createApi(env) {
38731
39114
  await c.get("services").workspaces.remove(requireActor(c), c.req.param("id"));
38732
39115
  return c.body(null, 204);
38733
39116
  });
39117
+ api.get("/workspaces/:id/trash", async (c) => c.json(await c.get("services").trash.list(requireActor(c), c.req.param("id"))));
39118
+ api.post("/trash/:id/restore", async (c) => c.json(await c.get("services").trash.restore(requireActor(c), c.req.param("id"))));
39119
+ api.delete("/trash/:id", async (c) => {
39120
+ await c.get("services").trash.purge(requireActor(c), c.req.param("id"));
39121
+ return c.body(null, 204);
39122
+ });
38734
39123
  api.get("/workspaces/:id/overview", async (c) => c.json(await c.get("services").workspaces.overview(requireActor(c), c.req.param("id"))));
38735
39124
  api.get("/workspaces/:id/home", async (c) => c.json(await c.get("services").workspaces.home(requireActor(c), c.req.param("id"))));
38736
39125
  api.get("/workspaces/:id/search", async (c) => {
@@ -38762,10 +39151,7 @@ function createApi(env) {
38762
39151
  "/projects/:id",
38763
39152
  async (c) => c.json(await c.get("services").workspaces.updateProject(requireActor(c), c.req.param("id"), await json2(c)))
38764
39153
  );
38765
- api.delete("/projects/:id", async (c) => {
38766
- await c.get("services").workspaces.removeProject(requireActor(c), c.req.param("id"));
38767
- return c.body(null, 204);
38768
- });
39154
+ api.delete("/projects/:id", async (c) => c.json({ trashId: await c.get("services").workspaces.removeProject(requireActor(c), c.req.param("id")) }));
38769
39155
  api.post(
38770
39156
  "/projects/:id/boards",
38771
39157
  async (c) => c.json(await c.get("services").boards.create(requireActor(c), c.req.param("id"), await json2(c)), 201)
@@ -38780,10 +39166,7 @@ function createApi(env) {
38780
39166
  await c.get("services").boards.update(requireActor(c), c.req.param("id"), await json2(c));
38781
39167
  return c.body(null, 204);
38782
39168
  });
38783
- api.delete("/boards/:id", async (c) => {
38784
- await c.get("services").boards.remove(requireActor(c), c.req.param("id"));
38785
- return c.body(null, 204);
38786
- });
39169
+ api.delete("/boards/:id", async (c) => c.json({ trashId: await c.get("services").boards.remove(requireActor(c), c.req.param("id")) }));
38787
39170
  api.get("/boards/:id/archived", async (c) => c.json(await c.get("services").boards.archived(requireActor(c), c.req.param("id"))));
38788
39171
  api.post(
38789
39172
  "/boards/:id/columns",
@@ -38797,10 +39180,7 @@ function createApi(env) {
38797
39180
  "/columns/:id",
38798
39181
  async (c) => c.json(await c.get("services").boards.updateColumn(requireActor(c), c.req.param("id"), await json2(c)))
38799
39182
  );
38800
- api.delete("/columns/:id", async (c) => {
38801
- await c.get("services").boards.removeColumn(requireActor(c), c.req.param("id"));
38802
- return c.body(null, 204);
38803
- });
39183
+ api.delete("/columns/:id", async (c) => c.json({ trashId: await c.get("services").boards.removeColumn(requireActor(c), c.req.param("id")) }));
38804
39184
  api.post(
38805
39185
  "/columns/:id/cards",
38806
39186
  async (c) => c.json(await c.get("services").cards.create(requireActor(c), c.req.param("id"), await json2(c)), 201)
@@ -38809,11 +39189,15 @@ function createApi(env) {
38809
39189
  "/labels/:id",
38810
39190
  async (c) => c.json(await c.get("services").boards.updateLabel(requireActor(c), c.req.param("id"), await json2(c)))
38811
39191
  );
38812
- api.delete("/labels/:id", async (c) => {
38813
- await c.get("services").boards.removeLabel(requireActor(c), c.req.param("id"));
39192
+ api.delete("/labels/:id", async (c) => c.json({ trashId: await c.get("services").boards.removeLabel(requireActor(c), c.req.param("id")) }));
39193
+ api.get("/cards/:id", async (c) => c.json(await c.get("services").cards.detail(requireActor(c), c.req.param("id"))));
39194
+ api.get("/cards/:id/history", async (c) => c.json(await c.get("services").history.list(requireActor(c), "card", c.req.param("id"), historyPage(c))));
39195
+ api.get("/history/:id", async (c) => c.json(await c.get("services").history.get(requireActor(c), c.req.param("id"))));
39196
+ api.post("/history/undo", async (c) => c.json(await c.get("services").undo.undo(requireActor(c), await json2(c))));
39197
+ api.post("/history/:id/restore", async (c) => {
39198
+ await c.get("services").undo.restoreVersion(requireActor(c), c.req.param("id"));
38814
39199
  return c.body(null, 204);
38815
39200
  });
38816
- api.get("/cards/:id", async (c) => c.json(await c.get("services").cards.detail(requireActor(c), c.req.param("id"))));
38817
39201
  api.patch("/cards/:id", async (c) => c.json(await c.get("services").cards.update(requireActor(c), c.req.param("id"), await json2(c))));
38818
39202
  api.post("/cards/:id/move", async (c) => c.json(await c.get("services").cards.move(requireActor(c), c.req.param("id"), await json2(c))));
38819
39203
  api.post("/cards/:id/archive", async (c) => {
@@ -38824,10 +39208,7 @@ function createApi(env) {
38824
39208
  await c.get("services").cards.setArchived(requireActor(c), c.req.param("id"), false);
38825
39209
  return c.body(null, 204);
38826
39210
  });
38827
- api.delete("/cards/:id", async (c) => {
38828
- await c.get("services").cards.remove(requireActor(c), c.req.param("id"));
38829
- return c.body(null, 204);
38830
- });
39211
+ api.delete("/cards/:id", async (c) => c.json({ trashId: await c.get("services").cards.remove(requireActor(c), c.req.param("id")) }));
38831
39212
  api.post(
38832
39213
  "/cards/:id/checklists",
38833
39214
  async (c) => c.json(await c.get("services").cards.createChecklist(requireActor(c), c.req.param("id"), await json2(c)), 201)
@@ -38836,10 +39217,7 @@ function createApi(env) {
38836
39217
  await c.get("services").cards.updateChecklist(requireActor(c), c.req.param("id"), await json2(c));
38837
39218
  return c.body(null, 204);
38838
39219
  });
38839
- api.delete("/checklists/:id", async (c) => {
38840
- await c.get("services").cards.removeChecklist(requireActor(c), c.req.param("id"));
38841
- return c.body(null, 204);
38842
- });
39220
+ api.delete("/checklists/:id", async (c) => c.json({ trashId: await c.get("services").cards.removeChecklist(requireActor(c), c.req.param("id")) }));
38843
39221
  api.post(
38844
39222
  "/checklists/:id/items",
38845
39223
  async (c) => c.json(await c.get("services").cards.addItem(requireActor(c), c.req.param("id"), await json2(c)), 201)
@@ -38848,28 +39226,20 @@ function createApi(env) {
38848
39226
  "/checklist-items/:id",
38849
39227
  async (c) => c.json(await c.get("services").cards.updateItem(requireActor(c), c.req.param("id"), await json2(c)))
38850
39228
  );
38851
- api.delete("/checklist-items/:id", async (c) => {
38852
- await c.get("services").cards.removeItem(requireActor(c), c.req.param("id"));
38853
- return c.body(null, 204);
38854
- });
39229
+ api.delete("/checklist-items/:id", async (c) => c.json({ trashId: await c.get("services").cards.removeItem(requireActor(c), c.req.param("id")) }));
38855
39230
  api.post("/cards/:id/pages", async (c) => {
38856
39231
  await c.get("services").cards.linkPage(requireActor(c), c.req.param("id"), await json2(c));
38857
39232
  return c.body(null, 204);
38858
39233
  });
38859
- api.delete("/cards/:id/pages/:pageId", async (c) => {
38860
- await c.get("services").cards.unlinkPage(requireActor(c), c.req.param("id"), c.req.param("pageId"));
38861
- return c.body(null, 204);
38862
- });
39234
+ api.delete("/cards/:id/pages/:pageId", async (c) => c.json({ trashId: await c.get("services").cards.unlinkPage(requireActor(c), c.req.param("id"), c.req.param("pageId")) }));
38863
39235
  api.get("/pages/:id", async (c) => c.json(await c.get("services").pages.get(requireActor(c), c.req.param("id"))));
39236
+ api.get("/pages/:id/history", async (c) => c.json(await c.get("services").history.list(requireActor(c), "page", c.req.param("id"), historyPage(c))));
38864
39237
  api.patch("/pages/:id", async (c) => c.json(await c.get("services").pages.update(requireActor(c), c.req.param("id"), await json2(c))));
38865
39238
  api.post("/pages/:id/move", async (c) => {
38866
39239
  await c.get("services").pages.move(requireActor(c), c.req.param("id"), await json2(c));
38867
39240
  return c.body(null, 204);
38868
39241
  });
38869
- api.delete("/pages/:id", async (c) => {
38870
- await c.get("services").pages.remove(requireActor(c), c.req.param("id"));
38871
- return c.body(null, 204);
38872
- });
39242
+ api.delete("/pages/:id", async (c) => c.json({ trashId: await c.get("services").pages.remove(requireActor(c), c.req.param("id")) }));
38873
39243
  for (const [path, target] of [
38874
39244
  ["/pages/:id/attachments", "pageId"],
38875
39245
  ["/cards/:id/attachments", "cardId"]
@@ -38899,14 +39269,13 @@ function createApi(env) {
38899
39269
  }
38900
39270
  });
38901
39271
  });
38902
- api.delete("/attachments/:id", async (c) => {
38903
- await c.get("services").attachments.remove(requireActor(c), c.req.param("id"));
38904
- return c.body(null, 204);
38905
- });
39272
+ api.delete("/attachments/:id", async (c) => c.json({ trashId: await c.get("services").attachments.remove(requireActor(c), c.req.param("id")) }));
39273
+ api.post("/attachments/:id/move", async (c) => c.json(await c.get("services").attachments.move(requireActor(c), c.req.param("id"), await json2(c))));
38906
39274
  api.post("/oauth/request", async (c) => c.json(await c.get("services").oauth.request(requireActor(c), await json2(c), endpointFor(c.get("config"), c.req.url))));
38907
39275
  api.post("/oauth/decision", async (c) => c.json(await c.get("services").oauth.decide(requireActor(c), await json2(c), endpointFor(c.get("config"), c.req.url))));
38908
39276
  api.get("/tokens", async (c) => c.json(await c.get("services").tokens.list(requireActor(c))));
38909
39277
  api.post("/tokens", async (c) => c.json(await c.get("services").tokens.create(requireActor(c), await json2(c)), 201));
39278
+ api.patch("/tokens/:id", async (c) => c.json(await c.get("services").tokens.update(requireActor(c), c.req.param("id"), await json2(c))));
38910
39279
  api.delete("/tokens/:id", async (c) => {
38911
39280
  await c.get("services").tokens.revoke(requireActor(c), c.req.param("id"));
38912
39281
  return c.body(null, 204);
@@ -49602,6 +49971,8 @@ var EMPTY_COMPLETION_RESULT = {
49602
49971
  // src/mcp/server.ts
49603
49972
  var MCP_SERVER_NAME = "orqevio";
49604
49973
  var MCP_SERVER_VERSION = "1.0.0";
49974
+ var MCP_UPLOAD_MB = 5;
49975
+ var MCP_MAX_REQUEST_BYTES = 8 * 1024 * 1024;
49605
49976
  var INSTRUCTIONS = `Orqevio is a workspace that combines Kanban task boards and Markdown documents.
49606
49977
  Structure: workspace \u2192 projects \u2192 boards (columns \u2192 cards) and documents (nested pages).
49607
49978
 
@@ -49613,9 +49984,37 @@ How to work with it:
49613
49984
  - To reference a card inside a document write a Markdown link: [Card title](/card/<card_id>). To reference a page: [Page title](/doc/<page_id>). Card references inside a page automatically link that card to the page.
49614
49985
  - update_page with mode "replace" should include base_version (from read_page) to avoid overwriting someone else's edits. Use mode "append" to add content safely.
49615
49986
  - Likewise, update_card with a description should include base_version (the version from get_card).
49616
- - Agents cannot delete anything. Use archive_card to remove a card from a board (it can be restored by a person).
49987
+ - Every change is recorded in the history of its card or page, and people can undo it from there.
49988
+ - When a card is done or no longer needed, prefer archive_card: it leaves the board but stays findable. Delete what was a mistake or a duplicate.
49989
+ - Tokens allowed to delete and move also have delete_* tools, move_attachment and move_card to another board. Deleting always moves things to the trash, where a person can bring them back for ${TRASH_DAYS} days. Agents can never empty the trash or delete anything for good.
49990
+ - Attachments: get_card and read_page list them. read_attachment returns text files as text and images as images. upload_attachment takes text or base64, up to ${MCP_UPLOAD_MB} MB.
49617
49991
  - The user's password vault is end-to-end encrypted and is never accessible through this server. Do not ask for passwords or secrets.`;
49618
49992
  var uuid3 = external_exports.uuid();
49993
+ var READ_TEXT_BYTES = 1024 * 1024;
49994
+ var TEXT_TYPES = /^(text\/|application\/(json|xml|yaml|x-yaml|csv|javascript|x-ndjson)\b)|\+(json|xml)$/;
49995
+ var IMAGE_TYPES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
49996
+ async function readAll(body, max) {
49997
+ const chunks = [];
49998
+ let size = 0;
49999
+ const reader = body.getReader();
50000
+ for (let next = await reader.read(); !next.done; next = await reader.read()) {
50001
+ size += next.value.byteLength;
50002
+ if (size > max) {
50003
+ await reader.cancel();
50004
+ throw new AppError(413, "file_too_large", "The file is too large to read here; open it in the Orqevio app.");
50005
+ }
50006
+ chunks.push(next.value);
50007
+ }
50008
+ const out = new Uint8Array(size);
50009
+ let at = 0;
50010
+ for (const chunk of chunks) {
50011
+ out.set(chunk, at);
50012
+ at += chunk.byteLength;
50013
+ }
50014
+ return out;
50015
+ }
50016
+ __name(readAll, "readAll");
50017
+ var attachmentSummary = /* @__PURE__ */ __name((a) => ({ id: a.id, name: a.filename, type: a.mimeType, size: a.size }), "attachmentSummary");
49619
50018
  var dueDate = external_exports.string().describe("Due date as YYYY-MM-DD or a full ISO 8601 date-time. Use null to clear it.");
49620
50019
  function normaliseDue(value) {
49621
50020
  if (value === void 0 || value === null) return value;
@@ -49645,12 +50044,14 @@ async function run(fn) {
49645
50044
  __name(run, "run");
49646
50045
  var READ = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
49647
50046
  var WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
50047
+ var DELETE = { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false };
49648
50048
  function createMcpServer(services, actor) {
49649
50049
  const server = new McpServer({ name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION }, { instructions: INSTRUCTIONS });
49650
50050
  const canReadTasks = hasScope(actor, "tasks:read");
49651
50051
  const canWriteTasks = hasScope(actor, "tasks:write");
49652
50052
  const canReadDocs = hasScope(actor, "docs:read");
49653
50053
  const canWriteDocs = hasScope(actor, "docs:write");
50054
+ const canOrganize = hasScope(actor, "organize") && (canWriteTasks || canWriteDocs);
49654
50055
  const ws = actor.workspaceId;
49655
50056
  server.registerTool(
49656
50057
  "list_projects",
@@ -49773,6 +50174,7 @@ function createMcpServer(services, actor) {
49773
50174
  items: cl.items.map((i) => ({ id: i.id, text: i.text, done: i.done }))
49774
50175
  })),
49775
50176
  linked_pages: card.pages.map((p) => ({ id: p.id, title: p.title || "Untitled" })),
50177
+ attachments: card.attachmentList.map(attachmentSummary),
49776
50178
  recent_activity: card.activity.slice(0, 10).map((a) => ({ action: a.action, by: a.actor.name, at: a.createdAt }))
49777
50179
  };
49778
50180
  })
@@ -49835,7 +50237,7 @@ function createMcpServer(services, actor) {
49835
50237
  "move_card",
49836
50238
  {
49837
50239
  title: "Move card",
49838
- description: "Moves a card to a column of the same board. index 0 places it at the top; omit index to place it at the bottom.",
50240
+ description: canOrganize ? "Moves a card to a column of its board, or of another board of the workspace (it loses the labels of its old board). index 0 places it at the top; omit index to place it at the bottom." : "Moves a card to a column of the same board. index 0 places it at the top; omit index to place it at the bottom.",
49839
50241
  inputSchema: { card_id: uuid3, column_id: uuid3, index: external_exports.number().int().min(0).optional() },
49840
50242
  annotations: { ...WRITE, idempotentHint: true }
49841
50243
  },
@@ -49994,6 +50396,7 @@ function createMcpServer(services, actor) {
49994
50396
  `updated: ${page.updatedAt}${page.updatedBy ? ` by ${page.updatedBy.name}` : ""}`,
49995
50397
  page.children.length ? `sub_pages: ${page.children.map((c) => `${c.title || "Untitled"} (${c.id})`).join(", ")}` : null,
49996
50398
  page.cards.length ? `linked_cards: ${page.cards.map((c) => `${c.title} (${c.id}, ${c.columnName})`).join(", ")}` : null,
50399
+ page.attachments.length ? `attachments: ${page.attachments.map((a) => `${a.filename} (${a.id}, ${a.mimeType}, ${a.size} bytes)`).join(", ")}` : null,
49997
50400
  "",
49998
50401
  "---",
49999
50402
  ""
@@ -50025,26 +50428,142 @@ function createMcpServer(services, actor) {
50025
50428
  "update_page",
50026
50429
  {
50027
50430
  title: "Update page",
50028
- description: 'Updates a page title and/or Markdown content. mode "replace" overwrites the content (send base_version from read_page to avoid overwriting newer edits); mode "append" adds content at the end.',
50431
+ description: 'Updates a page title, icon and/or Markdown content. mode "replace" overwrites the content (send base_version from read_page to avoid overwriting newer edits); mode "append" adds content at the end.',
50029
50432
  inputSchema: {
50030
50433
  page_id: uuid3,
50031
50434
  title: external_exports.string().max(200).optional(),
50435
+ icon: external_exports.string().max(16).nullable().optional().describe("An emoji for the page, or null to remove it."),
50032
50436
  content: external_exports.string().max(2e5).optional(),
50033
50437
  mode: external_exports.enum(["replace", "append"]).default("replace"),
50034
50438
  base_version: external_exports.number().int().min(1).optional()
50035
50439
  },
50036
50440
  annotations: WRITE
50037
50441
  },
50038
- ({ page_id, title, content, mode, base_version }) => run(async () => {
50442
+ ({ page_id, title, icon, content, mode, base_version }) => run(async () => {
50039
50443
  const result = await services.pages.update(
50040
50444
  actor,
50041
50445
  page_id,
50042
- { title, content, baseVersion: base_version },
50446
+ { title, icon, content, baseVersion: base_version },
50043
50447
  { allowBlindWrite: true, append: mode === "append" && content !== void 0 }
50044
50448
  );
50045
50449
  return { updated: true, page_id: result.id, version: result.version };
50046
50450
  })
50047
50451
  );
50452
+ server.registerTool(
50453
+ "move_page",
50454
+ {
50455
+ title: "Move page",
50456
+ description: "Moves a page, with its sub-pages, under another page of the same project, or to the top level with parent_id null. index 0 makes it the first; omit to place it last.",
50457
+ inputSchema: { page_id: uuid3, parent_id: uuid3.nullable(), index: external_exports.number().int().min(0).optional() },
50458
+ annotations: { ...WRITE, idempotentHint: true }
50459
+ },
50460
+ ({ page_id, parent_id, index: index3 }) => run(async () => {
50461
+ await services.pages.move(actor, page_id, { parentId: parent_id, index: index3 ?? 1e5 });
50462
+ return { moved: true, page_id, parent_id };
50463
+ })
50464
+ );
50465
+ }
50466
+ if (canWriteTasks || canWriteDocs) {
50467
+ server.registerTool(
50468
+ "upload_attachment",
50469
+ {
50470
+ title: "Upload attachment",
50471
+ description: `Attaches a file to a card or a page (send card_id or page_id). content is the file itself: plain text, or base64 with encoding "base64". Up to ${MCP_UPLOAD_MB} MB.`,
50472
+ inputSchema: {
50473
+ card_id: uuid3.optional(),
50474
+ page_id: uuid3.optional(),
50475
+ filename: external_exports.string().min(1).max(180),
50476
+ mime_type: external_exports.string().max(120).optional().describe("For example text/markdown or image/png. Guessed from the content when omitted."),
50477
+ content: external_exports.string().min(1),
50478
+ encoding: external_exports.enum(["text", "base64"]).default("text")
50479
+ },
50480
+ annotations: WRITE
50481
+ },
50482
+ (args) => run(async () => {
50483
+ if (args.card_id === void 0 === (args.page_id === void 0)) throw new AppError(400, "bad_request", "Send either card_id or page_id");
50484
+ const bytes = args.encoding === "base64" ? Uint8Array.from(Buffer.from(args.content, "base64")) : new TextEncoder().encode(args.content);
50485
+ if (bytes.byteLength > MCP_UPLOAD_MB * 1024 * 1024) throw new AppError(413, "file_too_large", `Files uploaded by agents are limited to ${MCP_UPLOAD_MB} MB`);
50486
+ const type = args.mime_type ?? (args.encoding === "text" ? "text/plain; charset=utf-8" : "application/octet-stream");
50487
+ const body = new Blob([bytes]).stream();
50488
+ const target = args.page_id ? { pageId: args.page_id } : { cardId: args.card_id };
50489
+ const file2 = await services.attachments.upload(actor, target, { body, size: bytes.byteLength, name: args.filename, type });
50490
+ return { uploaded: true, attachment: attachmentSummary(file2) };
50491
+ })
50492
+ );
50493
+ }
50494
+ if (canReadTasks || canReadDocs) {
50495
+ server.registerTool(
50496
+ "read_attachment",
50497
+ {
50498
+ title: "Read attachment",
50499
+ description: "Reads an attachment of a card or a page: text files (up to 1 MB) come back as text and images as images; for other files, what they are.",
50500
+ inputSchema: { attachment_id: uuid3 },
50501
+ annotations: READ
50502
+ },
50503
+ async ({ attachment_id }) => {
50504
+ try {
50505
+ const { meta: meta3, body } = await services.attachments.open(actor, attachment_id);
50506
+ const about = attachmentSummary(meta3);
50507
+ const type = meta3.mimeType.split(";")[0].trim().toLowerCase();
50508
+ if (TEXT_TYPES.test(type) && meta3.size <= READ_TEXT_BYTES) {
50509
+ const text2 = new TextDecoder().decode(await readAll(body, READ_TEXT_BYTES));
50510
+ return { content: [{ type: "text", text: JSON.stringify(about) }, { type: "text", text: text2 }] };
50511
+ }
50512
+ if (IMAGE_TYPES.has(type) && meta3.size <= MCP_UPLOAD_MB * 1024 * 1024) {
50513
+ const data = Buffer.from(await readAll(body, MCP_UPLOAD_MB * 1024 * 1024)).toString("base64");
50514
+ return { content: [{ type: "text", text: JSON.stringify(about) }, { type: "image", data, mimeType: type }] };
50515
+ }
50516
+ await body.cancel();
50517
+ return ok({ ...about, note: "This file cannot be read here; a person can open it in the Orqevio app." });
50518
+ } catch (error62) {
50519
+ return fail(error62);
50520
+ }
50521
+ }
50522
+ );
50523
+ }
50524
+ if (canOrganize) {
50525
+ const remove = /* @__PURE__ */ __name((name2, title, description, input2, fn) => server.registerTool(
50526
+ name2,
50527
+ { title, description: `${description} A person can bring it back from the trash for ${TRASH_DAYS} days.`, inputSchema: input2, annotations: DELETE },
50528
+ (args) => run(async () => ({ deleted: true, trash_id: await fn(args) }))
50529
+ ), "remove");
50530
+ if (canWriteTasks) {
50531
+ remove("delete_card", "Delete card", "Moves a card to the trash, with its checklists, links and attachments.", { card_id: uuid3 }, (a) => services.cards.remove(actor, a.card_id));
50532
+ remove("delete_board", "Delete board", "Moves a board to the trash, with its columns and cards.", { board_id: uuid3 }, (a) => services.boards.remove(actor, a.board_id));
50533
+ remove("delete_column", "Delete column", "Moves a column to the trash, with all its cards.", { column_id: uuid3 }, (a) => services.boards.removeColumn(actor, a.column_id));
50534
+ remove("delete_label", "Delete label", "Moves a label of a board to the trash; it comes off every card that had it.", { label_id: uuid3 }, (a) => services.boards.removeLabel(actor, a.label_id));
50535
+ remove("delete_checklist", "Delete checklist", "Moves a checklist of a card to the trash, with its items.", { checklist_id: uuid3 }, (a) => services.cards.removeChecklist(actor, a.checklist_id));
50536
+ remove("delete_checklist_item", "Delete checklist item", "Moves a checklist item to the trash.", { item_id: uuid3 }, (a) => services.cards.removeItem(actor, a.item_id));
50537
+ }
50538
+ if (canWriteDocs) {
50539
+ remove("delete_page", "Delete page", "Moves a page to the trash, with its sub-pages and attachments.", { page_id: uuid3 }, (a) => services.pages.remove(actor, a.page_id));
50540
+ }
50541
+ if (canWriteTasks && canWriteDocs) {
50542
+ remove("delete_project", "Delete project", "Moves a project to the trash, with all its boards and documents.", { project_id: uuid3 }, (a) => services.workspaces.removeProject(actor, a.project_id));
50543
+ }
50544
+ remove("delete_attachment", "Delete attachment", "Moves an attachment of a card or a page to the trash.", { attachment_id: uuid3 }, (a) => services.attachments.remove(actor, a.attachment_id));
50545
+ if (canReadTasks && canReadDocs) {
50546
+ remove(
50547
+ "unlink_card_from_page",
50548
+ "Unlink card from page",
50549
+ "Removes the link between a card and a page that link_card_to_page made (links from card references in the page stay while the reference is there).",
50550
+ { card_id: uuid3, page_id: uuid3 },
50551
+ (a) => services.cards.unlinkPage(actor, a.card_id, a.page_id)
50552
+ );
50553
+ }
50554
+ server.registerTool(
50555
+ "move_attachment",
50556
+ {
50557
+ title: "Move attachment",
50558
+ description: "Moves an attachment to another card or page of the workspace (send card_id or page_id).",
50559
+ inputSchema: { attachment_id: uuid3, card_id: uuid3.optional(), page_id: uuid3.optional() },
50560
+ annotations: { ...WRITE, idempotentHint: true }
50561
+ },
50562
+ ({ attachment_id, card_id, page_id }) => run(async () => {
50563
+ const moved = await services.attachments.move(actor, attachment_id, { cardId: card_id, pageId: page_id });
50564
+ return { moved: true, attachment: attachmentSummary(moved), card_id: card_id ?? null, page_id: page_id ?? null };
50565
+ })
50566
+ );
50048
50567
  }
50049
50568
  if ((canWriteTasks || canWriteDocs) && canReadTasks && canReadDocs) {
50050
50569
  server.registerTool(
@@ -50088,7 +50607,7 @@ async function handleMcp(c) {
50088
50607
  const wait = limiter.hit(actor.tokenId);
50089
50608
  if (wait > 0) return rpcError(429, -32002, `Rate limit exceeded. Retry in ${wait}s.`, { "Retry-After": String(wait) });
50090
50609
  const server = createMcpServer(c.get("services"), actor);
50091
- const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: void 0, enableJsonResponse: true });
50610
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: void 0, enableJsonResponse: true, maxRequestBodySize: MCP_MAX_REQUEST_BYTES });
50092
50611
  await server.connect(transport);
50093
50612
  try {
50094
50613
  return await transport.handleRequest(c.req.raw);
@@ -50177,7 +50696,8 @@ var SCOPE_LABEL = {
50177
50696
  "tasks:read": "read tasks",
50178
50697
  "tasks:write": "modify tasks",
50179
50698
  "docs:read": "read documents",
50180
- "docs:write": "modify documents"
50699
+ "docs:write": "modify documents",
50700
+ organize: "delete things (to the trash, from where a person can bring them back) or move them to another board, card or page"
50181
50701
  };
50182
50702
  var Access = class {
50183
50703
  constructor(deps) {
@@ -50292,17 +50812,31 @@ var toLabelDTO = /* @__PURE__ */ __name((l) => ({
50292
50812
  color: l.color
50293
50813
  }), "toLabelDTO");
50294
50814
  var CardService = class {
50295
- constructor(deps, access, activity2) {
50815
+ constructor(deps, access, activity2, trash2, history2) {
50296
50816
  this.deps = deps;
50297
50817
  this.access = access;
50298
50818
  this.activity = activity2;
50819
+ this.trash = trash2;
50820
+ this.history = history2;
50299
50821
  }
50300
50822
  deps;
50301
50823
  access;
50302
50824
  activity;
50825
+ trash;
50826
+ history;
50303
50827
  static {
50304
50828
  __name(this, "CardService");
50305
50829
  }
50830
+ /** Records a change in the card's history; run it in the transaction that makes the change. */
50831
+ change(db, actor, card, change) {
50832
+ this.history.record(db, actor, card.workspaceId, { entityType: "card", entityId: card.id, ...change });
50833
+ }
50834
+ /** Names of labels, in the order of the ids, for the history to show as they were. */
50835
+ labelNames(db, ids) {
50836
+ if (ids.length === 0) return [];
50837
+ const rows = db.select({ id: labels.id, name: labels.name }).from(labels).where(inArray(labels.id, ids)).all();
50838
+ return ids.map((id3) => rows.find((r) => r.id === id3)?.name ?? "");
50839
+ }
50306
50840
  /** Loads a card, enforcing workspace access and the given scope. */
50307
50841
  async load(actor, cardId, scope = "tasks:read", db = this.deps.db) {
50308
50842
  this.access.requireScope(actor, scope);
@@ -50369,7 +50903,7 @@ var CardService = class {
50369
50903
  async detail(actor, cardId) {
50370
50904
  const card = await this.load(actor, cardId);
50371
50905
  const db = this.deps.db;
50372
- const [[summary], [column], [board], labelRows, checklistData, pageLinks, files, history] = await Promise.all([
50906
+ const [[summary], [column], [board], labelRows, checklistData, pageLinks, files, history2] = await Promise.all([
50373
50907
  this.summarize([card]),
50374
50908
  db.select({ id: columns.id, name: columns.name }).from(columns).where(eq(columns.id, card.columnId)),
50375
50909
  db.select({ id: boards.id, name: boards.name, projectId: boards.projectId }).from(boards).where(eq(boards.id, card.boardId)),
@@ -50396,7 +50930,7 @@ var CardService = class {
50396
50930
  checklists: checklistData,
50397
50931
  pages: [...linked.values()],
50398
50932
  attachmentList: files.map(toAttachmentDTO),
50399
- activity: history
50933
+ activity: history2
50400
50934
  };
50401
50935
  }
50402
50936
  async checklistsFor(cardId) {
@@ -50440,13 +50974,15 @@ var CardService = class {
50440
50974
  }).returning().get();
50441
50975
  const labelIds = this.validLabelIds(tx, column.boardId, data.labelIds ?? []);
50442
50976
  if (labelIds.length) tx.insert(cardLabels).values(labelIds.map((labelId) => ({ cardId: row.id, labelId }))).run();
50977
+ this.change(tx, actor, row, { kind: "card.created", meta: { title: row.title, column: column.name } });
50978
+ if (row.description) this.change(tx, actor, row, { kind: "card.description", before: "", after: row.description });
50443
50979
  return row;
50444
50980
  });
50445
50981
  await this.activity.record(
50446
50982
  actor,
50447
50983
  card.workspaceId,
50448
50984
  { action: "card.created", entityType: "card", entityId: card.id, summary: card.title, meta: { column: column.name } },
50449
- { boardId: card.boardId, cardId: card.id }
50985
+ { boardId: card.boardId, cardId: card.id, structure: true }
50450
50986
  );
50451
50987
  const [summary] = await this.summarize([card]);
50452
50988
  return summary;
@@ -50455,6 +50991,8 @@ var CardService = class {
50455
50991
  const data = parse3(cardUpdateInput, input2);
50456
50992
  const card = await this.load(actor, cardId, "tasks:write");
50457
50993
  const updated = this.deps.db.transaction((tx) => {
50994
+ const prev = tx.select().from(cards).where(eq(cards.id, cardId)).get();
50995
+ if (!prev) throw notFound("Card");
50458
50996
  const patch = { updatedAt: /* @__PURE__ */ new Date() };
50459
50997
  if (data.title !== void 0) patch.title = data.title;
50460
50998
  if (data.description !== void 0) {
@@ -50468,10 +51006,24 @@ var CardService = class {
50468
51006
  const latest = tx.select({ version: cards.version }).from(cards).where(eq(cards.id, cardId)).get();
50469
51007
  throw conflict("This card was modified since you loaded it", { currentVersion: latest?.version ?? null });
50470
51008
  }
51009
+ if (data.title !== void 0) this.change(tx, actor, row, { kind: "card.title", before: prev.title, after: row.title });
51010
+ if (data.description !== void 0) this.change(tx, actor, row, { kind: "card.description", before: prev.description, after: row.description });
51011
+ if (data.dueAt !== void 0) this.change(tx, actor, row, { kind: "card.due", before: prev.dueAt?.toISOString() ?? null, after: row.dueAt?.toISOString() ?? null });
50471
51012
  if (data.labelIds) {
50472
51013
  const labelIds = this.validLabelIds(tx, card.boardId, data.labelIds);
51014
+ const was = tx.select({ id: cardLabels.labelId }).from(cardLabels).where(eq(cardLabels.cardId, cardId)).all().map((l) => l.id);
50473
51015
  tx.delete(cardLabels).where(eq(cardLabels.cardId, cardId)).run();
50474
51016
  if (labelIds.length) tx.insert(cardLabels).values(labelIds.map((labelId) => ({ cardId, labelId }))).run();
51017
+ const added = labelIds.filter((id3) => !was.includes(id3));
51018
+ const removed = was.filter((id3) => !labelIds.includes(id3));
51019
+ if (added.length || removed.length) {
51020
+ this.change(tx, actor, row, {
51021
+ kind: "card.labels",
51022
+ before: [...was].sort(),
51023
+ after: [...labelIds].sort(),
51024
+ meta: { added: this.labelNames(tx, added), removed: this.labelNames(tx, removed) }
51025
+ });
51026
+ }
50475
51027
  }
50476
51028
  return row;
50477
51029
  });
@@ -50497,19 +51049,38 @@ var CardService = class {
50497
51049
  const { columnId, index: index3 } = parse3(cardMoveInput, input2);
50498
51050
  const card = await this.load(actor, cardId, "tasks:write");
50499
51051
  const [target] = await this.deps.db.select().from(columns).where(eq(columns.id, columnId));
50500
- if (!target || target.boardId !== card.boardId) throw badRequest("The column must belong to the same board");
51052
+ if (!target || target.workspaceId !== card.workspaceId) throw badRequest("The column must belong to the same workspace");
51053
+ const otherBoard = target.boardId !== card.boardId;
51054
+ if (otherBoard) this.access.requireScope(actor, "organize");
51055
+ const boardName = /* @__PURE__ */ __name((id3) => otherBoard ? this.deps.db.select({ name: boards.name }).from(boards).where(eq(boards.id, id3)).get()?.name : void 0, "boardName");
51056
+ const place = /* @__PURE__ */ __name((board, column) => board ? `${board} \u203A ${column ?? ""}` : column ?? null, "place");
51057
+ const fromColumn = this.deps.db.select({ name: columns.name }).from(columns).where(eq(columns.id, card.columnId)).get()?.name ?? null;
51058
+ const from = place(boardName(card.boardId), fromColumn);
51059
+ const to = place(boardName(target.boardId), target.name);
50501
51060
  const moved = this.deps.db.transaction((tx) => {
51061
+ const prev = tx.select({ columnId: cards.columnId, boardId: cards.boardId }).from(cards).where(eq(cards.id, cardId)).get();
50502
51062
  const position2 = positionAt(tx, cards, and(eq(cards.columnId, columnId), isNull(cards.archivedAt)), index3, cardId);
50503
- return tx.update(cards).set({ columnId, position: position2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(cards.id, cardId)).returning().get();
51063
+ const row = tx.update(cards).set({ columnId, boardId: target.boardId, position: position2, updatedAt: /* @__PURE__ */ new Date() }).where(eq(cards.id, cardId)).returning().get();
51064
+ const lost = otherBoard ? tx.select({ id: cardLabels.labelId }).from(cardLabels).where(eq(cardLabels.cardId, cardId)).all().map((l) => l.id).sort() : [];
51065
+ if (lost.length) tx.delete(cardLabels).where(eq(cardLabels.cardId, cardId)).run();
51066
+ if (prev && prev.columnId !== columnId) {
51067
+ this.change(tx, actor, row, {
51068
+ kind: "card.moved",
51069
+ before: { boardId: prev.boardId, columnId: prev.columnId },
51070
+ after: { boardId: row.boardId, columnId },
51071
+ meta: { from, to, ...lost.length ? { labelIds: lost, labels: this.labelNames(tx, lost) } : {} }
51072
+ });
51073
+ }
51074
+ return row;
50504
51075
  });
50505
51076
  if (card.columnId !== columnId) {
50506
- const [from] = await this.deps.db.select({ name: columns.name }).from(columns).where(eq(columns.id, card.columnId));
50507
51077
  await this.activity.record(
50508
51078
  actor,
50509
51079
  card.workspaceId,
50510
- { action: "card.moved", entityType: "card", entityId: cardId, summary: card.title, meta: { from: from?.name ?? null, to: target.name } },
50511
- { boardId: card.boardId, cardId }
51080
+ { action: "card.moved", entityType: "card", entityId: cardId, summary: card.title, meta: { from, to } },
51081
+ { boardId: card.boardId, cardId, ...otherBoard ? { structure: true } : {} }
50512
51082
  );
51083
+ if (otherBoard) await this.activity.emit(card.workspaceId, { action: "card.moved", actor: actorRef(actor), boardId: target.boardId, cardId, structure: true });
50513
51084
  } else {
50514
51085
  await this.activity.emit(card.workspaceId, {
50515
51086
  action: "card.reordered",
@@ -50527,24 +51098,34 @@ var CardService = class {
50527
51098
  if (!archived) {
50528
51099
  patch.position = positionAt(this.deps.db, cards, and(eq(cards.columnId, card.columnId), isNull(cards.archivedAt)), void 0, cardId);
50529
51100
  }
50530
- await this.deps.db.update(cards).set(patch).where(eq(cards.id, cardId));
51101
+ this.deps.db.transaction((tx) => {
51102
+ const prev = tx.select({ archivedAt: cards.archivedAt }).from(cards).where(eq(cards.id, cardId)).get();
51103
+ tx.update(cards).set(patch).where(eq(cards.id, cardId)).run();
51104
+ if (prev) this.change(tx, actor, card, { kind: "card.archived", before: prev.archivedAt !== null, after: archived });
51105
+ });
50531
51106
  await this.activity.record(
50532
51107
  actor,
50533
51108
  card.workspaceId,
50534
51109
  { action: archived ? "card.archived" : "card.restored", entityType: "card", entityId: cardId, summary: card.title },
50535
- { boardId: card.boardId, cardId }
51110
+ { boardId: card.boardId, cardId, structure: true }
50536
51111
  );
50537
51112
  }
51113
+ /** Moves the card to the trash, with its checklists, labels, links and attachments. */
50538
51114
  async remove(actor, cardId) {
50539
- this.access.requireUser(actor);
51115
+ this.access.requireScope(actor, "organize");
50540
51116
  const card = await this.load(actor, cardId, "tasks:write");
50541
- await this.deps.db.delete(cards).where(eq(cards.id, cardId));
51117
+ const trashId = this.deps.db.transaction((tx) => {
51118
+ const trashId2 = this.trash.move(tx, actor, card.workspaceId, { kind: "card", id: cardId });
51119
+ this.change(tx, actor, card, { kind: "card.deleted", meta: { trashId: trashId2 } });
51120
+ return trashId2;
51121
+ });
50542
51122
  await this.activity.record(
50543
51123
  actor,
50544
51124
  card.workspaceId,
50545
51125
  { action: "card.deleted", entityType: "card", entityId: cardId, summary: card.title },
50546
- { boardId: card.boardId, cardId }
51126
+ { boardId: card.boardId, cardId, structure: true }
50547
51127
  );
51128
+ return trashId;
50548
51129
  }
50549
51130
  // ── Checklists ────────────────────────────────────────────────
50550
51131
  async touch(actor, card, detail) {
@@ -50559,10 +51140,14 @@ var CardService = class {
50559
51140
  async createChecklist(actor, cardId, input2) {
50560
51141
  const { title } = parse3(checklistCreateInput, input2);
50561
51142
  const card = await this.load(actor, cardId, "tasks:write");
50562
- const position2 = positionAt(this.deps.db, checklists, eq(checklists.cardId, cardId), void 0);
50563
- const [row] = await this.deps.db.insert(checklists).values({ workspaceId: card.workspaceId, cardId, title, position: position2 }).returning();
51143
+ const row = this.deps.db.transaction((tx) => {
51144
+ const position2 = positionAt(tx, checklists, eq(checklists.cardId, cardId), void 0);
51145
+ const row2 = tx.insert(checklists).values({ workspaceId: card.workspaceId, cardId, title, position: position2 }).returning().get();
51146
+ this.change(tx, actor, card, { kind: "checklist.created", subjectId: row2.id, meta: { title } });
51147
+ return row2;
51148
+ });
50564
51149
  await this.touch(actor, card, title);
50565
- return { id: row.id, cardId, title, position: position2, items: [] };
51150
+ return { id: row.id, cardId, title, position: row.position, items: [] };
50566
51151
  }
50567
51152
  async loadChecklist(actor, checklistId) {
50568
51153
  const [list] = await this.deps.db.select().from(checklists).where(eq(checklists.id, checklistId));
@@ -50573,23 +51158,36 @@ var CardService = class {
50573
51158
  async updateChecklist(actor, checklistId, input2) {
50574
51159
  const { title } = parse3(checklistUpdateInput, input2);
50575
51160
  const { card } = await this.loadChecklist(actor, checklistId);
50576
- await this.deps.db.update(checklists).set({ title }).where(eq(checklists.id, checklistId));
51161
+ this.deps.db.transaction((tx) => {
51162
+ const prev = tx.select({ title: checklists.title }).from(checklists).where(eq(checklists.id, checklistId)).get();
51163
+ tx.update(checklists).set({ title }).where(eq(checklists.id, checklistId)).run();
51164
+ if (prev) this.change(tx, actor, card, { kind: "checklist.title", subjectId: checklistId, before: prev.title, after: title });
51165
+ });
50577
51166
  await this.touch(actor, card, title);
50578
51167
  }
50579
- /** Only people delete checklists and their items: agents can't delete anything. */
51168
+ /** To the trash, with its items. Agents need to be allowed to delete and move. */
50580
51169
  async removeChecklist(actor, checklistId) {
50581
- this.access.requireUser(actor);
51170
+ this.access.requireScope(actor, "organize");
50582
51171
  const { list, card } = await this.loadChecklist(actor, checklistId);
50583
- await this.deps.db.delete(checklists).where(eq(checklists.id, checklistId));
51172
+ const trashId = this.deps.db.transaction((tx) => {
51173
+ const trashId2 = this.trash.move(tx, actor, card.workspaceId, { kind: "checklist", id: checklistId });
51174
+ this.change(tx, actor, card, { kind: "checklist.deleted", subjectId: checklistId, meta: { title: list.title, trashId: trashId2 } });
51175
+ return trashId2;
51176
+ });
50584
51177
  await this.touch(actor, card, list.title);
51178
+ return trashId;
50585
51179
  }
50586
51180
  async addItem(actor, checklistId, input2) {
50587
51181
  const { text: text2 } = parse3(checklistItemCreateInput, input2);
50588
51182
  const { list, card } = await this.loadChecklist(actor, checklistId);
50589
- const position2 = positionAt(this.deps.db, checklistItems, eq(checklistItems.checklistId, checklistId), void 0);
50590
- const [row] = await this.deps.db.insert(checklistItems).values({ workspaceId: list.workspaceId, checklistId, text: text2, position: position2 }).returning();
51183
+ const row = this.deps.db.transaction((tx) => {
51184
+ const position2 = positionAt(tx, checklistItems, eq(checklistItems.checklistId, checklistId), void 0);
51185
+ const row2 = tx.insert(checklistItems).values({ workspaceId: list.workspaceId, checklistId, text: text2, position: position2 }).returning().get();
51186
+ this.change(tx, actor, card, { kind: "item.created", subjectId: row2.id, meta: { text: text2, checklist: list.title } });
51187
+ return row2;
51188
+ });
50591
51189
  await this.touch(actor, card, text2);
50592
- return { id: row.id, checklistId, text: text2, done: false, position: position2 };
51190
+ return { id: row.id, checklistId, text: text2, done: false, position: row.position };
50593
51191
  }
50594
51192
  async loadItem(actor, itemId) {
50595
51193
  const [item] = await this.deps.db.select().from(checklistItems).where(eq(checklistItems.id, itemId));
@@ -50603,18 +51201,28 @@ var CardService = class {
50603
51201
  const patch = { updatedAt: /* @__PURE__ */ new Date() };
50604
51202
  if (data.text !== void 0) patch.text = data.text;
50605
51203
  if (data.done !== void 0) patch.done = data.done;
50606
- if (data.index !== void 0) {
50607
- patch.position = positionAt(this.deps.db, checklistItems, eq(checklistItems.checklistId, item.checklistId), data.index, itemId);
50608
- }
50609
- const [row] = await this.deps.db.update(checklistItems).set(patch).where(eq(checklistItems.id, itemId)).returning();
51204
+ const row = this.deps.db.transaction((tx) => {
51205
+ const prev = tx.select().from(checklistItems).where(eq(checklistItems.id, itemId)).get();
51206
+ if (!prev) throw notFound("Checklist item");
51207
+ if (data.index !== void 0) patch.position = positionAt(tx, checklistItems, eq(checklistItems.checklistId, item.checklistId), data.index, itemId);
51208
+ const row2 = tx.update(checklistItems).set(patch).where(eq(checklistItems.id, itemId)).returning().get();
51209
+ if (data.text !== void 0) this.change(tx, actor, card, { kind: "item.text", subjectId: itemId, before: prev.text, after: row2.text });
51210
+ if (data.done !== void 0) this.change(tx, actor, card, { kind: "item.done", subjectId: itemId, before: prev.done, after: row2.done, meta: { text: row2.text } });
51211
+ return row2;
51212
+ });
50610
51213
  await this.touch(actor, card, row.text);
50611
51214
  return { id: row.id, checklistId: row.checklistId, text: row.text, done: row.done, position: row.position };
50612
51215
  }
50613
51216
  async removeItem(actor, itemId) {
50614
- this.access.requireUser(actor);
51217
+ this.access.requireScope(actor, "organize");
50615
51218
  const { item, card } = await this.loadItem(actor, itemId);
50616
- await this.deps.db.delete(checklistItems).where(eq(checklistItems.id, itemId));
51219
+ const trashId = this.deps.db.transaction((tx) => {
51220
+ const trashId2 = this.trash.move(tx, actor, card.workspaceId, { kind: "checklist_item", id: itemId });
51221
+ this.change(tx, actor, card, { kind: "item.deleted", subjectId: itemId, meta: { text: item.text, trashId: trashId2 } });
51222
+ return trashId2;
51223
+ });
50617
51224
  await this.touch(actor, card, item.text);
51225
+ return trashId;
50618
51226
  }
50619
51227
  // ── Card ↔ page links ─────────────────────────────────────────
50620
51228
  async linkPage(actor, cardId, input2) {
@@ -50624,7 +51232,10 @@ var CardService = class {
50624
51232
  const card = await this.load(actor, cardId, "tasks:read");
50625
51233
  const [page] = await this.deps.db.select().from(pages).where(eq(pages.id, pageId));
50626
51234
  if (!page || page.workspaceId !== card.workspaceId) throw notFound("Page");
50627
- await this.deps.db.insert(cardPageLinks).values({ cardId, pageId, workspaceId: card.workspaceId, source: "manual" }).onConflictDoNothing();
51235
+ this.deps.db.transaction((tx) => {
51236
+ const added = tx.insert(cardPageLinks).values({ cardId, pageId, workspaceId: card.workspaceId, source: "manual" }).onConflictDoNothing().returning({ pageId: cardPageLinks.pageId }).all();
51237
+ if (added.length) this.change(tx, actor, card, { kind: "card.linked", subjectId: pageId, meta: { page: page.title } });
51238
+ });
50628
51239
  await this.activity.record(
50629
51240
  actor,
50630
51241
  card.workspaceId,
@@ -50632,19 +51243,26 @@ var CardService = class {
50632
51243
  { boardId: card.boardId, cardId, pageId }
50633
51244
  );
50634
51245
  }
50635
- /** Only people remove links: agents can link a page to a card but can't delete anything. */
51246
+ /** To the trash. Agents need write access to tasks or documents, and to be allowed to delete and move. */
50636
51247
  async unlinkPage(actor, cardId, pageId) {
50637
- this.access.requireUser(actor);
51248
+ this.access.requireScope(actor, "organize");
51249
+ this.access.requireAnyScope(actor, ["tasks:write", "docs:write"]);
51250
+ this.access.requireScope(actor, "docs:read");
50638
51251
  const card = await this.load(actor, cardId, "tasks:read");
50639
- const removed = await this.deps.db.delete(cardPageLinks).where(and(eq(cardPageLinks.cardId, cardId), eq(cardPageLinks.pageId, pageId), eq(cardPageLinks.source, "manual"))).returning({ pageId: cardPageLinks.pageId });
50640
- if (removed.length === 0) return;
50641
51252
  const [page] = await this.deps.db.select({ title: pages.title }).from(pages).where(eq(pages.id, pageId));
51253
+ const trashId = this.deps.db.transaction((tx) => {
51254
+ const trashId2 = this.trash.move(tx, actor, card.workspaceId, { kind: "link", cardId, pageId });
51255
+ if (trashId2) this.change(tx, actor, card, { kind: "card.unlinked", subjectId: pageId, meta: { page: page?.title ?? "", trashId: trashId2 } });
51256
+ return trashId2;
51257
+ });
51258
+ if (!trashId) return null;
50642
51259
  await this.activity.record(
50643
51260
  actor,
50644
51261
  card.workspaceId,
50645
51262
  { action: "card.unlinked", entityType: "card", entityId: cardId, summary: card.title, meta: { page: page?.title ?? "" } },
50646
51263
  { boardId: card.boardId, cardId, pageId }
50647
51264
  );
51265
+ return trashId;
50648
51266
  }
50649
51267
  };
50650
51268
 
@@ -50656,16 +51274,18 @@ var toColumnDTO = /* @__PURE__ */ __name((c) => ({
50656
51274
  position: c.position
50657
51275
  }), "toColumnDTO");
50658
51276
  var BoardService = class {
50659
- constructor(deps, access, activity2, cards2) {
51277
+ constructor(deps, access, activity2, cards2, trash2) {
50660
51278
  this.deps = deps;
50661
51279
  this.access = access;
50662
51280
  this.activity = activity2;
50663
51281
  this.cards = cards2;
51282
+ this.trash = trash2;
50664
51283
  }
50665
51284
  deps;
50666
51285
  access;
50667
51286
  activity;
50668
51287
  cards;
51288
+ trash;
50669
51289
  static {
50670
51290
  __name(this, "BoardService");
50671
51291
  }
@@ -50742,15 +51362,16 @@ var BoardService = class {
50742
51362
  );
50743
51363
  }
50744
51364
  async remove(actor, boardId) {
50745
- this.access.requireUser(actor);
51365
+ this.access.requireScope(actor, "organize");
50746
51366
  const board = await this.load(actor, boardId, "tasks:write");
50747
- await this.deps.db.delete(boards).where(eq(boards.id, boardId));
51367
+ const trashId = this.deps.db.transaction((tx) => this.trash.move(tx, actor, board.workspaceId, { kind: "board", id: boardId }));
50748
51368
  await this.activity.record(
50749
51369
  actor,
50750
51370
  board.workspaceId,
50751
51371
  { action: "board.deleted", entityType: "board", entityId: boardId, summary: board.name },
50752
51372
  { boardId, projectId: board.projectId, structure: true }
50753
51373
  );
51374
+ return trashId;
50754
51375
  }
50755
51376
  // ── Columns ───────────────────────────────────────────────────
50756
51377
  async createColumn(actor, boardId, input2) {
@@ -50797,16 +51418,17 @@ var BoardService = class {
50797
51418
  return toColumnDTO(row);
50798
51419
  }
50799
51420
  async removeColumn(actor, columnId) {
50800
- this.access.requireUser(actor);
51421
+ this.access.requireScope(actor, "organize");
50801
51422
  const column = await this.loadColumn(actor, columnId, "tasks:write");
50802
51423
  const [{ total }] = await this.deps.db.select({ total: count() }).from(cards).where(eq(cards.columnId, columnId));
50803
- await this.deps.db.delete(columns).where(eq(columns.id, columnId));
51424
+ const trashId = this.deps.db.transaction((tx) => this.trash.move(tx, actor, column.workspaceId, { kind: "column", id: columnId }));
50804
51425
  await this.activity.record(
50805
51426
  actor,
50806
51427
  column.workspaceId,
50807
51428
  { action: "column.deleted", entityType: "column", entityId: columnId, summary: column.name, meta: { cards: total } },
50808
51429
  { boardId: column.boardId, structure: total > 0 }
50809
51430
  );
51431
+ return trashId;
50810
51432
  }
50811
51433
  // ── Labels ────────────────────────────────────────────────────
50812
51434
  async createLabel(actor, boardId, input2) {
@@ -50840,17 +51462,162 @@ var BoardService = class {
50840
51462
  );
50841
51463
  return toLabelDTO(row);
50842
51464
  }
50843
- /** Only people delete labels: agents can't delete anything (see README, "Connecting agents"). */
51465
+ /** To the trash, taking it off its cards. Agents need to be allowed to delete and move. */
50844
51466
  async removeLabel(actor, labelId) {
50845
- this.access.requireUser(actor);
51467
+ this.access.requireScope(actor, "organize");
50846
51468
  const label = await this.loadLabel(actor, labelId);
50847
- await this.deps.db.delete(labels).where(eq(labels.id, labelId));
51469
+ const trashId = this.deps.db.transaction((tx) => this.trash.move(tx, actor, label.workspaceId, { kind: "label", id: labelId }));
50848
51470
  await this.activity.record(
50849
51471
  actor,
50850
51472
  label.workspaceId,
50851
51473
  { action: "label.deleted", entityType: "label", entityId: labelId, summary: label.name },
50852
51474
  { boardId: label.boardId }
50853
51475
  );
51476
+ return trashId;
51477
+ }
51478
+ };
51479
+
51480
+ // src/services/history.ts
51481
+ var STRETCH_MS = 10 * 60 * 1e3;
51482
+ var DAY_MS = 864e5;
51483
+ var MARK = /\.(created|deleted|restored|linked|unlinked)$/;
51484
+ var LIST_COLUMNS = (() => {
51485
+ const body = inArray(history.kind, [...HISTORY_BODY_KINDS]);
51486
+ return {
51487
+ ...getTableColumns(history),
51488
+ before: sql`CASE WHEN ${body} THEN NULL ELSE ${history.before} END`,
51489
+ after: sql`CASE WHEN ${body} THEN NULL ELSE ${history.after} END`
51490
+ };
51491
+ })();
51492
+ var encode3 = /* @__PURE__ */ __name((kind, value) => value === null || value === void 0 ? null : HISTORY_TEXT_KINDS.has(kind) ? String(value) : JSON.stringify(value), "encode");
51493
+ var decode3 = /* @__PURE__ */ __name((kind, raw2) => raw2 === null ? null : HISTORY_TEXT_KINDS.has(kind) ? raw2 : JSON.parse(raw2), "decode");
51494
+ var bodyMeta = /* @__PURE__ */ __name((kind, before, after) => {
51495
+ if (!HISTORY_BODY_KINDS.has(kind)) return {};
51496
+ const { added, removed } = lineStats(before ?? "", after ?? "");
51497
+ return { linesAdded: added, linesRemoved: removed };
51498
+ }, "bodyMeta");
51499
+ function toHistoryEntryDTO(row, withBodies) {
51500
+ const hidden = !withBodies && HISTORY_BODY_KINDS.has(row.kind);
51501
+ return {
51502
+ id: row.id,
51503
+ entityType: row.entityType,
51504
+ entityId: row.entityId,
51505
+ kind: row.kind,
51506
+ subjectId: row.subjectId,
51507
+ before: hidden ? null : decode3(row.kind, row.before),
51508
+ after: hidden ? null : decode3(row.kind, row.after),
51509
+ meta: row.meta,
51510
+ actor: { kind: row.actorKind, id: (row.actorKind === "agent" ? row.actorTokenId : row.actorUserId) ?? "", name: row.actorName },
51511
+ batchId: row.batchId,
51512
+ createdAt: row.createdAt.toISOString(),
51513
+ updatedAt: row.updatedAt.toISOString()
51514
+ };
51515
+ }
51516
+ __name(toHistoryEntryDTO, "toHistoryEntryDTO");
51517
+ var HistoryService = class {
51518
+ constructor(deps, access) {
51519
+ this.deps = deps;
51520
+ this.access = access;
51521
+ }
51522
+ deps;
51523
+ access;
51524
+ static {
51525
+ __name(this, "HistoryService");
51526
+ }
51527
+ /**
51528
+ * Records a change. Synchronous, to run in the transaction that makes it: the value before
51529
+ * is read there, and the change and its record are saved together or not at all.
51530
+ */
51531
+ record(db, actor, workspaceId, change, now = /* @__PURE__ */ new Date()) {
51532
+ const kind = change.kind;
51533
+ const before = encode3(kind, change.before);
51534
+ const after = encode3(kind, change.after);
51535
+ if (!MARK.test(kind) && before === after) return;
51536
+ const subject = change.subjectId ?? null;
51537
+ const note = actor.kind === "user" ? actor.note : void 0;
51538
+ if (note) change = { ...change, meta: { ...change.meta, ...note } };
51539
+ if (actor.kind === "user" && !note && HISTORY_TEXT_KINDS.has(kind)) {
51540
+ const last = db.select().from(history).where(and(eq(history.entityId, change.entityId), eq(history.kind, kind), subject ? eq(history.subjectId, subject) : isNull(history.subjectId))).orderBy(desc(history.updatedAt), desc(sql`rowid`)).limit(1).get();
51541
+ const annotated = Boolean(last?.meta.undoOf || last?.meta.restoredFrom);
51542
+ if (last && !annotated && last.actorKind === "user" && last.actorUserId === actor.userId && last.updatedAt.getTime() > now.getTime() - STRETCH_MS) {
51543
+ if (last.before === after) db.delete(history).where(eq(history.id, last.id)).run();
51544
+ else
51545
+ db.update(history).set({ after, meta: { ...last.meta, ...change.meta, ...bodyMeta(kind, last.before, after) }, updatedAt: now }).where(eq(history.id, last.id)).run();
51546
+ return;
51547
+ }
51548
+ }
51549
+ const recent = db.select({ batchId: history.batchId }).from(history).where(
51550
+ and(
51551
+ actor.kind === "agent" ? eq(history.actorTokenId, actor.tokenId) : and(eq(history.actorUserId, actor.userId), eq(history.actorKind, "user")),
51552
+ eq(history.workspaceId, workspaceId),
51553
+ gt(history.updatedAt, new Date(now.getTime() - STRETCH_MS))
51554
+ )
51555
+ ).orderBy(desc(history.updatedAt)).limit(1).get();
51556
+ db.insert(history).values({
51557
+ workspaceId,
51558
+ entityType: change.entityType,
51559
+ entityId: change.entityId,
51560
+ kind,
51561
+ subjectId: subject,
51562
+ before,
51563
+ after,
51564
+ meta: { ...change.meta, ...bodyMeta(kind, before, after) },
51565
+ actorKind: actor.kind,
51566
+ actorUserId: actor.userId,
51567
+ actorTokenId: actor.kind === "agent" ? actor.tokenId : null,
51568
+ actorName: actor.name,
51569
+ batchId: recent?.batchId ?? crypto.randomUUID(),
51570
+ createdAt: now,
51571
+ updatedAt: now
51572
+ }).run();
51573
+ }
51574
+ /** Checks the actor can read the page or card, which must exist (not in the trash). */
51575
+ async entity(actor, entityType, entityId) {
51576
+ this.access.requireScope(actor, entityType === "page" ? "docs:read" : "tasks:read");
51577
+ const table = entityType === "page" ? pages : cards;
51578
+ const [row] = await this.deps.db.select({ workspaceId: table.workspaceId }).from(table).where(eq(table.id, entityId));
51579
+ if (!row) throw notFound(entityType === "page" ? "Page" : "Card");
51580
+ await this.access.workspace(actor, row.workspaceId);
51581
+ }
51582
+ /**
51583
+ * The changes of a page or a card, newest first, after the entry `beforeId` (updated at
51584
+ * `before`) of the previous page. Long texts are left out, not even read; `get` has them.
51585
+ */
51586
+ async list(actor, entityType, entityId, opts = {}) {
51587
+ await this.entity(actor, entityType, entityId);
51588
+ const rows = await this.deps.db.select(LIST_COLUMNS).from(history).where(and(eq(history.entityId, entityId), eq(history.entityType, entityType), this.after(opts.before, opts.beforeId))).orderBy(desc(history.updatedAt), desc(sql`rowid`)).limit(Math.min(opts.limit ?? 50, 100));
51589
+ return rows.map((row) => toHistoryEntryDTO(row, false));
51590
+ }
51591
+ /**
51592
+ * Where the next page starts: after the last entry of the previous one, in the list's order.
51593
+ * Several changes can share a millisecond, so the entry itself breaks the tie. If it changed
51594
+ * since (merged with a later edit, or gone), the time alone is the best there is.
51595
+ */
51596
+ after(before, beforeId) {
51597
+ if (!before) return void 0;
51598
+ const anchor2 = beforeId ? this.deps.db.get(sql`SELECT rowid AS seq FROM history WHERE id = ${beforeId} AND updated_at = ${before.getTime()}`) : void 0;
51599
+ if (!anchor2) return lt(history.updatedAt, before);
51600
+ return or(lt(history.updatedAt, before), and(eq(history.updatedAt, before), sql`rowid < ${anchor2.seq}`));
51601
+ }
51602
+ /** One change, with its texts before and after. */
51603
+ async get(actor, entryId) {
51604
+ const [row] = await this.deps.db.select().from(history).where(eq(history.id, entryId));
51605
+ if (!row) throw notFound("History entry");
51606
+ await this.entity(actor, row.entityType, row.entityId);
51607
+ return toHistoryEntryDTO(row, true);
51608
+ }
51609
+ /**
51610
+ * Forgets the history of what a trash entry holds, as it is deleted for good: the pages and
51611
+ * cards in it, and the checklists, items and files it took from a card or a page.
51612
+ */
51613
+ forget(db, trashId) {
51614
+ const ids = sql`SELECT json_extract(data, '$.id') FROM trash_rows WHERE trash_id = ${trashId}`;
51615
+ db.delete(history).where(or(sql`${history.entityId} IN (${ids})`, sql`${history.subjectId} IN (${ids})`)).run();
51616
+ }
51617
+ /** Deletes what has been in the history for HISTORY_DAYS. Runs hourly. */
51618
+ async purgeExpired(now = /* @__PURE__ */ new Date()) {
51619
+ const removed = await this.deps.db.delete(history).where(lte(history.updatedAt, new Date(now.getTime() - HISTORY_DAYS * DAY_MS))).returning({ id: history.id });
51620
+ return removed.length;
50854
51621
  }
50855
51622
  };
50856
51623
 
@@ -50951,98 +51718,1069 @@ var SearchService = class {
50951
51718
  }
50952
51719
  };
50953
51720
 
50954
- // src/services/tokens.ts
50955
- var TOKEN_PREFIX = "orq_";
50956
- var toTokenDTO = /* @__PURE__ */ __name((t, workspaceName) => ({
50957
- id: t.id,
50958
- name: t.name,
50959
- workspaceId: t.workspaceId,
50960
- workspaceName,
50961
- prefix: t.prefix,
50962
- scopes: t.scopes.filter((s) => SCOPES.includes(s)),
50963
- createdAt: t.createdAt.toISOString(),
50964
- lastUsedAt: t.lastUsedAt?.toISOString() ?? null,
50965
- expiresAt: t.expiresAt?.toISOString() ?? null,
50966
- revokedAt: t.revokedAt?.toISOString() ?? null,
50967
- oauth: t.oauthClientId ? { clientId: t.oauthClientId, redirectUri: t.oauthRedirectUri ?? "" } : null
50968
- }), "toTokenDTO");
50969
- var TokenService = class {
50970
- constructor(deps, access) {
51721
+ // src/services/trash.ts
51722
+ var TABLES = {
51723
+ projects,
51724
+ boards,
51725
+ board_columns: columns,
51726
+ labels,
51727
+ cards,
51728
+ card_labels: cardLabels,
51729
+ checklists,
51730
+ checklist_items: checklistItems,
51731
+ pages,
51732
+ card_page_links: cardPageLinks,
51733
+ attachments
51734
+ };
51735
+ var ORDER = Object.keys(TABLES);
51736
+ var ROOT_TABLE = {
51737
+ project: "projects",
51738
+ board: "boards",
51739
+ column: "board_columns",
51740
+ card: "cards",
51741
+ page: "pages",
51742
+ attachment: "attachments",
51743
+ label: "labels",
51744
+ checklist: "checklists",
51745
+ checklist_item: "checklist_items",
51746
+ link: "card_page_links"
51747
+ };
51748
+ var COUNTED = {
51749
+ boards: "boards",
51750
+ board_columns: "columns",
51751
+ cards: "cards",
51752
+ pages: "pages",
51753
+ attachments: "attachments",
51754
+ checklists: "checklists",
51755
+ checklist_items: "items",
51756
+ labels: "labels"
51757
+ };
51758
+ var DAY_MS2 = 24 * 60 * 60 * 1e3;
51759
+ var SEPARATOR = " \u203A ";
51760
+ var Snapshot = class {
51761
+ constructor(db) {
51762
+ this.db = db;
51763
+ }
51764
+ db;
51765
+ static {
51766
+ __name(this, "Snapshot");
51767
+ }
51768
+ rows = [];
51769
+ seen = /* @__PURE__ */ new Set();
51770
+ query(table, query) {
51771
+ for (const data of this.db.all(query)) {
51772
+ const key = data.id != null ? `${table} ${String(data.id)}` : `${table} ${JSON.stringify(data)}`;
51773
+ if (this.seen.has(key)) continue;
51774
+ this.seen.add(key);
51775
+ this.rows.push({ table, data });
51776
+ }
51777
+ }
51778
+ where(table, where) {
51779
+ this.query(table, sql`SELECT * FROM ${sql.identifier(table)} WHERE ${where} ORDER BY rowid`);
51780
+ }
51781
+ /** `scope` selects card ids: the cards and everything on them. */
51782
+ cards(scope) {
51783
+ this.where("cards", sql`id IN (${scope})`);
51784
+ this.where("card_labels", sql`card_id IN (${scope})`);
51785
+ this.where("checklists", sql`card_id IN (${scope})`);
51786
+ this.where("checklist_items", sql`checklist_id IN (SELECT id FROM checklists WHERE card_id IN (${scope}))`);
51787
+ this.where("card_page_links", sql`card_id IN (${scope})`);
51788
+ this.where("attachments", sql`card_id IN (${scope})`);
51789
+ }
51790
+ /** The pages matching `roots`, with every page under them, top ones first. */
51791
+ pages(roots) {
51792
+ const tree = pageTree(roots);
51793
+ this.query("pages", sql`${tree} SELECT p.* FROM pages p JOIN tree t ON t.id = p.id ORDER BY t.depth, p.position, p.id`);
51794
+ this.query("card_page_links", sql`${tree} SELECT * FROM card_page_links WHERE page_id IN (SELECT id FROM tree)`);
51795
+ this.query("attachments", sql`${tree} SELECT * FROM attachments WHERE page_id IN (SELECT id FROM tree)`);
51796
+ }
51797
+ /** Parents before children; within a table, in the order they were read. */
51798
+ sorted() {
51799
+ return this.rows.map((row, i) => ({ row, i })).sort((a, b) => ORDER.indexOf(a.row.table) - ORDER.indexOf(b.row.table) || a.i - b.i).map((x) => x.row);
51800
+ }
51801
+ };
51802
+ var restoreError = /* @__PURE__ */ __name((code, message, details) => new AppError(409, code, message, details), "restoreError");
51803
+ var TrashService = class {
51804
+ constructor(deps, access, activity2, history2) {
50971
51805
  this.deps = deps;
50972
51806
  this.access = access;
51807
+ this.activity = activity2;
51808
+ this.history = history2;
50973
51809
  }
50974
51810
  deps;
50975
51811
  access;
51812
+ activity;
51813
+ history;
50976
51814
  static {
50977
- __name(this, "TokenService");
51815
+ __name(this, "TrashService");
50978
51816
  }
50979
- lastTouched = /* @__PURE__ */ new Map();
50980
- async list(actor) {
50981
- this.access.requireUser(actor);
50982
- const rows = await this.deps.db.select({ token: apiTokens, workspaceName: workspaces.name }).from(apiTokens).innerJoin(workspaces, eq(workspaces.id, apiTokens.workspaceId)).where(eq(apiTokens.userId, actor.userId)).orderBy(desc(apiTokens.createdAt));
50983
- return rows.map((r) => toTokenDTO(r.token, r.workspaceName));
51817
+ /** What restoring the item says in the history of the page or card it belongs to. */
51818
+ restoredChange(tx, kind, data, meta3) {
51819
+ const text2 = /* @__PURE__ */ __name((value) => typeof value === "string" ? value : "", "text");
51820
+ const id3 = text2(data.id);
51821
+ switch (kind) {
51822
+ case "card":
51823
+ return { entityType: "card", entityId: id3, kind: "card.restored", meta: meta3 };
51824
+ case "page":
51825
+ return { entityType: "page", entityId: id3, kind: "page.restored", meta: meta3 };
51826
+ case "checklist":
51827
+ return { entityType: "card", entityId: text2(data.card_id), kind: "checklist.restored", subjectId: id3, meta: { ...meta3, title: text2(data.title) } };
51828
+ case "checklist_item": {
51829
+ const list = tx.get(sql`SELECT card_id FROM checklists WHERE id = ${text2(data.checklist_id)}`);
51830
+ return list ? { entityType: "card", entityId: list.card_id, kind: "item.restored", subjectId: id3, meta: { ...meta3, text: text2(data.text) } } : null;
51831
+ }
51832
+ case "attachment":
51833
+ return {
51834
+ ...data.page_id ? { entityType: "page", entityId: text2(data.page_id) } : { entityType: "card", entityId: text2(data.card_id) },
51835
+ kind: "attachment.restored",
51836
+ subjectId: id3,
51837
+ meta: { ...meta3, name: text2(data.filename) }
51838
+ };
51839
+ case "link": {
51840
+ const page = tx.get(sql`SELECT title FROM pages WHERE id = ${text2(data.page_id)}`);
51841
+ return { entityType: "card", entityId: text2(data.card_id), kind: "card.linked", subjectId: text2(data.page_id), meta: { ...meta3, page: page?.title ?? "" } };
51842
+ }
51843
+ default:
51844
+ return null;
51845
+ }
50984
51846
  }
50985
- async create(actor, input2) {
51847
+ /**
51848
+ * Moves an item, with everything it holds, to the trash and deletes it. Synchronous, so
51849
+ * the caller can run it inside its own transaction. Returns the trash entry's id, or
51850
+ * null when there was nothing to delete.
51851
+ */
51852
+ move(db, actor, workspaceId, target) {
51853
+ const snapshot = new Snapshot(db);
51854
+ const root = this.capture(db, snapshot, target);
51855
+ if (!root) return null;
51856
+ const rows = snapshot.sorted();
51857
+ const contents = {};
51858
+ let bytes = 0;
51859
+ for (const { table, data } of rows) {
51860
+ if (table === "attachments") bytes += Number(data.size ?? 0);
51861
+ if (data === root.data) continue;
51862
+ const counted = COUNTED[table];
51863
+ if (counted) contents[counted] = (contents[counted] ?? 0) + 1;
51864
+ }
51865
+ const now = /* @__PURE__ */ new Date();
51866
+ const [entry] = db.insert(trash).values({
51867
+ workspaceId,
51868
+ kind: target.kind,
51869
+ entityId: target.kind === "link" ? `${target.cardId}:${target.pageId}` : target.id,
51870
+ title: root.title,
51871
+ location: root.location,
51872
+ contents,
51873
+ bytes,
51874
+ actorKind: actor.kind,
51875
+ actorUserId: actor.kind === "user" ? actor.userId : null,
51876
+ actorTokenId: actor.kind === "agent" ? actor.tokenId : null,
51877
+ actorName: actor.name,
51878
+ deletedAt: now,
51879
+ expiresAt: new Date(now.getTime() + TRASH_DAYS * DAY_MS2)
51880
+ }).returning({ id: trash.id }).all();
51881
+ for (const { table, data } of rows) {
51882
+ db.insert(trashRows).values({ trashId: entry.id, tableName: table, data, storageKey: table === "attachments" ? String(data.storage_key) : null }).run();
51883
+ }
51884
+ this.remove(db, target);
51885
+ return entry.id;
51886
+ }
51887
+ /** Reads the item's rows into `snapshot`; returns its own row, title and location, or null if it doesn't exist. */
51888
+ capture(db, snapshot, target) {
51889
+ const one = /* @__PURE__ */ __name((table, id3) => db.get(sql`SELECT * FROM ${sql.identifier(table)} WHERE id = ${id3}`), "one");
51890
+ const name2 = /* @__PURE__ */ __name((query) => db.get(query)?.name ?? "", "name");
51891
+ const path = /* @__PURE__ */ __name((...parts) => parts.filter(Boolean).join(SEPARATOR), "path");
51892
+ const boardPath = /* @__PURE__ */ __name((boardId) => path(name2(sql`SELECT p.name FROM boards b JOIN projects p ON p.id = b.project_id WHERE b.id = ${boardId}`), name2(sql`SELECT name FROM boards WHERE id = ${boardId}`)), "boardPath");
51893
+ const cardPath = /* @__PURE__ */ __name((cardId) => {
51894
+ const card = db.get(sql`SELECT board_id, column_id, title FROM cards WHERE id = ${cardId}`);
51895
+ return card ? path(boardPath(card.board_id), card.title) : "";
51896
+ }, "cardPath");
51897
+ const pagePath = /* @__PURE__ */ __name((pageId) => {
51898
+ const page = db.get(sql`SELECT project_id, title FROM pages WHERE id = ${pageId}`);
51899
+ return page ? path(name2(sql`SELECT name FROM projects WHERE id = ${page.project_id}`), page.title) : "";
51900
+ }, "pagePath");
51901
+ switch (target.kind) {
51902
+ case "project": {
51903
+ const row = one("projects", target.id);
51904
+ if (!row) return null;
51905
+ snapshot.where("projects", sql`id = ${target.id}`);
51906
+ const boardIds = sql`SELECT id FROM boards WHERE project_id = ${target.id}`;
51907
+ snapshot.where("boards", sql`project_id = ${target.id}`);
51908
+ snapshot.where("board_columns", sql`board_id IN (${boardIds})`);
51909
+ snapshot.where("labels", sql`board_id IN (${boardIds})`);
51910
+ snapshot.cards(sql`SELECT id FROM cards WHERE board_id IN (${boardIds})`);
51911
+ snapshot.pages(sql`project_id = ${target.id} AND parent_id IS NULL`);
51912
+ return { data: snapshot.rows[0].data, title: String(row.name), location: "" };
51913
+ }
51914
+ case "board": {
51915
+ const row = one("boards", target.id);
51916
+ if (!row) return null;
51917
+ snapshot.where("boards", sql`id = ${target.id}`);
51918
+ snapshot.where("board_columns", sql`board_id = ${target.id}`);
51919
+ snapshot.where("labels", sql`board_id = ${target.id}`);
51920
+ snapshot.cards(sql`SELECT id FROM cards WHERE board_id = ${target.id}`);
51921
+ return { data: snapshot.rows[0].data, title: String(row.name), location: name2(sql`SELECT name FROM projects WHERE id = ${row.project_id}`) };
51922
+ }
51923
+ case "column": {
51924
+ const row = one("board_columns", target.id);
51925
+ if (!row) return null;
51926
+ snapshot.where("board_columns", sql`id = ${target.id}`);
51927
+ snapshot.cards(sql`SELECT id FROM cards WHERE column_id = ${target.id}`);
51928
+ return { data: snapshot.rows[0].data, title: String(row.name), location: boardPath(row.board_id) };
51929
+ }
51930
+ case "card": {
51931
+ const row = one("cards", target.id);
51932
+ if (!row) return null;
51933
+ snapshot.cards(sql`SELECT ${target.id}`);
51934
+ const column = name2(sql`SELECT name FROM board_columns WHERE id = ${row.column_id}`);
51935
+ return { data: snapshot.rows[0].data, title: String(row.title), location: path(boardPath(row.board_id), column) };
51936
+ }
51937
+ case "page": {
51938
+ const row = one("pages", target.id);
51939
+ if (!row) return null;
51940
+ snapshot.pages(sql`id = ${target.id}`);
51941
+ const parent = row.parent_id ? name2(sql`SELECT title AS name FROM pages WHERE id = ${row.parent_id}`) : "";
51942
+ return { data: snapshot.rows[0].data, title: String(row.title), location: path(name2(sql`SELECT name FROM projects WHERE id = ${row.project_id}`), parent) };
51943
+ }
51944
+ case "attachment": {
51945
+ const row = one("attachments", target.id);
51946
+ if (!row) return null;
51947
+ snapshot.where("attachments", sql`id = ${target.id}`);
51948
+ return { data: snapshot.rows[0].data, title: String(row.filename), location: row.card_id ? cardPath(row.card_id) : pagePath(row.page_id) };
51949
+ }
51950
+ case "label": {
51951
+ const row = one("labels", target.id);
51952
+ if (!row) return null;
51953
+ snapshot.where("labels", sql`id = ${target.id}`);
51954
+ snapshot.where("card_labels", sql`label_id = ${target.id}`);
51955
+ return { data: snapshot.rows[0].data, title: String(row.name), location: boardPath(row.board_id) };
51956
+ }
51957
+ case "checklist": {
51958
+ const row = one("checklists", target.id);
51959
+ if (!row) return null;
51960
+ snapshot.where("checklists", sql`id = ${target.id}`);
51961
+ snapshot.where("checklist_items", sql`checklist_id = ${target.id}`);
51962
+ return { data: snapshot.rows[0].data, title: String(row.title), location: cardPath(row.card_id) };
51963
+ }
51964
+ case "checklist_item": {
51965
+ const row = one("checklist_items", target.id);
51966
+ if (!row) return null;
51967
+ snapshot.where("checklist_items", sql`id = ${target.id}`);
51968
+ const list = db.get(sql`SELECT card_id, title FROM checklists WHERE id = ${row.checklist_id}`);
51969
+ return { data: snapshot.rows[0].data, title: String(row.text), location: list ? path(cardPath(list.card_id), list.title) : "" };
51970
+ }
51971
+ case "link": {
51972
+ snapshot.where("card_page_links", sql`card_id = ${target.cardId} AND page_id = ${target.pageId} AND source = 'manual'`);
51973
+ if (snapshot.rows.length === 0) return null;
51974
+ const page = db.get(sql`SELECT title FROM pages WHERE id = ${target.pageId}`);
51975
+ return { data: snapshot.rows[0].data, title: page?.title ?? "", location: cardPath(target.cardId) };
51976
+ }
51977
+ }
51978
+ }
51979
+ /** Deletes the item; what it holds goes with it by cascade, page trees deepest first. */
51980
+ remove(db, target) {
51981
+ switch (target.kind) {
51982
+ case "project":
51983
+ deletePageTrees(db, sql`${pages.projectId} = ${target.id} AND ${pages.parentId} IS NULL`);
51984
+ db.delete(projects).where(eq(projects.id, target.id)).run();
51985
+ return;
51986
+ case "page":
51987
+ deletePageTrees(db, sql`${pages.id} = ${target.id}`);
51988
+ return;
51989
+ case "link":
51990
+ db.delete(cardPageLinks).where(and(eq(cardPageLinks.cardId, target.cardId), eq(cardPageLinks.pageId, target.pageId), eq(cardPageLinks.source, "manual"))).run();
51991
+ return;
51992
+ default: {
51993
+ const table = TABLES[ROOT_TABLE[target.kind]];
51994
+ db.delete(table).where(eq(table.id, target.id)).run();
51995
+ }
51996
+ }
51997
+ }
51998
+ // ── People's side: listing, restoring, deleting for good ─────
51999
+ async list(actor, workspaceId) {
50986
52000
  this.access.requireUser(actor);
50987
- const data = parse3(tokenCreateInput, input2);
50988
- await this.access.workspace(actor, data.workspaceId);
50989
- const token = `${TOKEN_PREFIX}${randomToken(32)}`;
50990
- const scopes = [...new Set(data.scopes)];
50991
- if (scopes.includes("tasks:write") && !scopes.includes("tasks:read")) scopes.push("tasks:read");
50992
- if (scopes.includes("docs:write") && !scopes.includes("docs:read")) scopes.push("docs:read");
50993
- const [row] = await this.deps.db.insert(apiTokens).values({
50994
- userId: actor.userId,
50995
- workspaceId: data.workspaceId,
50996
- name: data.name,
50997
- tokenHash: sha2562(token),
50998
- prefix: token.slice(0, 12),
50999
- scopes,
51000
- expiresAt: data.expiresInDays ? new Date(Date.now() + data.expiresInDays * 864e5) : null
51001
- }).returning();
51002
- const [w] = await this.deps.db.select({ name: workspaces.name }).from(workspaces).where(eq(workspaces.id, data.workspaceId));
51003
- return { ...toTokenDTO(row, w.name), token };
52001
+ await this.access.workspace(actor, workspaceId);
52002
+ const rows = await this.deps.db.select().from(trash).where(eq(trash.workspaceId, workspaceId)).orderBy(desc(trash.deletedAt));
52003
+ return rows.map(toTrashEntryDTO);
51004
52004
  }
51005
- async revoke(actor, tokenId) {
52005
+ async load(actor, trashId) {
51006
52006
  this.access.requireUser(actor);
51007
- const [row] = await this.deps.db.update(apiTokens).set({ revokedAt: /* @__PURE__ */ new Date() }).where(and(eq(apiTokens.id, tokenId), eq(apiTokens.userId, actor.userId), isNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
51008
- if (!row) throw notFound("Token");
52007
+ const [entry] = await this.deps.db.select().from(trash).where(eq(trash.id, trashId));
52008
+ if (!entry) throw notFound("Trash entry");
52009
+ await this.access.workspace(actor, entry.workspaceId);
52010
+ return entry;
52011
+ }
52012
+ /** Puts the item back, with everything it held. If its place is gone, in the first one available. */
52013
+ async restore(actor, trashId) {
52014
+ const entry = await this.load(actor, trashId);
52015
+ const result = this.deps.db.transaction((tx) => {
52016
+ const rows = tx.select({ table: trashRows.tableName, data: trashRows.data }).from(trashRows).where(eq(trashRows.trashId, trashId)).orderBy(trashRows.id).all();
52017
+ const root = rows.find((r) => r.table === ROOT_TABLE[entry.kind]);
52018
+ if (!root) throw notFound("Trash entry");
52019
+ const placed = this.place(tx, entry.workspaceId, entry.kind, root.data, rows);
52020
+ const reinsert = new Reinsert(tx);
52021
+ for (const row of rows) {
52022
+ if (row.table === "card_page_links" && row.data.source === "mention") continue;
52023
+ if (!reinsert.insert(row) && row === root) throw restoreError("restore_place_gone", "It no longer fits anywhere it could go back to.");
52024
+ }
52025
+ rebuildMentions(tx, entry.workspaceId, reinsert.cards, reinsert.pages);
52026
+ const restored = this.restoredChange(tx, entry.kind, root.data, { trashId, movedTo: placed.movedTo });
52027
+ if (restored) this.history.record(tx, actor, entry.workspaceId, restored);
52028
+ tx.delete(trash).where(eq(trash.id, trashId)).run();
52029
+ return placed;
52030
+ });
52031
+ await this.activity.record(
52032
+ actor,
52033
+ entry.workspaceId,
52034
+ { action: "trash.restored", entityType: result.entityType, entityId: result.entityId, summary: entry.title, meta: { kind: entry.kind, ...result.movedTo ? { movedTo: result.movedTo } : {} } },
52035
+ result.event
52036
+ );
52037
+ return { kind: entry.kind, entityId: entry.entityId, movedTo: result.movedTo, path: result.path };
52038
+ }
52039
+ /**
52040
+ * Checks the item still has somewhere to go back to and points its row there. Cards,
52041
+ * columns, boards and pages whose place is gone go to the first one available; the
52042
+ * rest need theirs. Throws when there is none.
52043
+ */
52044
+ place(tx, workspaceId, kind, root, rows) {
52045
+ const exists2 = /* @__PURE__ */ __name((table, id3) => id3 != null && Boolean(tx.get(sql`SELECT 1 AS found FROM ${sql.identifier(table)} WHERE id = ${id3} LIMIT 1`)), "exists");
52046
+ const atEnd = /* @__PURE__ */ __name((table, scope) => {
52047
+ const keys = tx.all(sql`SELECT position FROM ${sql.identifier(table)} WHERE ${scope} ORDER BY position`).map((r) => r.position);
52048
+ return keyAtEnd(keys);
52049
+ }, "atEnd");
52050
+ const missing = /* @__PURE__ */ __name((table, id3, what) => {
52051
+ const holder = tx.get(
52052
+ sql`SELECT t.title FROM trash_rows r JOIN trash t ON t.id = r.trash_id WHERE r.table_name = ${table} AND json_extract(r.data, '$.id') = ${id3} LIMIT 1`
52053
+ );
52054
+ if (holder) return restoreError("restore_place_in_trash", `Restore \u201C${holder.title}\u201D first: the ${what} it belongs to is in the trash too.`, { title: holder.title });
52055
+ return restoreError("restore_place_gone", `The ${what} it belonged to no longer exists, and there is nowhere else to put it.`);
52056
+ }, "missing");
52057
+ const needs = /* @__PURE__ */ __name((table, id3, what) => {
52058
+ if (!exists2(table, id3)) throw missing(table, id3, what);
52059
+ }, "needs");
52060
+ const firstProject = /* @__PURE__ */ __name(() => tx.get(sql`SELECT id, name FROM projects WHERE workspace_id = ${workspaceId} ORDER BY position, id LIMIT 1`), "firstProject");
52061
+ const firstBoard = /* @__PURE__ */ __name(() => tx.get(
52062
+ sql`SELECT b.id, b.name, p.name AS project FROM boards b JOIN projects p ON p.id = b.project_id WHERE b.workspace_id = ${workspaceId} ORDER BY p.position, p.id, b.position, b.id LIMIT 1`
52063
+ ), "firstBoard");
52064
+ const boardName = /* @__PURE__ */ __name((boardId) => tx.get(sql`SELECT b.name, p.name AS project FROM boards b JOIN projects p ON p.id = b.project_id WHERE b.id = ${boardId}`), "boardName");
52065
+ const ofTable = /* @__PURE__ */ __name((table) => rows.filter((r) => r.table === table).map((r) => r.data), "ofTable");
52066
+ const event = /* @__PURE__ */ __name((e) => e, "event");
52067
+ let movedTo = null;
52068
+ switch (kind) {
52069
+ case "project":
52070
+ return { entityType: "project", entityId: String(root.id), movedTo, path: `p/${root.id}`, event: event({ projectId: String(root.id), structure: true }) };
52071
+ case "board": {
52072
+ if (!exists2("projects", root.project_id)) {
52073
+ const target = firstProject();
52074
+ if (!target) throw missing("projects", root.project_id, "project");
52075
+ root.project_id = target.id;
52076
+ root.position = atEnd("boards", sql`project_id = ${target.id}`);
52077
+ movedTo = target.name;
52078
+ }
52079
+ return { entityType: "board", entityId: String(root.id), movedTo, path: `b/${root.id}`, event: event({ boardId: String(root.id), projectId: String(root.project_id), structure: true }) };
52080
+ }
52081
+ case "column": {
52082
+ if (!exists2("boards", root.board_id)) {
52083
+ const target = firstBoard();
52084
+ if (!target) throw missing("boards", root.board_id, "board");
52085
+ root.board_id = target.id;
52086
+ root.position = atEnd("board_columns", sql`board_id = ${target.id}`);
52087
+ for (const card of ofTable("cards")) card.board_id = target.id;
52088
+ movedTo = [target.project, target.name].join(SEPARATOR);
52089
+ }
52090
+ return { entityType: "column", entityId: String(root.id), movedTo, path: `b/${root.board_id}`, event: event({ boardId: String(root.board_id), structure: true }) };
52091
+ }
52092
+ case "card": {
52093
+ const column = tx.get(sql`SELECT board_id, name FROM board_columns WHERE id = ${root.column_id}`);
52094
+ if (column && column.board_id !== root.board_id) {
52095
+ const board = boardName(column.board_id);
52096
+ root.board_id = column.board_id;
52097
+ root.position = atEnd("cards", sql`column_id = ${root.column_id}`);
52098
+ movedTo = [board.project, board.name, column.name].join(SEPARATOR);
52099
+ } else if (!column) {
52100
+ const first = /* @__PURE__ */ __name((scope) => tx.get(
52101
+ sql`SELECT c.id, c.name, b.id AS board_id, b.name AS board, p.name AS project FROM board_columns c JOIN boards b ON b.id = c.board_id JOIN projects p ON p.id = b.project_id WHERE ${scope} ORDER BY p.position, p.id, b.position, b.id, c.position, c.id LIMIT 1`
52102
+ ), "first");
52103
+ const target = first(sql`c.board_id = ${root.board_id}`) ?? first(sql`c.workspace_id = ${workspaceId}`);
52104
+ if (!target) throw missing("board_columns", root.column_id, "column");
52105
+ root.board_id = target.board_id;
52106
+ root.column_id = target.id;
52107
+ root.position = atEnd("cards", sql`column_id = ${target.id}`);
52108
+ movedTo = [target.project, target.board, target.name].join(SEPARATOR);
52109
+ }
52110
+ return { entityType: "card", entityId: String(root.id), movedTo, path: `b/${root.board_id}`, event: event({ boardId: String(root.board_id), cardId: String(root.id), structure: true }) };
52111
+ }
52112
+ case "page": {
52113
+ const parent = root.parent_id != null ? tx.get(sql`SELECT project_id FROM pages WHERE id = ${root.parent_id}`) : void 0;
52114
+ const projectName = /* @__PURE__ */ __name((id3) => tx.get(sql`SELECT name FROM projects WHERE id = ${id3}`)?.name ?? null, "projectName");
52115
+ if (parent) {
52116
+ if (parent.project_id !== root.project_id) {
52117
+ for (const page of ofTable("pages")) page.project_id = parent.project_id;
52118
+ root.position = atEnd("pages", sql`parent_id = ${root.parent_id}`);
52119
+ movedTo = projectName(parent.project_id);
52120
+ }
52121
+ } else if (!exists2("projects", root.project_id)) {
52122
+ const target = firstProject();
52123
+ if (!target) throw missing("projects", root.project_id, "project");
52124
+ for (const page of ofTable("pages")) page.project_id = target.id;
52125
+ root.parent_id = null;
52126
+ root.position = atEnd("pages", sql`project_id = ${target.id} AND parent_id IS NULL`);
52127
+ movedTo = target.name;
52128
+ } else if (root.parent_id != null) {
52129
+ root.parent_id = null;
52130
+ root.position = atEnd("pages", sql`project_id = ${root.project_id} AND parent_id IS NULL`);
52131
+ movedTo = projectName(root.project_id);
52132
+ }
52133
+ return { entityType: "page", entityId: String(root.id), movedTo, path: `d/${root.id}`, event: event({ pageId: String(root.id), projectId: String(root.project_id), structure: true }) };
52134
+ }
52135
+ case "attachment": {
52136
+ if (root.card_id != null) {
52137
+ needs("cards", root.card_id, "card");
52138
+ const boardId = tx.get(sql`SELECT board_id FROM cards WHERE id = ${root.card_id}`).board_id;
52139
+ return { entityType: "card", entityId: String(root.card_id), movedTo, path: `b/${boardId}`, event: event({ boardId, cardId: String(root.card_id) }) };
52140
+ }
52141
+ needs("pages", root.page_id, "page");
52142
+ return { entityType: "page", entityId: String(root.page_id), movedTo, path: `d/${root.page_id}`, event: event({ pageId: String(root.page_id) }) };
52143
+ }
52144
+ case "label":
52145
+ needs("boards", root.board_id, "board");
52146
+ return { entityType: "label", entityId: String(root.id), movedTo, path: `b/${root.board_id}`, event: event({ boardId: String(root.board_id) }) };
52147
+ case "checklist":
52148
+ case "checklist_item": {
52149
+ const cardId = kind === "checklist" ? (needs("cards", root.card_id, "card"), root.card_id) : (needs("checklists", root.checklist_id, "checklist"), tx.get(sql`SELECT card_id FROM checklists WHERE id = ${root.checklist_id}`).card_id);
52150
+ const boardId = tx.get(sql`SELECT board_id FROM cards WHERE id = ${cardId}`).board_id;
52151
+ return { entityType: "card", entityId: String(cardId), movedTo, path: `b/${boardId}`, event: event({ boardId, cardId: String(cardId) }) };
52152
+ }
52153
+ case "link": {
52154
+ needs("cards", root.card_id, "card");
52155
+ needs("pages", root.page_id, "page");
52156
+ const boardId = tx.get(sql`SELECT board_id FROM cards WHERE id = ${root.card_id}`).board_id;
52157
+ return { entityType: "card", entityId: String(root.card_id), movedTo, path: `b/${boardId}`, event: event({ boardId, cardId: String(root.card_id), pageId: String(root.page_id) }) };
52158
+ }
52159
+ }
52160
+ }
52161
+ /** Deletes an entry for good, with the files of its attachments. */
52162
+ async purge(actor, trashId) {
52163
+ const entry = await this.load(actor, trashId);
52164
+ if (!await this.erase(trashId)) throw notFound("Trash entry");
52165
+ await this.activity.record(actor, entry.workspaceId, {
52166
+ action: "trash.purged",
52167
+ entityType: purgedEntityType(entry.kind),
52168
+ entityId: entry.entityId,
52169
+ summary: entry.title,
52170
+ meta: { kind: entry.kind }
52171
+ });
51009
52172
  }
51010
- /** Resolves a bearer token into an agent actor, or null if invalid, expired, revoked or orphaned. */
51011
- async authenticate(token) {
51012
- if (!token.startsWith(TOKEN_PREFIX) || token.length > 100) return null;
51013
- const now = /* @__PURE__ */ new Date();
51014
- const [row] = await this.deps.db.select({ token: apiTokens }).from(apiTokens).innerJoin(
51015
- workspaceMembers,
51016
- and(eq(workspaceMembers.workspaceId, apiTokens.workspaceId), eq(workspaceMembers.userId, apiTokens.userId))
51017
- ).where(
51018
- and(
51019
- eq(apiTokens.tokenHash, sha2562(token)),
51020
- isNull(apiTokens.revokedAt),
51021
- or(isNull(apiTokens.expiresAt), gt(apiTokens.expiresAt, now))
51022
- )
51023
- ).limit(1);
51024
- return row ? this.actorFor(row.token, now) : null;
52173
+ /** Deletes for good what has been in the trash for TRASH_DAYS. Runs hourly. */
52174
+ async purgeExpired(now = /* @__PURE__ */ new Date()) {
52175
+ const expired = await this.deps.db.select({ id: trash.id }).from(trash).where(lte(trash.expiresAt, now));
52176
+ let erased = 0;
52177
+ for (const { id: id3 } of expired) if (await this.erase(id3)) erased++;
52178
+ return erased;
52179
+ }
52180
+ /**
52181
+ * Deletes an entry and then the files of its attachments. Reading the files and deleting
52182
+ * the entry happen in one transaction, so a restore running at the same time either
52183
+ * comes first (and nothing is erased) or finds nothing to restore. Returns whether this
52184
+ * call erased it.
52185
+ */
52186
+ async erase(trashId) {
52187
+ const files = this.deps.db.transaction((tx) => {
52188
+ const keys = tx.select({ key: trashRows.storageKey }).from(trashRows).where(and(eq(trashRows.trashId, trashId), isNotNull(trashRows.storageKey))).all();
52189
+ this.history.forget(tx, trashId);
52190
+ const erased = tx.delete(trash).where(eq(trash.id, trashId)).returning({ id: trash.id }).all();
52191
+ return erased.length > 0 ? keys : null;
52192
+ });
52193
+ if (!files) return false;
52194
+ for (const { key } of files) await this.deps.storage.delete(key).catch(() => {
52195
+ });
52196
+ return true;
51025
52197
  }
51026
- /** The agent acting with a valid token (or OAuth grant); records when it was last used. */
51027
- async actorFor(t, now) {
51028
- const last = this.lastTouched.get(t.id) ?? 0;
51029
- if (now.getTime() - last > 6e4) {
51030
- this.lastTouched.set(t.id, now.getTime());
51031
- await this.deps.db.update(apiTokens).set({ lastUsedAt: now }).where(eq(apiTokens.id, t.id));
52198
+ };
52199
+ function rebuildMentions(tx, workspaceId, cards2, pages2) {
52200
+ if (cards2.size === 0 && pages2.size === 0) return;
52201
+ const exists2 = /* @__PURE__ */ new Map();
52202
+ const isCard = /* @__PURE__ */ __name((id3) => {
52203
+ let found = exists2.get(id3);
52204
+ if (found === void 0) {
52205
+ found = Boolean(tx.get(sql`SELECT 1 AS found FROM cards WHERE id = ${id3} AND workspace_id = ${workspaceId}`));
52206
+ exists2.set(id3, found);
52207
+ }
52208
+ return found;
52209
+ }, "isCard");
52210
+ const mentioning = tx.all(sql`SELECT id, content FROM pages WHERE workspace_id = ${workspaceId} AND content LIKE '%/card/%'`);
52211
+ for (const page of mentioning) {
52212
+ if (cards2.size === 0 && !pages2.has(page.id)) continue;
52213
+ for (const cardId of extractReferences(page.content).cards.slice(0, 200)) {
52214
+ if (!pages2.has(page.id) && !cards2.has(cardId)) continue;
52215
+ if (!isCard(cardId)) continue;
52216
+ tx.run(sql`INSERT OR IGNORE INTO card_page_links (card_id, page_id, workspace_id, source, created_at) VALUES (${cardId}, ${page.id}, ${workspaceId}, 'mention', ${Date.now()})`);
52217
+ }
52218
+ }
52219
+ }
52220
+ __name(rebuildMentions, "rebuildMentions");
52221
+ var AUTHORS = /* @__PURE__ */ new Set(["users", "api_tokens"]);
52222
+ var SHAPES = new Map(
52223
+ ORDER.map((table) => {
52224
+ const definition = TABLES[table];
52225
+ const references = getTableConfig(definition).foreignKeys.map((fk) => {
52226
+ const reference = fk.reference();
52227
+ return { column: reference.columns[0].name, table: getTableConfig(reference.foreignTable).name, target: reference.foreignColumns[0].name };
52228
+ });
52229
+ return [table, { columns: Object.values(getTableColumns(definition)).map((c) => c.name), references }];
52230
+ })
52231
+ );
52232
+ var Reinsert = class {
52233
+ constructor(tx) {
52234
+ this.tx = tx;
52235
+ }
52236
+ tx;
52237
+ static {
52238
+ __name(this, "Reinsert");
52239
+ }
52240
+ known = /* @__PURE__ */ new Map();
52241
+ /** The cards and pages put back, for rebuilding their mentions. */
52242
+ cards = /* @__PURE__ */ new Set();
52243
+ pages = /* @__PURE__ */ new Set();
52244
+ exists(table, column, value) {
52245
+ const key = `${table} ${column} ${String(value)}`;
52246
+ let found = this.known.get(key);
52247
+ if (found === void 0) {
52248
+ found = Boolean(this.tx.get(sql`SELECT 1 AS found FROM ${sql.identifier(table)} WHERE ${sql.identifier(column)} = ${value} LIMIT 1`));
52249
+ this.known.set(key, found);
52250
+ }
52251
+ return found;
52252
+ }
52253
+ /** Returns whether the row went back in. */
52254
+ insert({ table, data }) {
52255
+ const shape = SHAPES.get(table);
52256
+ for (const reference of shape.references) {
52257
+ const value = data[reference.column];
52258
+ if (value == null || this.exists(reference.table, reference.target, value)) continue;
52259
+ if (!AUTHORS.has(reference.table)) return false;
52260
+ data[reference.column] = null;
52261
+ }
52262
+ if (table === "card_labels" && !this.tx.get(sql`SELECT 1 AS found FROM labels l JOIN cards c ON c.board_id = l.board_id WHERE l.id = ${data.label_id} AND c.id = ${data.card_id}`)) {
52263
+ return false;
51032
52264
  }
52265
+ const names = shape.columns.filter((name2) => name2 in data);
52266
+ this.tx.run(
52267
+ sql`INSERT OR IGNORE INTO ${sql.identifier(table)} (${sql.join(
52268
+ names.map((n) => sql.identifier(n)),
52269
+ sql`, `
52270
+ )}) VALUES (${sql.join(
52271
+ names.map((n) => sql`${data[n]}`),
52272
+ sql`, `
52273
+ )})`
52274
+ );
52275
+ if (data.id != null) this.known.set(`${table} id ${String(data.id)}`, true);
52276
+ if (table === "cards") this.cards.add(String(data.id));
52277
+ if (table === "pages") this.pages.add(String(data.id));
52278
+ return true;
52279
+ }
52280
+ };
52281
+ var purgedEntityType = /* @__PURE__ */ __name((kind) => ["project", "board", "column", "card", "label", "page"].find((k) => k === kind) ?? "card", "purgedEntityType");
52282
+ function toTrashEntryDTO(row) {
52283
+ return {
52284
+ id: row.id,
52285
+ kind: row.kind,
52286
+ entityId: row.entityId,
52287
+ title: row.title,
52288
+ location: row.location,
52289
+ contents: row.contents,
52290
+ bytes: row.bytes,
52291
+ deletedBy: {
52292
+ kind: row.actorKind,
52293
+ id: (row.actorKind === "agent" ? row.actorTokenId : row.actorUserId) ?? "",
52294
+ name: row.actorName
52295
+ },
52296
+ deletedAt: row.deletedAt.toISOString(),
52297
+ expiresAt: row.expiresAt.toISOString()
52298
+ };
52299
+ }
52300
+ __name(toTrashEntryDTO, "toTrashEntryDTO");
52301
+
52302
+ // src/services/undo.ts
52303
+ var AT_END = 1e5;
52304
+ var MAX_CHANGES = 500;
52305
+ var CHUNK = 90;
52306
+ var LIGHT_COLUMNS = (() => {
52307
+ const body = inArray(history.kind, [...HISTORY_BODY_KINDS]);
52308
+ return {
52309
+ ...getTableColumns(history),
52310
+ before: sql`CASE WHEN ${body} THEN NULL ELSE ${history.before} END`,
52311
+ after: sql`CASE WHEN ${body} THEN NULL ELSE ${history.after} END`,
52312
+ seq: sql`rowid`
52313
+ };
52314
+ })();
52315
+ var State = class {
52316
+ static {
52317
+ __name(this, "State");
52318
+ }
52319
+ values = /* @__PURE__ */ new Map();
52320
+ exists = /* @__PURE__ */ new Map();
52321
+ /** For long texts: the change whose text before will be the text by then (compared in SQLite, never loaded). */
52322
+ bodies = /* @__PURE__ */ new Map();
52323
+ /** Trash entries the newer changes bring back, with everything they hold. */
52324
+ restoring = /* @__PURE__ */ new Set();
52325
+ };
52326
+ var fieldKey = /* @__PURE__ */ __name((row) => `${row.entityId}|${row.kind}|${row.subjectId ?? ""}`, "fieldKey");
52327
+ var sameSet = /* @__PURE__ */ __name((a, b) => Array.isArray(a) && Array.isArray(b) ? a.length === b.length && [...a].sort().every((v, i) => v === [...b].sort()[i]) : a === b, "sameSet");
52328
+ var columnOf = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) && "columnId" in value ? value.columnId : null, "columnOf");
52329
+ var fileAt = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) && "pageId" in value ? `${value.cardId ?? ""}|${value.pageId ?? ""}` : null, "fileAt");
52330
+ var parentOf = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) && "projectId" in value ? value.parentId : void 0, "parentOf");
52331
+ var UndoService = class {
52332
+ constructor(deps, access, services) {
52333
+ this.deps = deps;
52334
+ this.access = access;
52335
+ this.services = services;
52336
+ }
52337
+ deps;
52338
+ access;
52339
+ services;
52340
+ static {
52341
+ __name(this, "UndoService");
52342
+ }
52343
+ async undo(actor, input2) {
52344
+ this.access.requireUser(actor);
52345
+ const data = parse3(undoInput, input2);
52346
+ const rows = await this.entries(actor, data.ids, data.since);
52347
+ const undoing = new Set(rows.map((r) => r.id));
52348
+ const state = new State();
52349
+ const plan = rows.map((row) => this.planItem(row, this.check(row, undoing, state), undoing, state));
52350
+ if (data.dryRun || data.conflicts === "ask" && plan.some((p) => p.status === "conflict")) return { applied: false, plan, undone: 0, skipped: 0, failed: 0 };
52351
+ let undone = 0;
52352
+ let skipped = 0;
52353
+ let failed = 0;
52354
+ for (const [i, row] of rows.entries()) {
52355
+ const check3 = this.check(row, undoing, new State());
52356
+ const item = this.planItem(row, check3, undoing);
52357
+ plan[i] = item;
52358
+ if (check3.status === "unchanged") continue;
52359
+ if (check3.status === "impossible") {
52360
+ failed++;
52361
+ continue;
52362
+ }
52363
+ if (check3.status === "conflict" && data.conflicts !== "force") {
52364
+ skipped++;
52365
+ continue;
52366
+ }
52367
+ try {
52368
+ await this.apply(row, { ...actor, note: { undoOf: row.id } });
52369
+ undone++;
52370
+ } catch (error62) {
52371
+ if (!(error62 instanceof AppError)) throw error62;
52372
+ plan[i] = { ...item, status: "impossible", reason: "refused" };
52373
+ failed++;
52374
+ }
52375
+ }
52376
+ return { applied: true, plan, undone, skipped, failed };
52377
+ }
52378
+ /** Puts a page's content or a card's description back as it was after a change, as a new change. */
52379
+ async restoreVersion(actor, entryId) {
52380
+ this.access.requireUser(actor);
52381
+ const [row] = await this.deps.db.select().from(history).where(eq(history.id, entryId));
52382
+ if (!row) throw notFound("History entry");
52383
+ await this.access.workspace(actor, row.workspaceId);
52384
+ if (!HISTORY_BODY_KINDS.has(row.kind)) throw badRequest("Only versions of a content or a description can be restored");
52385
+ const text2 = row.after ?? "";
52386
+ const by = { ...actor, note: { restoredFrom: row.id } };
52387
+ if (row.kind === "page.content") {
52388
+ const page = this.deps.db.select({ version: pages.version }).from(pages).where(eq(pages.id, row.entityId)).get();
52389
+ if (!page) throw notFound("Page");
52390
+ await this.services.pages.update(by, row.entityId, { content: text2, baseVersion: page.version });
52391
+ } else {
52392
+ const card = this.deps.db.select({ version: cards.version }).from(cards).where(eq(cards.id, row.entityId)).get();
52393
+ if (!card) throw notFound("Card");
52394
+ await this.services.cards.update(by, row.entityId, { description: text2, baseVersion: card.version });
52395
+ }
52396
+ }
52397
+ rows(where) {
52398
+ return this.deps.db.select(LIGHT_COLUMNS).from(history).where(where).orderBy(desc(history.updatedAt), desc(sql`rowid`));
52399
+ }
52400
+ /** The changes to undo, newest first: those asked for, or all their author did from one on. */
52401
+ async entries(actor, ids, since) {
52402
+ let rows = [];
52403
+ if (ids) {
52404
+ for (let i = 0; i < ids.length; i += CHUNK) rows.push(...await this.rows(inArray(history.id, ids.slice(i, i + CHUNK))));
52405
+ if (rows.length !== new Set(ids).size) throw notFound("History entry");
52406
+ rows.sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime() || b.seq - a.seq);
52407
+ } else {
52408
+ const [anchor2] = await this.rows(eq(history.id, since));
52409
+ if (!anchor2) throw notFound("History entry");
52410
+ const author = anchor2.actorKind === "agent" ? eq(history.actorTokenId, anchor2.actorTokenId ?? "") : and(eq(history.actorKind, "user"), eq(history.actorUserId, anchor2.actorUserId ?? ""));
52411
+ const from = or(gt(history.updatedAt, anchor2.updatedAt), and(eq(history.updatedAt, anchor2.updatedAt), sql`rowid >= ${anchor2.seq}`));
52412
+ rows = await this.rows(and(eq(history.workspaceId, anchor2.workspaceId), author, from)).limit(MAX_CHANGES);
52413
+ }
52414
+ for (const workspaceId of new Set(rows.map((r) => r.workspaceId))) await this.access.workspace(actor, workspaceId);
52415
+ return rows;
52416
+ }
52417
+ planItem(row, check3, undoing, state) {
52418
+ const table = row.entityType === "page" ? pages : cards;
52419
+ const trashed = typeof row.meta.trashId === "string" ? [row.meta.trashId, ...state?.restoring ?? []] : [...state?.restoring ?? []];
52420
+ const title = this.deps.db.select({ title: table.title }).from(table).where(eq(table.id, row.entityId)).get()?.title ?? trashed.map((trashId) => this.kept(trashId, row.entityId)?.title).find((t) => typeof t === "string");
51033
52421
  return {
51034
- kind: "agent",
51035
- userId: t.userId,
51036
- tokenId: t.id,
51037
- name: t.name,
51038
- workspaceId: t.workspaceId,
51039
- scopes: new Set(t.scopes.filter((s) => SCOPES.includes(s)))
52422
+ entryId: row.id,
52423
+ kind: row.kind,
52424
+ entityType: row.entityType,
52425
+ entityId: row.entityId,
52426
+ entityTitle: title ?? (typeof row.meta.title === "string" ? row.meta.title : ""),
52427
+ status: check3.status,
52428
+ ...check3.reason ? { reason: check3.reason } : {},
52429
+ ...check3.status === "conflict" ? { changedBy: check3.by !== void 0 ? check3.by : this.changedSince(row, check3.exists === void 0, undoing, state?.restoring), current: check3.current ?? null } : {}
51040
52430
  };
51041
52431
  }
52432
+ /**
52433
+ * What counts as changing the same thing after this change: the same value for a value; for
52434
+ * a page or a card made or brought back, anything on it; for a checklist, anything on it and
52435
+ * its items; for an item, a file or a link, anything on that. What is under it counts whether
52436
+ * it is there or coming back with the trash entries in `restoring`.
52437
+ */
52438
+ sameThing(row, isValue, restoring) {
52439
+ if (isValue) return and(eq(history.entityId, row.entityId), eq(history.kind, row.kind), row.subjectId ? eq(history.subjectId, row.subjectId) : void 0);
52440
+ const kept = /* @__PURE__ */ __name((table) => sql`SELECT data FROM trash_rows WHERE table_name = ${table} AND trash_id IN (SELECT value FROM json_each(${JSON.stringify([...restoring])}))`, "kept");
52441
+ if (row.entityType === "page" && !row.subjectId) {
52442
+ const tree = sql`WITH RECURSIVE tree(id, depth) AS (
52443
+ SELECT ${row.entityId}, 0
52444
+ UNION ALL SELECT p.id, t.depth + 1 FROM pages p JOIN tree t ON p.parent_id = t.id WHERE t.depth < ${MAX_TREE_DEPTH}
52445
+ UNION ALL SELECT json_extract(k.data, '$.id'), t.depth + 1 FROM (${kept("pages")}) k JOIN tree t ON json_extract(k.data, '$.parent_id') = t.id WHERE t.depth < ${MAX_TREE_DEPTH}
52446
+ ) SELECT id FROM tree`;
52447
+ return or(sql`${history.entityId} IN (${tree})`, sql`${history.subjectId} IN (${tree})`);
52448
+ }
52449
+ if (!row.subjectId) return eq(history.entityId, row.entityId);
52450
+ if (row.kind.startsWith("attachment.")) return eq(history.subjectId, row.subjectId);
52451
+ if (!row.kind.startsWith("checklist.")) return and(eq(history.entityId, row.entityId), eq(history.subjectId, row.subjectId));
52452
+ return and(
52453
+ eq(history.entityId, row.entityId),
52454
+ or(
52455
+ eq(history.subjectId, row.subjectId),
52456
+ sql`${history.subjectId} IN (SELECT id FROM checklist_items WHERE checklist_id = ${row.subjectId})`,
52457
+ sql`${history.subjectId} IN (SELECT json_extract(k.data, '$.id') FROM (${kept("checklist_items")}) k WHERE json_extract(k.data, '$.checklist_id') = ${row.subjectId})`
52458
+ )
52459
+ );
52460
+ }
52461
+ /**
52462
+ * The changes made to the same thing after this one, newest first, besides those undone with
52463
+ * it. For something made or brought back, only someone else's count: its author's own later
52464
+ * changes go with it.
52465
+ */
52466
+ laterChanges(row, isValue, undoing, restoring = /* @__PURE__ */ new Set()) {
52467
+ const author = /* @__PURE__ */ __name((r) => r.kind === "agent" ? `agent:${r.tokenId}` : `user:${r.userId}`, "author");
52468
+ const own2 = author({ kind: row.actorKind, userId: row.actorUserId, tokenId: row.actorTokenId });
52469
+ return this.deps.db.select({ id: history.id, kind: history.actorKind, userId: history.actorUserId, tokenId: history.actorTokenId, name: history.actorName, meta: history.meta }).from(history).where(and(this.sameThing(row, isValue, restoring), or(gt(history.updatedAt, row.updatedAt), and(eq(history.updatedAt, row.updatedAt), sql`rowid > ${row.seq}`)))).orderBy(desc(history.updatedAt), desc(sql`rowid`)).all().filter((r) => !undoing.has(r.id) && !undoing.has(String(r.meta.undoOf)) && (isValue || author(r) !== own2));
52470
+ }
52471
+ /** Who changed it after this change, besides the changes being undone with it. */
52472
+ changedSince(row, isValue, undoing, restoring) {
52473
+ const [later] = this.laterChanges(row, isValue, undoing, restoring);
52474
+ return later ? { kind: later.kind, id: (later.kind === "agent" ? later.tokenId : later.userId) ?? "", name: later.name } : null;
52475
+ }
52476
+ /** What a trash entry keeps of one thing it holds, if it holds it. */
52477
+ kept(trashId, id3) {
52478
+ const found = this.deps.db.select({ data: trashRows.data }).from(trashRows).where(and(eq(trashRows.trashId, trashId), sql`json_extract(${trashRows.data}, '$.id') = ${id3}`)).get();
52479
+ return found?.data;
52480
+ }
52481
+ /**
52482
+ * The rows of `table` that the trash entries being brought back keep, where `column` is
52483
+ * `value`: what they will be once back. Without their long texts, compared where they are kept.
52484
+ */
52485
+ keptRows(restoring, table, column, value) {
52486
+ const ids = [...restoring];
52487
+ const found = [];
52488
+ for (let i = 0; i < ids.length; i += CHUNK) {
52489
+ const rows = this.deps.db.select({ trashId: trashRows.trashId, data: sql`json_remove(${trashRows.data}, '$.content', '$.description')` }).from(trashRows).where(and(inArray(trashRows.trashId, ids.slice(i, i + CHUNK)), eq(trashRows.tableName, table), sql`json_extract(${trashRows.data}, ${`$.${column}`}) = ${value}`)).all();
52490
+ found.push(...rows.map((r) => ({ trashId: r.trashId, data: JSON.parse(r.data) })));
52491
+ }
52492
+ return found;
52493
+ }
52494
+ trashed(row) {
52495
+ const id3 = typeof row.meta.trashId === "string" ? row.meta.trashId : null;
52496
+ return id3 !== null && Boolean(this.deps.db.select({ id: trash.id }).from(trash).where(eq(trash.id, id3)).get());
52497
+ }
52498
+ /** How undoing this change stands, against `state`: now, and after the newer changes being undone. */
52499
+ check(row, undoing, state) {
52500
+ const db = this.deps.db;
52501
+ const kind = row.kind;
52502
+ const before = decode3(kind, row.before);
52503
+ const after = decode3(kind, row.after);
52504
+ const subject = row.subjectId ?? "";
52505
+ const one = /* @__PURE__ */ __name((query) => query.get(), "one");
52506
+ const has = /* @__PURE__ */ __name((key, real2) => state.exists.get(key) ?? real2(), "has");
52507
+ const returning = /* @__PURE__ */ __name((id3) => [...state.restoring].some((trashId) => this.kept(trashId, id3) !== void 0), "returning");
52508
+ const kept = /* @__PURE__ */ __name((table, id3, column = "id") => this.keptRows(state.restoring, table, column, id3), "kept");
52509
+ const text2 = /* @__PURE__ */ __name((v) => v == null ? null : String(v), "text");
52510
+ const date5 = /* @__PURE__ */ __name((v) => v == null ? null : new Date(Number(v)), "date");
52511
+ const entityKey = `${row.entityType}:${row.entityId}`;
52512
+ const entityExists = has(
52513
+ entityKey,
52514
+ () => Boolean(row.entityType === "page" ? one(db.select({ id: pages.id }).from(pages).where(eq(pages.id, row.entityId))) : one(db.select({ id: cards.id }).from(cards).where(eq(cards.id, row.entityId)))) || returning(row.entityId)
52515
+ );
52516
+ const bringBack = /* @__PURE__ */ __name((key, real2) => {
52517
+ if (has(key, real2)) return { status: "unchanged" };
52518
+ if (!this.trashed(row)) return { status: "impossible", reason: "trash_gone" };
52519
+ state.exists.set(key, true);
52520
+ state.restoring.add(String(row.meta.trashId));
52521
+ return { status: "ready", exists: true };
52522
+ }, "bringBack");
52523
+ const takeAway = /* @__PURE__ */ __name((key, real2) => {
52524
+ if (!has(key, real2)) return { status: "unchanged" };
52525
+ const status = this.laterChanges(row, false, undoing, state.restoring).length ? "conflict" : "ready";
52526
+ if (status === "ready") state.exists.set(key, false);
52527
+ return { status, exists: false };
52528
+ }, "takeAway");
52529
+ const value = /* @__PURE__ */ __name((current, same = (a, b) => a === b, place, key = fieldKey(row), back = before) => {
52530
+ const now = state.values.has(key) ? state.values.get(key) : current;
52531
+ if (same(now, back)) return { status: "unchanged" };
52532
+ if (place && !place()) return { status: "impossible", reason: "place_gone" };
52533
+ const status = same(now, after) ? "ready" : "conflict";
52534
+ if (status === "ready") state.values.set(key, back);
52535
+ return { status, current: now };
52536
+ }, "value");
52537
+ const body = /* @__PURE__ */ __name((table, column, trashId) => {
52538
+ const key = fieldKey(row);
52539
+ const ref = state.bodies.get(key);
52540
+ const now = ref ? sql`(SELECT "before" FROM history WHERE id = ${ref})` : trashId ? sql`(SELECT json_extract(data, ${`$.${column}`}) FROM trash_rows WHERE trash_id = ${trashId} AND table_name = ${table} AND json_extract(data, '$.id') = ${row.entityId})` : sql`(SELECT ${sql.identifier(column)} FROM ${sql.identifier(table)} WHERE id = ${row.entityId})`;
52541
+ const found = db.get(
52542
+ sql`SELECT ${now} IS h."before" AS isBefore, ${now} IS h."after" AS isAfter, substr(${now}, 1, 200) AS current FROM history h WHERE h.id = ${row.id}`
52543
+ );
52544
+ if (!found) return { status: "impossible", reason: "gone" };
52545
+ if (found.isBefore) return { status: "unchanged" };
52546
+ if (!found.isAfter) return { status: "conflict", current: found.current };
52547
+ state.bodies.set(key, row.id);
52548
+ return { status: "ready" };
52549
+ }, "body");
52550
+ switch (kind) {
52551
+ case "page.deleted":
52552
+ return bringBack(entityKey, () => entityExists);
52553
+ case "card.deleted":
52554
+ return bringBack(entityKey, () => entityExists);
52555
+ case "page.created":
52556
+ case "page.restored":
52557
+ case "card.created":
52558
+ case "card.restored":
52559
+ return takeAway(entityKey, () => entityExists);
52560
+ }
52561
+ const file2 = /* @__PURE__ */ __name(() => Boolean(one(db.select({ id: attachments.id }).from(attachments).where(eq(attachments.id, subject)))), "file");
52562
+ if (kind === "attachment.created" || kind === "attachment.restored") return takeAway(`attachment:${subject}`, () => file2() || returning(subject));
52563
+ if (!entityExists) return { status: "impossible", reason: "gone" };
52564
+ switch (kind) {
52565
+ case "attachment.deleted":
52566
+ return bringBack(`attachment:${subject}`, file2);
52567
+ case "attachment.moved": {
52568
+ const keptFile = /* @__PURE__ */ __name(() => kept("attachments", subject).map(({ data }) => ({ cardId: text2(data.card_id), pageId: text2(data.page_id), workspaceId: String(data.workspace_id) }))[0], "keptFile");
52569
+ const at = one(db.select({ cardId: attachments.cardId, pageId: attachments.pageId, workspaceId: attachments.workspaceId }).from(attachments).where(eq(attachments.id, subject))) ?? keptFile();
52570
+ if (!at) return { status: "impossible", reason: "gone" };
52571
+ const key = `attachment-place:${subject}`;
52572
+ const back = before;
52573
+ const there = /* @__PURE__ */ __name(() => {
52574
+ const table = back?.pageId ? pages : cards;
52575
+ const id3 = back?.pageId ?? back?.cardId ?? "";
52576
+ return Boolean(one(db.select({ id: table.id }).from(table).where(and(eq(table.id, id3), eq(table.workspaceId, at.workspaceId))))) || kept(back?.pageId ? "pages" : "cards", id3).some(({ data }) => data.workspace_id === at.workspaceId);
52577
+ }, "there");
52578
+ return value({ cardId: at.cardId, pageId: at.pageId }, (a, b) => fileAt(a) === fileAt(b), there, key);
52579
+ }
52580
+ }
52581
+ if (row.entityType === "page") {
52582
+ const live = one(db.select({ title: pages.title, icon: pages.icon, parentId: pages.parentId, projectId: pages.projectId }).from(pages).where(eq(pages.id, row.entityId)));
52583
+ const [back] = live ? [] : kept("pages", row.entityId);
52584
+ const page = live ?? (back && { title: String(back.data.title), icon: text2(back.data.icon), parentId: text2(back.data.parent_id), projectId: String(back.data.project_id) });
52585
+ if (!page) return { status: "impossible", reason: "gone" };
52586
+ switch (kind) {
52587
+ case "page.title":
52588
+ return value(page.title);
52589
+ case "page.icon":
52590
+ return value(page.icon);
52591
+ case "page.content":
52592
+ return body("pages", "content", back?.trashId);
52593
+ case "page.moved": {
52594
+ const target = parentOf(before);
52595
+ return value(
52596
+ { projectId: page.projectId, parentId: page.parentId },
52597
+ (a, b) => parentOf(a) === parentOf(b),
52598
+ // Its old parent: there, or coming back from the trash first.
52599
+ () => target === null || Boolean(one(db.select({ id: pages.id }).from(pages).where(and(eq(pages.id, target ?? ""), eq(pages.projectId, page.projectId))))) || kept("pages", target ?? "").some(({ data }) => data.project_id === page.projectId)
52600
+ );
52601
+ }
52602
+ }
52603
+ } else {
52604
+ const live = one(
52605
+ db.select({ id: cards.id, title: cards.title, boardId: cards.boardId, columnId: cards.columnId, workspaceId: cards.workspaceId, dueAt: cards.dueAt, archivedAt: cards.archivedAt }).from(cards).where(eq(cards.id, row.entityId))
52606
+ );
52607
+ const [back] = live ? [] : kept("cards", row.entityId);
52608
+ const card = live ?? (back && {
52609
+ id: row.entityId,
52610
+ title: String(back.data.title),
52611
+ boardId: String(back.data.board_id),
52612
+ columnId: String(back.data.column_id),
52613
+ workspaceId: String(back.data.workspace_id),
52614
+ dueAt: date5(back.data.due_at),
52615
+ archivedAt: date5(back.data.archived_at)
52616
+ });
52617
+ if (!card) return { status: "impossible", reason: "gone" };
52618
+ const labelIds = /* @__PURE__ */ __name(() => {
52619
+ if (live) return db.select({ id: cardLabels.labelId }).from(cardLabels).where(eq(cardLabels.cardId, card.id)).all().map((l) => l.id);
52620
+ const ids = kept("card_labels", card.id, "card_id").map(({ data }) => String(data.label_id));
52621
+ if (!ids.length) return [];
52622
+ return db.select({ id: labels.id }).from(labels).where(and(eq(labels.boardId, card.boardId), sql`${labels.id} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`)).all().map((l) => l.id);
52623
+ }, "labelIds");
52624
+ switch (kind) {
52625
+ case "card.title":
52626
+ return value(card.title);
52627
+ case "card.description":
52628
+ return body("cards", "description", back?.trashId);
52629
+ case "card.due":
52630
+ return value(card.dueAt?.toISOString() ?? null);
52631
+ case "card.labels": {
52632
+ const wanted = Array.isArray(before) ? before.map(String) : [];
52633
+ const place = state.values.get(`${card.id}|card.moved|`);
52634
+ const board = place?.boardId ?? card.boardId;
52635
+ const still = wanted.length ? db.select({ id: labels.id }).from(labels).where(and(eq(labels.boardId, board), sql`${labels.id} IN (SELECT value FROM json_each(${JSON.stringify(wanted)}))`)).all().map((l) => l.id) : [];
52636
+ return value(labelIds(), sameSet, void 0, fieldKey(row), wanted.filter((id3) => still.includes(id3)));
52637
+ }
52638
+ case "card.moved": {
52639
+ const target = columnOf(before);
52640
+ const key = fieldKey(row);
52641
+ const had = state.values.get(key);
52642
+ const place = state.values.has(key) ? had : { boardId: card.boardId, columnId: card.columnId };
52643
+ const check3 = value(
52644
+ { boardId: card.boardId, columnId: card.columnId },
52645
+ (a, b) => columnOf(a) === columnOf(b),
52646
+ // Its old column, on its board or another one of the same workspace.
52647
+ () => Boolean(one(db.select({ id: columns.id }).from(columns).where(and(eq(columns.id, target ?? ""), eq(columns.workspaceId, card.workspaceId)))))
52648
+ );
52649
+ const labelKey = `${card.id}|card.labels|`;
52650
+ const labelsNow = state.values.has(labelKey) ? state.values.get(labelKey) : labelIds();
52651
+ const toOtherBoard = before?.boardId !== void 0 && before.boardId !== place.boardId;
52652
+ if (check3.status !== "ready" || !toOtherBoard) return check3;
52653
+ if (!Array.isArray(labelsNow) || labelsNow.length === 0) {
52654
+ const lost = Array.isArray(row.meta.labelIds) ? row.meta.labelIds : [];
52655
+ const back2 = lost.length ? db.select({ id: labels.id }).from(labels).where(and(eq(labels.boardId, before.boardId), inArray(labels.id, lost))).all().map((l) => l.id) : [];
52656
+ state.values.set(labelKey, back2);
52657
+ return check3;
52658
+ }
52659
+ if (had === void 0) state.values.delete(key);
52660
+ else state.values.set(key, had);
52661
+ const [who] = this.laterChanges({ ...row, kind: "card.labels", subjectId: null }, true, undoing);
52662
+ return { status: "conflict", current: labelsNow, by: who ? { kind: who.kind, id: (who.kind === "agent" ? who.tokenId : who.userId) ?? "", name: who.name } : null };
52663
+ }
52664
+ case "card.archived":
52665
+ return value(card.archivedAt !== null);
52666
+ case "card.linked":
52667
+ case "card.unlinked": {
52668
+ const link = /* @__PURE__ */ __name(() => Boolean(one(db.select({ id: cardPageLinks.pageId }).from(cardPageLinks).where(and(eq(cardPageLinks.cardId, card.id), eq(cardPageLinks.pageId, subject), eq(cardPageLinks.source, "manual"))))) || kept("card_page_links", card.id, "card_id").some(({ data }) => data.page_id === subject && data.source === "manual"), "link");
52669
+ return kind === "card.linked" ? takeAway(`link:${card.id}:${subject}`, link) : bringBack(`link:${card.id}:${subject}`, link);
52670
+ }
52671
+ }
52672
+ const checklist = /* @__PURE__ */ __name(() => one(db.select({ title: checklists.title }).from(checklists).where(and(eq(checklists.id, subject), eq(checklists.cardId, card.id)))) ?? kept("checklists", subject).filter(({ data }) => data.card_id === card.id).map(({ data }) => ({ title: String(data.title) }))[0], "checklist");
52673
+ const item = /* @__PURE__ */ __name(() => one(db.select({ text: checklistItems.text, done: checklistItems.done }).from(checklistItems).where(eq(checklistItems.id, subject))) ?? kept("checklist_items", subject).map(({ data }) => ({ text: String(data.text), done: Boolean(data.done) }))[0], "item");
52674
+ switch (kind) {
52675
+ case "checklist.created":
52676
+ case "checklist.restored":
52677
+ return takeAway(`checklist:${subject}`, () => Boolean(checklist()) || returning(subject));
52678
+ case "checklist.deleted":
52679
+ return bringBack(`checklist:${subject}`, () => Boolean(checklist()));
52680
+ case "checklist.title": {
52681
+ const list = checklist();
52682
+ return list ? value(list.title) : { status: "impossible", reason: "gone" };
52683
+ }
52684
+ case "item.created":
52685
+ case "item.restored":
52686
+ return takeAway(`item:${subject}`, () => Boolean(item()) || returning(subject));
52687
+ case "item.deleted":
52688
+ return bringBack(`item:${subject}`, () => Boolean(item()));
52689
+ case "item.text":
52690
+ case "item.done": {
52691
+ const it = item();
52692
+ return it ? value(kind === "item.text" ? it.text : it.done) : { status: "impossible", reason: "gone" };
52693
+ }
52694
+ }
52695
+ }
52696
+ return { status: "impossible", reason: "refused" };
52697
+ }
52698
+ /** Undoes one change, through the services that make changes, so it is checked and recorded as any other. */
52699
+ async apply(row, actor) {
52700
+ const { cards: cardService, pages: pageService, attachments: attachmentService, trash: trashService } = this.services;
52701
+ const kind = row.kind;
52702
+ const raw2 = HISTORY_BODY_KINDS.has(kind) ? this.deps.db.get(sql`SELECT "before" AS text FROM history WHERE id = ${row.id}`)?.text ?? null : row.before;
52703
+ const before = decode3(kind, raw2);
52704
+ const subject = row.subjectId ?? "";
52705
+ const trashId = typeof row.meta.trashId === "string" ? row.meta.trashId : "";
52706
+ const db = this.deps.db;
52707
+ switch (kind) {
52708
+ case "page.title":
52709
+ return pageService.update(actor, row.entityId, { title: String(before ?? "") });
52710
+ case "page.icon":
52711
+ return pageService.update(actor, row.entityId, { icon: before === null ? null : String(before) });
52712
+ case "page.content": {
52713
+ const page = db.select({ version: pages.version }).from(pages).where(eq(pages.id, row.entityId)).get();
52714
+ return pageService.update(actor, row.entityId, { content: String(before ?? ""), baseVersion: page?.version });
52715
+ }
52716
+ case "page.moved":
52717
+ return pageService.move(actor, row.entityId, { parentId: parentOf(before) ?? null, index: AT_END });
52718
+ case "page.created":
52719
+ case "page.restored":
52720
+ return pageService.remove(actor, row.entityId);
52721
+ case "card.title":
52722
+ return cardService.update(actor, row.entityId, { title: String(before ?? "") });
52723
+ case "card.description": {
52724
+ const card = db.select({ version: cards.version }).from(cards).where(eq(cards.id, row.entityId)).get();
52725
+ return cardService.update(actor, row.entityId, { description: String(before ?? ""), baseVersion: card?.version });
52726
+ }
52727
+ case "card.due":
52728
+ return cardService.update(actor, row.entityId, { dueAt: before === null ? null : String(before) });
52729
+ case "card.labels": {
52730
+ const card = db.select({ boardId: cards.boardId }).from(cards).where(eq(cards.id, row.entityId)).get();
52731
+ const wanted = Array.isArray(before) ? before : [];
52732
+ const existing = wanted.length && card ? db.select({ id: labels.id }).from(labels).where(and(eq(labels.boardId, card.boardId), inArray(labels.id, wanted))).all().map((l) => l.id) : [];
52733
+ return cardService.update(actor, row.entityId, { labelIds: wanted.filter((id3) => existing.includes(id3)) });
52734
+ }
52735
+ case "card.moved": {
52736
+ await cardService.move(actor, row.entityId, { columnId: columnOf(before), index: AT_END });
52737
+ const lost = Array.isArray(row.meta.labelIds) ? row.meta.labelIds : [];
52738
+ const card = lost.length ? db.select({ boardId: cards.boardId }).from(cards).where(eq(cards.id, row.entityId)).get() : void 0;
52739
+ if (!card) return;
52740
+ const back = db.select({ id: labels.id }).from(labels).where(and(eq(labels.boardId, card.boardId), inArray(labels.id, lost))).all().map((l) => l.id);
52741
+ const has = db.select({ id: cardLabels.labelId }).from(cardLabels).where(eq(cardLabels.cardId, row.entityId)).all().map((l) => l.id);
52742
+ if (back.some((id3) => !has.includes(id3))) await cardService.update(actor, row.entityId, { labelIds: [.../* @__PURE__ */ new Set([...has, ...back])] });
52743
+ return;
52744
+ }
52745
+ case "card.archived":
52746
+ return cardService.setArchived(actor, row.entityId, before === true);
52747
+ case "card.created":
52748
+ case "card.restored":
52749
+ return cardService.remove(actor, row.entityId);
52750
+ case "card.linked":
52751
+ return cardService.unlinkPage(actor, row.entityId, subject);
52752
+ case "checklist.created":
52753
+ case "checklist.restored":
52754
+ return cardService.removeChecklist(actor, subject);
52755
+ case "checklist.title":
52756
+ return cardService.updateChecklist(actor, subject, { title: String(before ?? "") });
52757
+ case "item.created":
52758
+ case "item.restored":
52759
+ return cardService.removeItem(actor, subject);
52760
+ case "item.text":
52761
+ return cardService.updateItem(actor, subject, { text: String(before ?? "") });
52762
+ case "item.done":
52763
+ return cardService.updateItem(actor, subject, { done: before === true });
52764
+ case "attachment.created":
52765
+ case "attachment.restored":
52766
+ return attachmentService.remove(actor, subject);
52767
+ case "attachment.moved": {
52768
+ const back = before;
52769
+ return attachmentService.move(actor, subject, back?.pageId ? { pageId: back.pageId } : { cardId: back?.cardId ?? "" });
52770
+ }
52771
+ case "page.deleted":
52772
+ case "card.deleted":
52773
+ case "card.unlinked":
52774
+ case "checklist.deleted":
52775
+ case "item.deleted":
52776
+ case "attachment.deleted":
52777
+ return trashService.restore(actor, trashId);
52778
+ }
52779
+ }
51042
52780
  };
51043
52781
 
51044
52782
  // src/version.ts
51045
- var VERSION = "1.0.2";
52783
+ var VERSION = "1.1.0";
51046
52784
 
51047
52785
  // src/services/updates.ts
51048
52786
  var REGISTRY = "https://registry.npmjs.org/create-orqevio/latest";
@@ -51221,16 +52959,18 @@ var toProjectDTO = /* @__PURE__ */ __name((p) => ({
51221
52959
  updatedAt: p.updatedAt.toISOString()
51222
52960
  }), "toProjectDTO");
51223
52961
  var WorkspaceService = class {
51224
- constructor(deps, access, activity2, cards2) {
52962
+ constructor(deps, access, activity2, cards2, trash2) {
51225
52963
  this.deps = deps;
51226
52964
  this.access = access;
51227
52965
  this.activity = activity2;
51228
52966
  this.cards = cards2;
52967
+ this.trash = trash2;
51229
52968
  }
51230
52969
  deps;
51231
52970
  access;
51232
52971
  activity;
51233
52972
  cards;
52973
+ trash;
51234
52974
  static {
51235
52975
  __name(this, "WorkspaceService");
51236
52976
  }
@@ -51369,19 +53109,20 @@ var WorkspaceService = class {
51369
53109
  );
51370
53110
  return toProjectDTO(p);
51371
53111
  }
53112
+ /** To the trash, with its boards and pages: agents need write access to both, and to be allowed to delete and move. */
51372
53113
  async removeProject(actor, projectId) {
51373
- this.access.requireUser(actor);
53114
+ this.access.requireScope(actor, "organize");
53115
+ this.access.requireScope(actor, "tasks:write");
53116
+ this.access.requireScope(actor, "docs:write");
51374
53117
  const current = await this.getProject(actor, projectId);
51375
- this.deps.db.transaction((tx) => {
51376
- deletePageTrees(tx, sql`${pages.projectId} = ${projectId} AND ${pages.parentId} IS NULL`);
51377
- tx.delete(projects).where(eq(projects.id, projectId)).run();
51378
- });
53118
+ const trashId = this.deps.db.transaction((tx) => this.trash.move(tx, actor, current.workspaceId, { kind: "project", id: projectId }));
51379
53119
  await this.activity.record(
51380
53120
  actor,
51381
53121
  current.workspaceId,
51382
53122
  { action: "project.deleted", entityType: "project", entityId: projectId, summary: current.name },
51383
53123
  { projectId, structure: true }
51384
53124
  );
53125
+ return trashId;
51385
53126
  }
51386
53127
  };
51387
53128
 
@@ -51389,17 +53130,23 @@ var WorkspaceService = class {
51389
53130
  function createServices(deps) {
51390
53131
  const access = new Access(deps);
51391
53132
  const activity2 = new ActivityService(deps);
51392
- const cards2 = new CardService(deps, access, activity2);
51393
- const workspaces2 = new WorkspaceService(deps, access, activity2, cards2);
53133
+ const history2 = new HistoryService(deps, access);
53134
+ const trash2 = new TrashService(deps, access, activity2, history2);
53135
+ const cards2 = new CardService(deps, access, activity2, trash2, history2);
53136
+ const workspaces2 = new WorkspaceService(deps, access, activity2, cards2, trash2);
51394
53137
  const tokens = new TokenService(deps, access);
51395
- const attachments2 = new AttachmentService(deps, access, activity2);
53138
+ const attachments2 = new AttachmentService(deps, access, activity2, trash2, history2);
53139
+ const pages2 = new PageService(deps, access, activity2, trash2, history2);
51396
53140
  return {
51397
53141
  access,
51398
53142
  activity: activity2,
53143
+ history: history2,
53144
+ trash: trash2,
51399
53145
  cards: cards2,
51400
53146
  workspaces: workspaces2,
51401
- boards: new BoardService(deps, access, activity2, cards2),
51402
- pages: new PageService(deps, access, activity2),
53147
+ boards: new BoardService(deps, access, activity2, cards2, trash2),
53148
+ pages: pages2,
53149
+ undo: new UndoService(deps, access, { cards: cards2, pages: pages2, attachments: attachments2, trash: trash2 }),
51403
53150
  search: new SearchService(deps, access),
51404
53151
  attachments: attachments2,
51405
53152
  tokens,
@@ -51463,6 +53210,20 @@ var migrations_gen_default = {
51463
53210
  "when": 1794775030557,
51464
53211
  "tag": "0006_card_version",
51465
53212
  "breakpoints": true
53213
+ },
53214
+ {
53215
+ "idx": 7,
53216
+ "version": "6",
53217
+ "when": 1794869113841,
53218
+ "tag": "0007_trash",
53219
+ "breakpoints": true
53220
+ },
53221
+ {
53222
+ "idx": 8,
53223
+ "version": "6",
53224
+ "when": 1794875822892,
53225
+ "tag": "0008_history",
53226
+ "breakpoints": true
51466
53227
  }
51467
53228
  ]
51468
53229
  },
@@ -51473,7 +53234,9 @@ var migrations_gen_default = {
51473
53234
  "m0003": "CREATE TABLE `oauth_codes` (\n `id` text PRIMARY KEY NOT NULL,\n `user_id` text NOT NULL,\n `workspace_id` text NOT NULL,\n `client_id` text NOT NULL,\n `client_name` text NOT NULL,\n `redirect_uri` text NOT NULL,\n `code_challenge` text NOT NULL,\n `scopes` text NOT NULL,\n `expires_at` integer NOT NULL,\n `used_at` integer,\n `token_id` text,\n FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`token_id`) REFERENCES `api_tokens`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nCREATE INDEX `oauth_codes_expires_idx` ON `oauth_codes` (`expires_at`);--> statement-breakpoint\nCREATE TABLE `oauth_tokens` (\n `id` text PRIMARY KEY NOT NULL,\n `token_id` text NOT NULL,\n `kind` text NOT NULL,\n `expires_at` integer NOT NULL,\n `rotated_at` integer,\n `created_at` integer NOT NULL,\n FOREIGN KEY (`token_id`) REFERENCES `api_tokens`(`id`) ON UPDATE no action ON DELETE cascade\n);\n--> statement-breakpoint\nCREATE INDEX `oauth_tokens_grant_idx` ON `oauth_tokens` (`token_id`);--> statement-breakpoint\nALTER TABLE `api_tokens` ADD `oauth_client_id` text;--> statement-breakpoint\nALTER TABLE `api_tokens` ADD `oauth_redirect_uri` text;",
51474
53235
  "m0004": "ALTER TABLE `users` ADD `locale` text DEFAULT 'en' NOT NULL;",
51475
53236
  "m0005": "ALTER TABLE `oauth_codes` ADD `replace_previous` integer DEFAULT false NOT NULL;",
51476
- "m0006": "ALTER TABLE `cards` ADD `version` integer DEFAULT 1 NOT NULL;"
53237
+ "m0006": "ALTER TABLE `cards` ADD `version` integer DEFAULT 1 NOT NULL;",
53238
+ "m0007": "CREATE TABLE `trash` (\n `id` text PRIMARY KEY NOT NULL,\n `workspace_id` text NOT NULL,\n `kind` text NOT NULL,\n `entity_id` text NOT NULL,\n `title` text NOT NULL,\n `location` text DEFAULT '' NOT NULL,\n `contents` text NOT NULL,\n `bytes` integer DEFAULT 0 NOT NULL,\n `actor_kind` text NOT NULL,\n `actor_user_id` text,\n `actor_token_id` text,\n `actor_name` text NOT NULL,\n `deleted_at` integer NOT NULL,\n `expires_at` integer NOT NULL,\n FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,\n FOREIGN KEY (`actor_token_id`) REFERENCES `api_tokens`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nCREATE INDEX `trash_workspace_idx` ON `trash` (`workspace_id`,`deleted_at`);--> statement-breakpoint\nCREATE INDEX `trash_expires_idx` ON `trash` (`expires_at`);--> statement-breakpoint\nCREATE TABLE `trash_rows` (\n `id` integer PRIMARY KEY NOT NULL,\n `trash_id` text NOT NULL,\n `table_name` text NOT NULL,\n `data` text NOT NULL,\n `storage_key` text,\n FOREIGN KEY (`trash_id`) REFERENCES `trash`(`id`) ON UPDATE no action ON DELETE cascade\n);\n--> statement-breakpoint\nCREATE INDEX `trash_rows_trash_idx` ON `trash_rows` (`trash_id`,`id`);--> statement-breakpoint\nCREATE INDEX `trash_rows_storage_idx` ON `trash_rows` (`storage_key`);",
53239
+ "m0008": "CREATE TABLE `history` (\n `id` text PRIMARY KEY NOT NULL,\n `workspace_id` text NOT NULL,\n `entity_type` text NOT NULL,\n `entity_id` text NOT NULL,\n `kind` text NOT NULL,\n `subject_id` text,\n `before` text,\n `after` text,\n `meta` text NOT NULL,\n `actor_kind` text NOT NULL,\n `actor_user_id` text,\n `actor_token_id` text,\n `actor_name` text NOT NULL,\n `batch_id` text NOT NULL,\n `created_at` integer NOT NULL,\n `updated_at` integer NOT NULL,\n FOREIGN KEY (`workspace_id`) REFERENCES `workspaces`(`id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`actor_user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE set null,\n FOREIGN KEY (`actor_token_id`) REFERENCES `api_tokens`(`id`) ON UPDATE no action ON DELETE set null\n);\n--> statement-breakpoint\nCREATE INDEX `history_entity_idx` ON `history` (`entity_id`,`updated_at`);--> statement-breakpoint\nCREATE INDEX `history_subject_idx` ON `history` (`subject_id`);--> statement-breakpoint\nCREATE INDEX `history_user_idx` ON `history` (`actor_user_id`,`updated_at`);--> statement-breakpoint\nCREATE INDEX `history_token_idx` ON `history` (`actor_token_id`,`updated_at`);--> statement-breakpoint\nCREATE INDEX `history_updated_idx` ON `history` (`updated_at`);--> statement-breakpoint\nCREATE INDEX `history_batch_idx` ON `history` (`batch_id`);"
51477
53240
  }
51478
53241
  };
51479
53242
 
@@ -51625,9 +53388,11 @@ var OrqevioCopy = class extends DurableObject {
51625
53388
  })
51626
53389
  );
51627
53390
  }
51628
- /** Hourly: removes attachments left in R2 without a database row. */
53391
+ /** Hourly: deletes for good what has been in the trash or the history for 30 days, then files in R2 that nothing uses. */
51629
53392
  async alarm() {
51630
53393
  try {
53394
+ await this.services.trash.purgeExpired().catch((error62) => console.error("[trash] purge failed", error62));
53395
+ await this.services.history.purgeExpired().catch((error62) => console.error("[history] purge failed", error62));
51631
53396
  await this.services.attachments.sweepOrphans();
51632
53397
  } finally {
51633
53398
  await this.ctx.storage.setAlarm(Date.now() + SWEEP_EVERY_MS);