@macro-inc/sdk 0.0.1

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 (296) hide show
  1. package/README.md +177 -0
  2. package/dist/chunk-5HAKQN23.js +1263 -0
  3. package/dist/chunk-77EI4LSQ.js +2492 -0
  4. package/dist/chunk-CTKR64MY.js +1436 -0
  5. package/dist/chunk-JXIQT5TH.js +1467 -0
  6. package/dist/chunk-P4DTO6VD.js +830 -0
  7. package/dist/chunk-PAAFJYGO.js +967 -0
  8. package/dist/chunk-QNUS5BC5.js +913 -0
  9. package/dist/chunk-SGAHIERJ.js +1235 -0
  10. package/dist/chunk-V45LUJDI.js +838 -0
  11. package/dist/chunk-YRUXFEZM.js +1044 -0
  12. package/dist/generated/agent-harness/client/client.gen.d.ts +2 -0
  13. package/dist/generated/agent-harness/client/index.d.ts +10 -0
  14. package/dist/generated/agent-harness/client/types.gen.d.ts +120 -0
  15. package/dist/generated/agent-harness/client/utils.gen.d.ts +37 -0
  16. package/dist/generated/agent-harness/client.gen.d.ts +12 -0
  17. package/dist/generated/agent-harness/core/auth.gen.d.ts +25 -0
  18. package/dist/generated/agent-harness/core/bodySerializer.gen.d.ts +25 -0
  19. package/dist/generated/agent-harness/core/params.gen.d.ts +43 -0
  20. package/dist/generated/agent-harness/core/pathSerializer.gen.d.ts +33 -0
  21. package/dist/generated/agent-harness/core/queryKeySerializer.gen.d.ts +18 -0
  22. package/dist/generated/agent-harness/core/serverSentEvents.gen.d.ts +71 -0
  23. package/dist/generated/agent-harness/core/types.gen.d.ts +83 -0
  24. package/dist/generated/agent-harness/core/utils.gen.d.ts +19 -0
  25. package/dist/generated/agent-harness/index.d.ts +2 -0
  26. package/dist/generated/agent-harness/index.js +6 -0
  27. package/dist/generated/agent-harness/sdk.gen.d.ts +84 -0
  28. package/dist/generated/agent-harness/types.gen.d.ts +539 -0
  29. package/dist/generated/auth/client/client.gen.d.ts +2 -0
  30. package/dist/generated/auth/client/index.d.ts +10 -0
  31. package/dist/generated/auth/client/types.gen.d.ts +120 -0
  32. package/dist/generated/auth/client/utils.gen.d.ts +37 -0
  33. package/dist/generated/auth/client.gen.d.ts +12 -0
  34. package/dist/generated/auth/core/auth.gen.d.ts +25 -0
  35. package/dist/generated/auth/core/bodySerializer.gen.d.ts +25 -0
  36. package/dist/generated/auth/core/params.gen.d.ts +43 -0
  37. package/dist/generated/auth/core/pathSerializer.gen.d.ts +33 -0
  38. package/dist/generated/auth/core/queryKeySerializer.gen.d.ts +18 -0
  39. package/dist/generated/auth/core/serverSentEvents.gen.d.ts +71 -0
  40. package/dist/generated/auth/core/types.gen.d.ts +83 -0
  41. package/dist/generated/auth/core/utils.gen.d.ts +19 -0
  42. package/dist/generated/auth/index.d.ts +2 -0
  43. package/dist/generated/auth/index.js +6 -0
  44. package/dist/generated/auth/sdk.gen.d.ts +383 -0
  45. package/dist/generated/auth/types.gen.d.ts +2175 -0
  46. package/dist/generated/cognition/client/client.gen.d.ts +2 -0
  47. package/dist/generated/cognition/client/index.d.ts +10 -0
  48. package/dist/generated/cognition/client/types.gen.d.ts +120 -0
  49. package/dist/generated/cognition/client/utils.gen.d.ts +37 -0
  50. package/dist/generated/cognition/client.gen.d.ts +12 -0
  51. package/dist/generated/cognition/core/auth.gen.d.ts +25 -0
  52. package/dist/generated/cognition/core/bodySerializer.gen.d.ts +25 -0
  53. package/dist/generated/cognition/core/params.gen.d.ts +43 -0
  54. package/dist/generated/cognition/core/pathSerializer.gen.d.ts +33 -0
  55. package/dist/generated/cognition/core/queryKeySerializer.gen.d.ts +18 -0
  56. package/dist/generated/cognition/core/serverSentEvents.gen.d.ts +71 -0
  57. package/dist/generated/cognition/core/types.gen.d.ts +83 -0
  58. package/dist/generated/cognition/core/utils.gen.d.ts +19 -0
  59. package/dist/generated/cognition/index.d.ts +2 -0
  60. package/dist/generated/cognition/index.js +6 -0
  61. package/dist/generated/cognition/sdk.gen.d.ts +224 -0
  62. package/dist/generated/cognition/types.gen.d.ts +2484 -0
  63. package/dist/generated/connection/client/client.gen.d.ts +2 -0
  64. package/dist/generated/connection/client/index.d.ts +10 -0
  65. package/dist/generated/connection/client/types.gen.d.ts +120 -0
  66. package/dist/generated/connection/client/utils.gen.d.ts +37 -0
  67. package/dist/generated/connection/client.gen.d.ts +12 -0
  68. package/dist/generated/connection/core/auth.gen.d.ts +25 -0
  69. package/dist/generated/connection/core/bodySerializer.gen.d.ts +25 -0
  70. package/dist/generated/connection/core/params.gen.d.ts +43 -0
  71. package/dist/generated/connection/core/pathSerializer.gen.d.ts +33 -0
  72. package/dist/generated/connection/core/queryKeySerializer.gen.d.ts +18 -0
  73. package/dist/generated/connection/core/serverSentEvents.gen.d.ts +71 -0
  74. package/dist/generated/connection/core/types.gen.d.ts +83 -0
  75. package/dist/generated/connection/core/utils.gen.d.ts +19 -0
  76. package/dist/generated/connection/index.d.ts +2 -0
  77. package/dist/generated/connection/index.js +839 -0
  78. package/dist/generated/connection/sdk.gen.d.ts +38 -0
  79. package/dist/generated/connection/types.gen.d.ts +235 -0
  80. package/dist/generated/contacts/client/client.gen.d.ts +2 -0
  81. package/dist/generated/contacts/client/index.d.ts +10 -0
  82. package/dist/generated/contacts/client/types.gen.d.ts +120 -0
  83. package/dist/generated/contacts/client/utils.gen.d.ts +37 -0
  84. package/dist/generated/contacts/client.gen.d.ts +12 -0
  85. package/dist/generated/contacts/core/auth.gen.d.ts +25 -0
  86. package/dist/generated/contacts/core/bodySerializer.gen.d.ts +25 -0
  87. package/dist/generated/contacts/core/params.gen.d.ts +43 -0
  88. package/dist/generated/contacts/core/pathSerializer.gen.d.ts +33 -0
  89. package/dist/generated/contacts/core/queryKeySerializer.gen.d.ts +18 -0
  90. package/dist/generated/contacts/core/serverSentEvents.gen.d.ts +71 -0
  91. package/dist/generated/contacts/core/types.gen.d.ts +83 -0
  92. package/dist/generated/contacts/core/utils.gen.d.ts +19 -0
  93. package/dist/generated/contacts/index.d.ts +2 -0
  94. package/dist/generated/contacts/index.js +6 -0
  95. package/dist/generated/contacts/sdk.gen.d.ts +43 -0
  96. package/dist/generated/contacts/types.gen.d.ts +52 -0
  97. package/dist/generated/email/client/client.gen.d.ts +2 -0
  98. package/dist/generated/email/client/index.d.ts +10 -0
  99. package/dist/generated/email/client/types.gen.d.ts +120 -0
  100. package/dist/generated/email/client/utils.gen.d.ts +37 -0
  101. package/dist/generated/email/client.gen.d.ts +12 -0
  102. package/dist/generated/email/core/auth.gen.d.ts +25 -0
  103. package/dist/generated/email/core/bodySerializer.gen.d.ts +25 -0
  104. package/dist/generated/email/core/params.gen.d.ts +43 -0
  105. package/dist/generated/email/core/pathSerializer.gen.d.ts +33 -0
  106. package/dist/generated/email/core/queryKeySerializer.gen.d.ts +18 -0
  107. package/dist/generated/email/core/serverSentEvents.gen.d.ts +71 -0
  108. package/dist/generated/email/core/types.gen.d.ts +83 -0
  109. package/dist/generated/email/core/utils.gen.d.ts +19 -0
  110. package/dist/generated/email/index.d.ts +2 -0
  111. package/dist/generated/email/index.js +6 -0
  112. package/dist/generated/email/sdk.gen.d.ts +254 -0
  113. package/dist/generated/email/types.gen.d.ts +2614 -0
  114. package/dist/generated/notification/client/client.gen.d.ts +2 -0
  115. package/dist/generated/notification/client/index.d.ts +10 -0
  116. package/dist/generated/notification/client/types.gen.d.ts +120 -0
  117. package/dist/generated/notification/client/utils.gen.d.ts +37 -0
  118. package/dist/generated/notification/client.gen.d.ts +12 -0
  119. package/dist/generated/notification/core/auth.gen.d.ts +25 -0
  120. package/dist/generated/notification/core/bodySerializer.gen.d.ts +25 -0
  121. package/dist/generated/notification/core/params.gen.d.ts +43 -0
  122. package/dist/generated/notification/core/pathSerializer.gen.d.ts +33 -0
  123. package/dist/generated/notification/core/queryKeySerializer.gen.d.ts +18 -0
  124. package/dist/generated/notification/core/serverSentEvents.gen.d.ts +71 -0
  125. package/dist/generated/notification/core/types.gen.d.ts +83 -0
  126. package/dist/generated/notification/core/utils.gen.d.ts +19 -0
  127. package/dist/generated/notification/index.d.ts +2 -0
  128. package/dist/generated/notification/index.js +6 -0
  129. package/dist/generated/notification/sdk.gen.d.ts +118 -0
  130. package/dist/generated/notification/types.gen.d.ts +1352 -0
  131. package/dist/generated/properties/client/client.gen.d.ts +2 -0
  132. package/dist/generated/properties/client/index.d.ts +10 -0
  133. package/dist/generated/properties/client/types.gen.d.ts +120 -0
  134. package/dist/generated/properties/client/utils.gen.d.ts +37 -0
  135. package/dist/generated/properties/client.gen.d.ts +12 -0
  136. package/dist/generated/properties/core/auth.gen.d.ts +25 -0
  137. package/dist/generated/properties/core/bodySerializer.gen.d.ts +25 -0
  138. package/dist/generated/properties/core/params.gen.d.ts +43 -0
  139. package/dist/generated/properties/core/pathSerializer.gen.d.ts +33 -0
  140. package/dist/generated/properties/core/queryKeySerializer.gen.d.ts +18 -0
  141. package/dist/generated/properties/core/serverSentEvents.gen.d.ts +71 -0
  142. package/dist/generated/properties/core/types.gen.d.ts +83 -0
  143. package/dist/generated/properties/core/utils.gen.d.ts +19 -0
  144. package/dist/generated/properties/index.d.ts +2 -0
  145. package/dist/generated/properties/index.js +6 -0
  146. package/dist/generated/properties/sdk.gen.d.ts +158 -0
  147. package/dist/generated/properties/types.gen.d.ts +1288 -0
  148. package/dist/generated/scheduled-action/client/client.gen.d.ts +2 -0
  149. package/dist/generated/scheduled-action/client/index.d.ts +10 -0
  150. package/dist/generated/scheduled-action/client/types.gen.d.ts +120 -0
  151. package/dist/generated/scheduled-action/client/utils.gen.d.ts +37 -0
  152. package/dist/generated/scheduled-action/client.gen.d.ts +12 -0
  153. package/dist/generated/scheduled-action/core/auth.gen.d.ts +25 -0
  154. package/dist/generated/scheduled-action/core/bodySerializer.gen.d.ts +25 -0
  155. package/dist/generated/scheduled-action/core/params.gen.d.ts +43 -0
  156. package/dist/generated/scheduled-action/core/pathSerializer.gen.d.ts +33 -0
  157. package/dist/generated/scheduled-action/core/queryKeySerializer.gen.d.ts +18 -0
  158. package/dist/generated/scheduled-action/core/serverSentEvents.gen.d.ts +71 -0
  159. package/dist/generated/scheduled-action/core/types.gen.d.ts +83 -0
  160. package/dist/generated/scheduled-action/core/utils.gen.d.ts +19 -0
  161. package/dist/generated/scheduled-action/index.d.ts +2 -0
  162. package/dist/generated/scheduled-action/index.js +845 -0
  163. package/dist/generated/scheduled-action/sdk.gen.d.ts +42 -0
  164. package/dist/generated/scheduled-action/types.gen.d.ts +241 -0
  165. package/dist/generated/search/client/client.gen.d.ts +2 -0
  166. package/dist/generated/search/client/index.d.ts +10 -0
  167. package/dist/generated/search/client/types.gen.d.ts +120 -0
  168. package/dist/generated/search/client/utils.gen.d.ts +37 -0
  169. package/dist/generated/search/client.gen.d.ts +12 -0
  170. package/dist/generated/search/core/auth.gen.d.ts +25 -0
  171. package/dist/generated/search/core/bodySerializer.gen.d.ts +25 -0
  172. package/dist/generated/search/core/params.gen.d.ts +43 -0
  173. package/dist/generated/search/core/pathSerializer.gen.d.ts +33 -0
  174. package/dist/generated/search/core/queryKeySerializer.gen.d.ts +18 -0
  175. package/dist/generated/search/core/serverSentEvents.gen.d.ts +71 -0
  176. package/dist/generated/search/core/types.gen.d.ts +83 -0
  177. package/dist/generated/search/core/utils.gen.d.ts +19 -0
  178. package/dist/generated/search/index.d.ts +2 -0
  179. package/dist/generated/search/index.js +6 -0
  180. package/dist/generated/search/sdk.gen.d.ts +44 -0
  181. package/dist/generated/search/types.gen.d.ts +2194 -0
  182. package/dist/generated/static-files/client/client.gen.d.ts +2 -0
  183. package/dist/generated/static-files/client/index.d.ts +10 -0
  184. package/dist/generated/static-files/client/types.gen.d.ts +120 -0
  185. package/dist/generated/static-files/client/utils.gen.d.ts +37 -0
  186. package/dist/generated/static-files/client.gen.d.ts +12 -0
  187. package/dist/generated/static-files/core/auth.gen.d.ts +25 -0
  188. package/dist/generated/static-files/core/bodySerializer.gen.d.ts +25 -0
  189. package/dist/generated/static-files/core/params.gen.d.ts +43 -0
  190. package/dist/generated/static-files/core/pathSerializer.gen.d.ts +33 -0
  191. package/dist/generated/static-files/core/queryKeySerializer.gen.d.ts +18 -0
  192. package/dist/generated/static-files/core/serverSentEvents.gen.d.ts +71 -0
  193. package/dist/generated/static-files/core/types.gen.d.ts +83 -0
  194. package/dist/generated/static-files/core/utils.gen.d.ts +19 -0
  195. package/dist/generated/static-files/index.d.ts +2 -0
  196. package/dist/generated/static-files/index.js +842 -0
  197. package/dist/generated/static-files/sdk.gen.d.ts +43 -0
  198. package/dist/generated/static-files/types.gen.d.ts +214 -0
  199. package/dist/generated/storage/client/client.gen.d.ts +2 -0
  200. package/dist/generated/storage/client/index.d.ts +10 -0
  201. package/dist/generated/storage/client/types.gen.d.ts +120 -0
  202. package/dist/generated/storage/client/utils.gen.d.ts +37 -0
  203. package/dist/generated/storage/client.gen.d.ts +12 -0
  204. package/dist/generated/storage/core/auth.gen.d.ts +25 -0
  205. package/dist/generated/storage/core/bodySerializer.gen.d.ts +25 -0
  206. package/dist/generated/storage/core/params.gen.d.ts +43 -0
  207. package/dist/generated/storage/core/pathSerializer.gen.d.ts +33 -0
  208. package/dist/generated/storage/core/queryKeySerializer.gen.d.ts +18 -0
  209. package/dist/generated/storage/core/serverSentEvents.gen.d.ts +71 -0
  210. package/dist/generated/storage/core/types.gen.d.ts +83 -0
  211. package/dist/generated/storage/core/utils.gen.d.ts +19 -0
  212. package/dist/generated/storage/index.d.ts +2 -0
  213. package/dist/generated/storage/index.js +6 -0
  214. package/dist/generated/storage/sdk.gen.d.ts +858 -0
  215. package/dist/generated/storage/types.gen.d.ts +12105 -0
  216. package/dist/generated/unfurl/client/client.gen.d.ts +2 -0
  217. package/dist/generated/unfurl/client/index.d.ts +10 -0
  218. package/dist/generated/unfurl/client/types.gen.d.ts +120 -0
  219. package/dist/generated/unfurl/client/utils.gen.d.ts +37 -0
  220. package/dist/generated/unfurl/client.gen.d.ts +12 -0
  221. package/dist/generated/unfurl/core/auth.gen.d.ts +25 -0
  222. package/dist/generated/unfurl/core/bodySerializer.gen.d.ts +25 -0
  223. package/dist/generated/unfurl/core/params.gen.d.ts +43 -0
  224. package/dist/generated/unfurl/core/pathSerializer.gen.d.ts +33 -0
  225. package/dist/generated/unfurl/core/queryKeySerializer.gen.d.ts +18 -0
  226. package/dist/generated/unfurl/core/serverSentEvents.gen.d.ts +71 -0
  227. package/dist/generated/unfurl/core/types.gen.d.ts +83 -0
  228. package/dist/generated/unfurl/core/utils.gen.d.ts +19 -0
  229. package/dist/generated/unfurl/index.d.ts +2 -0
  230. package/dist/generated/unfurl/index.js +835 -0
  231. package/dist/generated/unfurl/sdk.gen.d.ts +47 -0
  232. package/dist/generated/unfurl/types.gen.d.ts +125 -0
  233. package/dist/src/config.d.ts +51 -0
  234. package/dist/src/entities/agent-sessions/agent-session.d.ts +45 -0
  235. package/dist/src/entities/agent-sessions/namespace.d.ts +18 -0
  236. package/dist/src/entities/bots/namespace.d.ts +25 -0
  237. package/dist/src/entities/calls/call-record.d.ts +55 -0
  238. package/dist/src/entities/calls/namespace.d.ts +9 -0
  239. package/dist/src/entities/channels/channel.d.ts +88 -0
  240. package/dist/src/entities/channels/message.d.ts +64 -0
  241. package/dist/src/entities/channels/namespace.d.ts +30 -0
  242. package/dist/src/entities/channels/post.d.ts +20 -0
  243. package/dist/src/entities/channels/thread.d.ts +30 -0
  244. package/dist/src/entities/chats/chat.d.ts +55 -0
  245. package/dist/src/entities/chats/namespace.d.ts +14 -0
  246. package/dist/src/entities/crm/comment.d.ts +43 -0
  247. package/dist/src/entities/crm/company.d.ts +70 -0
  248. package/dist/src/entities/crm/contact.d.ts +48 -0
  249. package/dist/src/entities/crm/namespace.d.ts +22 -0
  250. package/dist/src/entities/documents/comment.d.ts +41 -0
  251. package/dist/src/entities/documents/document.d.ts +130 -0
  252. package/dist/src/entities/documents/namespace.d.ts +43 -0
  253. package/dist/src/entities/documents/system-skill.d.ts +16 -0
  254. package/dist/src/entities/email/attachment.d.ts +36 -0
  255. package/dist/src/entities/email/label.d.ts +31 -0
  256. package/dist/src/entities/email/link.d.ts +29 -0
  257. package/dist/src/entities/email/message.d.ts +58 -0
  258. package/dist/src/entities/email/namespace.d.ts +49 -0
  259. package/dist/src/entities/email/thread.d.ts +88 -0
  260. package/dist/src/entities/entity.d.ts +101 -0
  261. package/dist/src/entities/favorites/namespace.d.ts +19 -0
  262. package/dist/src/entities/foreign/foreign-entity.d.ts +30 -0
  263. package/dist/src/entities/foreign/namespace.d.ts +7 -0
  264. package/dist/src/entities/notifications/namespace.d.ts +29 -0
  265. package/dist/src/entities/notifications/notification.d.ts +50 -0
  266. package/dist/src/entities/pins/namespace.d.ts +19 -0
  267. package/dist/src/entities/projects/namespace.d.ts +13 -0
  268. package/dist/src/entities/projects/project.d.ts +42 -0
  269. package/dist/src/entities/properties/namespace.d.ts +47 -0
  270. package/dist/src/entities/properties/property-definition.d.ts +45 -0
  271. package/dist/src/entities/properties/property-option.d.ts +32 -0
  272. package/dist/src/entities/search.d.ts +23 -0
  273. package/dist/src/entities/tasks/namespace.d.ts +21 -0
  274. package/dist/src/entities/tasks/task.d.ts +34 -0
  275. package/dist/src/entities/teams/namespace.d.ts +12 -0
  276. package/dist/src/entities/teams/team.d.ts +40 -0
  277. package/dist/src/entities/users/namespace.d.ts +10 -0
  278. package/dist/src/entities/users/user.d.ts +43 -0
  279. package/dist/src/entities/webhooks/namespace.d.ts +31 -0
  280. package/dist/src/entities/webhooks/webhook.d.ts +88 -0
  281. package/dist/src/events/hydrate/channel.d.ts +85 -0
  282. package/dist/src/events/hydrate/document.d.ts +54 -0
  283. package/dist/src/events/receiver.d.ts +51 -0
  284. package/dist/src/events/types.d.ts +40 -0
  285. package/dist/src/events/verify.d.ts +13 -0
  286. package/dist/src/local-portmap.d.ts +8 -0
  287. package/dist/src/macro.d.ts +62 -0
  288. package/dist/src/macro.js +4215 -0
  289. package/dist/src/mentions.d.ts +37 -0
  290. package/dist/src/raw.d.ts +12 -0
  291. package/dist/src/utils/client.d.ts +53 -0
  292. package/dist/src/utils/index.d.ts +4 -0
  293. package/dist/src/utils/lazy.d.ts +18 -0
  294. package/dist/src/utils/pagination.d.ts +7 -0
  295. package/dist/src/utils/unwrap.d.ts +23 -0
  296. package/package.json +49 -0
@@ -0,0 +1,4215 @@
1
+ import {
2
+ Sdk as Sdk3
3
+ } from "../chunk-SGAHIERJ.js";
4
+ import {
5
+ Sdk as Sdk6
6
+ } from "../chunk-PAAFJYGO.js";
7
+ import {
8
+ Sdk as Sdk2
9
+ } from "../chunk-JXIQT5TH.js";
10
+ import {
11
+ Sdk
12
+ } from "../chunk-QNUS5BC5.js";
13
+ import {
14
+ Sdk as Sdk5
15
+ } from "../chunk-5HAKQN23.js";
16
+ import {
17
+ Sdk as Sdk7
18
+ } from "../chunk-YRUXFEZM.js";
19
+ import {
20
+ Sdk as Sdk8
21
+ } from "../chunk-V45LUJDI.js";
22
+ import {
23
+ Sdk as Sdk9,
24
+ createClient
25
+ } from "../chunk-77EI4LSQ.js";
26
+ import {
27
+ Sdk as Sdk4
28
+ } from "../chunk-P4DTO6VD.js";
29
+
30
+ // src/config.ts
31
+ var WEB_APP_URLS = {
32
+ dev: "https://dev.macro.com",
33
+ prod: "https://macro.com",
34
+ local: "http://localhost:3000"
35
+ };
36
+ var HOSTS = {
37
+ dev: {
38
+ "agent-harness": "https://agent-harness-dev.macro.com",
39
+ storage: "https://cloud-storage-dev.macro.com",
40
+ auth: "https://auth-service-dev.macro.com",
41
+ email: "https://email-service-dev.macro.com",
42
+ cognition: "https://document-cognition-dev.macro.com",
43
+ notification: "https://notifications-dev.macro.com",
44
+ properties: "https://cloud-storage-dev.macro.com",
45
+ search: "https://cloud-storage-dev.macro.com",
46
+ "scheduled-action": "https://agent-schedule-dev.macro.com",
47
+ "static-files": "https://static-file-service-dev.macro.com",
48
+ connection: "https://connection-gateway-dev.macro.com",
49
+ contacts: "https://contacts-dev.macro.com",
50
+ unfurl: "https://unfurl-service-dev.macro.com"
51
+ },
52
+ prod: {
53
+ "agent-harness": "https://agent-harness.macro.com",
54
+ storage: "https://cloud-storage.macro.com",
55
+ auth: "https://auth-service.macro.com",
56
+ email: "https://email-service.macro.com",
57
+ cognition: "https://document-cognition.macro.com",
58
+ notification: "https://notifications.macro.com",
59
+ properties: "https://cloud-storage.macro.com",
60
+ search: "https://cloud-storage.macro.com",
61
+ "scheduled-action": "https://agent-schedule.macro.com",
62
+ "static-files": "https://static-file-service.macro.com",
63
+ connection: "https://connection-gateway.macro.com",
64
+ contacts: "https://contacts.macro.com",
65
+ unfurl: "https://unfurl-service.macro.com"
66
+ },
67
+ local: {
68
+ "agent-harness": "http://localhost:8101",
69
+ storage: "http://localhost:8086",
70
+ auth: "http://localhost:8080",
71
+ email: "http://localhost:8087",
72
+ cognition: "http://localhost:8085",
73
+ notification: "http://localhost:8089",
74
+ properties: "http://localhost:8086",
75
+ search: "http://localhost:8086",
76
+ "scheduled-action": "http://localhost:8098",
77
+ "static-files": "http://localhost:8100",
78
+ connection: "http://localhost:8082",
79
+ contacts: "http://localhost:8083",
80
+ unfurl: "http://localhost:8095"
81
+ }
82
+ };
83
+
84
+ // src/entities/bots/namespace.ts
85
+ var BotsNamespace = class {
86
+ constructor(client) {
87
+ this.client = client;
88
+ }
89
+ client;
90
+ /**
91
+ * The authenticated bot's own record. Requires bot auth; with a user API
92
+ * key this throws (a user token has no bot identity).
93
+ */
94
+ async me() {
95
+ if (this.client.authConfig.type !== "bot") {
96
+ throw new MacroError(
97
+ "bots.me() requires bot auth \u2014 a user API key has no bot identity"
98
+ );
99
+ }
100
+ return unwrap(await this.client.storage.getSelfBot());
101
+ }
102
+ /**
103
+ * Channels containing the authenticated bot. Requires bot auth.
104
+ */
105
+ async channels() {
106
+ if (this.client.authConfig.type !== "bot") {
107
+ throw new MacroError(
108
+ "bots.channels() requires bot auth \u2014 a user API key has no bot identity"
109
+ );
110
+ }
111
+ const bot = await this.me();
112
+ return unwrap(
113
+ await this.client.storage.listBotChannels({
114
+ path: { bot_id: bot.id }
115
+ })
116
+ );
117
+ }
118
+ /**
119
+ * The authenticated bot's canonical principal id (`bot|<uuid>`) — the form
120
+ * used for bot mentions, senders, and webhook `ids` filters. Cached on the
121
+ * client; see {@link MacroClient.myPrincipalId}.
122
+ */
123
+ async myPrincipalId() {
124
+ if (this.client.authConfig.type !== "bot") {
125
+ throw new MacroError(
126
+ "bots.myPrincipalId() requires bot auth \u2014 a user API key has no bot identity"
127
+ );
128
+ }
129
+ return this.client.myPrincipalId();
130
+ }
131
+ };
132
+
133
+ // src/mentions.ts
134
+ function wrapXml(tag, data) {
135
+ return `<${tag}>${JSON.stringify(data)}</${tag}>`;
136
+ }
137
+ function isMentionable(value) {
138
+ return typeof value === "object" && value !== null && typeof value.toMention === "function";
139
+ }
140
+ var here = {
141
+ toMention: () => ({
142
+ tag: wrapXml("m-group-mention", { groupAlias: "here" }),
143
+ mention: { entity_type: "group", entity_id: "here" }
144
+ })
145
+ };
146
+ function msg(strings, ...values) {
147
+ let content = "";
148
+ const mentions = [];
149
+ for (const [i2, string] of strings.entries()) {
150
+ content += string;
151
+ if (i2 >= values.length) continue;
152
+ const value = values[i2];
153
+ if (isMentionable(value)) {
154
+ const part = value.toMention();
155
+ content += part.tag;
156
+ mentions.push(part.mention);
157
+ } else {
158
+ content += String(value);
159
+ }
160
+ }
161
+ return { content, mentions: dedupe(mentions) };
162
+ }
163
+ function dedupe(mentions) {
164
+ const seen = /* @__PURE__ */ new Set();
165
+ return mentions.filter((m2) => {
166
+ const key = `${m2.entity_type}:${m2.entity_id}`;
167
+ if (seen.has(key)) return false;
168
+ seen.add(key);
169
+ return true;
170
+ });
171
+ }
172
+ function toBody(body) {
173
+ return typeof body === "string" ? { content: body, mentions: [] } : body;
174
+ }
175
+
176
+ // src/entities/entity.ts
177
+ var MacroEntity = class {
178
+ constructor(client, id, seed) {
179
+ this.client = client;
180
+ this.id = id;
181
+ this.detail = new Lazy(() => this.fetch(), seed);
182
+ }
183
+ client;
184
+ id;
185
+ detail;
186
+ /** A lazy accessor for one detail field, `null` normalized to `undefined`. */
187
+ field(key) {
188
+ return async () => (await this.detail.get())[key] ?? void 0;
189
+ }
190
+ /**
191
+ * Like {@link field}, but maps the raw value through `map` before returning.
192
+ * Used to expose an id field as a handle to the entity it references, e.g.
193
+ * `this.mappedField('owner', (id) => User.byId(this.client, id))`.
194
+ */
195
+ mappedField(key, map) {
196
+ return async () => map(
197
+ (await this.detail.get())[key] ?? void 0
198
+ );
199
+ }
200
+ toJSON() {
201
+ const detail = this.detail.peek();
202
+ return detail === void 0 ? { id: this.id } : { id: this.id, detail };
203
+ }
204
+ /** Run a write, unwrap it, and drop the cached detail so reads refetch. */
205
+ async mutate(fn) {
206
+ const out = unwrap(await fn(this.client));
207
+ this.detail.clear();
208
+ return out;
209
+ }
210
+ };
211
+ var FavoritableEntity = class extends MacroEntity {
212
+ /**
213
+ * Add this entity to the user's favorites. Returns this handle for chaining.
214
+ * Plain unwrap: favoriting alters the user's favorites collection, not this
215
+ * entity's own detail, so there's nothing cached to invalidate.
216
+ */
217
+ async favorite() {
218
+ unwrap(
219
+ await this.client.storage.addFavorite({
220
+ body: { entityId: this.id, entityType: this.entityType }
221
+ })
222
+ );
223
+ return this;
224
+ }
225
+ /** Remove this entity from the user's favorites. Returns this handle for chaining. */
226
+ async unfavorite() {
227
+ unwrap(
228
+ await this.client.storage.removeFavoriteByEntity({
229
+ path: {
230
+ entity_type: this.entityType,
231
+ entity_id: this.id
232
+ }
233
+ })
234
+ );
235
+ return this;
236
+ }
237
+ };
238
+ var PropertiedEntity = class extends FavoritableEntity {
239
+ /** This entity's reference for bulk property operations. */
240
+ propertyReference() {
241
+ return { entity_type: this.propertyEntityType, entity_id: this.id };
242
+ }
243
+ /** The properties set on this entity, each with its definition, value, and options. */
244
+ async properties(opts) {
245
+ const { properties } = unwrap(
246
+ await this.client.properties.getEntityProperties({
247
+ path: {
248
+ entity_type: this.propertyEntityType,
249
+ entity_id: this.id
250
+ },
251
+ query: opts?.includeMetadata !== void 0 ? { include_metadata: opts.includeMetadata } : void 0
252
+ })
253
+ );
254
+ return properties;
255
+ }
256
+ /**
257
+ * Set a property value on this entity, or attach the property without a
258
+ * value when `value` is omitted.
259
+ */
260
+ async setProperty(property, value) {
261
+ unwrap(
262
+ await this.client.properties.setEntityProperty({
263
+ path: {
264
+ ...this.propertyReference(),
265
+ property_id: property.id
266
+ },
267
+ body: { value: value ?? null }
268
+ })
269
+ );
270
+ }
271
+ /** Apply multi-select option deltas atomically across this entity's properties. */
272
+ async updatePropertyOptions(changes) {
273
+ return unwrap(
274
+ await this.client.properties.bulkUpdateEntityPropertyOptions({
275
+ path: this.propertyReference(),
276
+ body: {
277
+ properties: changes.map((change) => ({
278
+ property_id: change.property.id,
279
+ ...change.add ? { add_option_ids: change.add.map((option) => option.id) } : {},
280
+ ...change.remove ? { remove_option_ids: change.remove.map((option) => option.id) } : {}
281
+ }))
282
+ }
283
+ })
284
+ );
285
+ }
286
+ /** Remove a property from this entity, given its {@link properties} entry. */
287
+ async deleteProperty(assignment) {
288
+ unwrap(
289
+ await this.client.properties.deleteEntityProperty({
290
+ path: { entity_property_id: assignment.property.id }
291
+ })
292
+ );
293
+ }
294
+ };
295
+
296
+ // src/entities/search.ts
297
+ var DEFAULT_SEARCH_PAGE_SIZE = 50;
298
+ function entitySearch(opts) {
299
+ const { filters, type, make, includeCrm } = opts;
300
+ return (client, query, searchOpts) => {
301
+ const searchOn = searchOpts?.searchOn ?? "name_content";
302
+ const pageSize = searchOpts?.pageSize ?? DEFAULT_SEARCH_PAGE_SIZE;
303
+ return paginate(async (cursor) => {
304
+ const { results, next_cursor } = unwrap(
305
+ await client.search.unifiedSearch({
306
+ body: {
307
+ query,
308
+ match_type: "partial",
309
+ search_on: searchOn,
310
+ ...filters ? { filters } : {},
311
+ ...includeCrm ? { include_crm: true } : {}
312
+ },
313
+ query: {
314
+ page_size: pageSize,
315
+ ...cursor ? { cursor } : {}
316
+ }
317
+ })
318
+ );
319
+ const hits = results.filter(
320
+ (r2) => r2.type === type
321
+ );
322
+ return {
323
+ items: hits.map((h2) => make(client, h2)),
324
+ nextCursor: next_cursor
325
+ };
326
+ });
327
+ };
328
+ }
329
+
330
+ // src/entities/channels/post.ts
331
+ async function postToChannel(client, target, body) {
332
+ const { channelId, thread } = resolve(target);
333
+ if (await hasEntityAccess(client)) {
334
+ const { id } = unwrap(
335
+ await client.storage.postMessage({
336
+ path: { channel_id: channelId },
337
+ body: {
338
+ content: body.content,
339
+ mentions: body.mentions,
340
+ attachments: [],
341
+ thread_id: thread?.rootId ?? null,
342
+ nonce: crypto.randomUUID()
343
+ }
344
+ })
345
+ );
346
+ return id;
347
+ }
348
+ if (thread) {
349
+ throw new MacroError(
350
+ "a user-owned bot can only post via the channel webhook endpoint, which does not support threads \u2014 use a team-owned bot, or requestedAs(user), to reply in a thread"
351
+ );
352
+ }
353
+ const { message_id } = unwrap(
354
+ await client.storage.postChannelBotWebhook({
355
+ path: { channel_id: channelId },
356
+ body: { content: body.content },
357
+ // Not a claim to be acting as a user — no acting user is sent. The
358
+ // header is required to parse but never read here (the route resolves
359
+ // no access scope, only bot identity plus channel membership), and
360
+ // `user` is the value that authenticates: the inherited default would
361
+ // be `team`, which a user-owned bot is rejected for. If this route ever
362
+ // moves onto entity access, this breaks — user scope without an acting
363
+ // user is refused there.
364
+ headers: { "x-macro-bot-scope": "user" }
365
+ })
366
+ );
367
+ return message_id;
368
+ }
369
+ function resolve(target) {
370
+ return "rootId" in target ? { channelId: target.channelId, thread: target } : { channelId: target.id };
371
+ }
372
+ async function hasEntityAccess(client) {
373
+ if (client.authConfig.type !== "bot" || client.hasActingUser()) return true;
374
+ const { owner } = await client.selfBot();
375
+ return owner?.type === "team";
376
+ }
377
+
378
+ // src/entities/channels/thread.ts
379
+ var Thread = class {
380
+ constructor(client, channelId, rootId) {
381
+ this.client = client;
382
+ this.channelId = channelId;
383
+ this.rootId = rootId;
384
+ }
385
+ client;
386
+ channelId;
387
+ rootId;
388
+ /** The channel this thread is in. */
389
+ channel() {
390
+ return Channel.byId(this.client, this.channelId);
391
+ }
392
+ /** The message this thread hangs off. */
393
+ root() {
394
+ return Message.byId(this.client, this.channelId, this.rootId);
395
+ }
396
+ /** List the replies in this thread, oldest first. */
397
+ async replies() {
398
+ const replies = unwrap(
399
+ await this.client.storage.getThreadReplies({
400
+ path: { channel_id: this.channelId, message_id: this.rootId }
401
+ })
402
+ );
403
+ return replies.map(
404
+ (reply) => Message.fromReply(this.client, this.channelId, reply)
405
+ );
406
+ }
407
+ /**
408
+ * Post a reply in this thread.
409
+ *
410
+ * @param body - Plain text, or a rich body composed with {@link msg}.
411
+ * @returns The created reply.
412
+ */
413
+ async reply(body) {
414
+ const id = await postToChannel(this.client, this, toBody(body));
415
+ return Message.byId(this.client, this.channelId, id);
416
+ }
417
+ };
418
+
419
+ // src/entities/channels/message.ts
420
+ var Message = class _Message extends FavoritableEntity {
421
+ constructor(client, channelId, id, mentions = [], seed) {
422
+ super(client, id, seed);
423
+ this.channelId = channelId;
424
+ this.mentions = mentions;
425
+ }
426
+ channelId;
427
+ mentions;
428
+ /** Favorites identify channel messages as `channel_message`. */
429
+ entityType = "channel_message";
430
+ async fetch() {
431
+ const { messages } = unwrap(
432
+ await this.client.storage.getMessageWithContext({
433
+ path: { channel_id: this.channelId, message_id: this.id }
434
+ })
435
+ );
436
+ const target = messages.find((m2) => m2.id === this.id);
437
+ if (!target) throw new MacroNotFoundError(`message ${this.id} not found`);
438
+ return target;
439
+ }
440
+ /** A handle to a message by id. Fields load on first access. */
441
+ static byId(client, channelId, id, mentions = []) {
442
+ return new _Message(client, channelId, id, mentions);
443
+ }
444
+ /** Build a message from a list-endpoint record (pre-seeded, no fetch). */
445
+ static from(client, data, mentions = []) {
446
+ return new _Message(client, data.channel_id, data.id, mentions, data);
447
+ }
448
+ /** Build a message from a thread-reply record (pre-seeded, no fetch). */
449
+ static fromReply(client, channelId, reply, mentions = []) {
450
+ return new _Message(client, channelId, reply.id, mentions, reply);
451
+ }
452
+ /** Build a message from a webhook event record (pre-seeded, no fetch). */
453
+ static received(client, channelId, data, mentions = []) {
454
+ return new _Message(client, channelId, data.id, mentions, data);
455
+ }
456
+ /** The message body. */
457
+ content = this.field("content");
458
+ /** When the message was created. */
459
+ createdAt = this.field("created_at");
460
+ /** When the message was last edited, if it has been. */
461
+ editedAt = this.field("edited_at");
462
+ /** When the message was last updated. */
463
+ updatedAt = this.field("updated_at");
464
+ /** The user who sent this message. */
465
+ async author() {
466
+ return User.byId(this.client, (await this.detail.get()).sender_id);
467
+ }
468
+ /** The channel this message is in. */
469
+ channel() {
470
+ return Channel.byId(this.client, this.channelId);
471
+ }
472
+ /** The thread rooted at this message. */
473
+ thread() {
474
+ return new Thread(this.client, this.channelId, this.id);
475
+ }
476
+ /** Add an emoji reaction to this message. */
477
+ async react(emoji) {
478
+ await this.mutate(
479
+ (c2) => c2.storage.postReaction({
480
+ path: { channel_id: this.channelId },
481
+ body: { action: "Add", emoji, message_id: this.id }
482
+ })
483
+ );
484
+ return this;
485
+ }
486
+ /** Remove one of your emoji reactions from this message. */
487
+ async unreact(emoji) {
488
+ await this.mutate(
489
+ (c2) => c2.storage.postReaction({
490
+ path: { channel_id: this.channelId },
491
+ body: { action: "Remove", emoji, message_id: this.id }
492
+ })
493
+ );
494
+ return this;
495
+ }
496
+ /**
497
+ * Replace this message's body.
498
+ *
499
+ * @param body - Plain text, or a rich body composed with {@link msg}.
500
+ */
501
+ async edit(body) {
502
+ const { content, mentions } = toBody(body);
503
+ await this.mutate(
504
+ (c2) => c2.storage.patchMessage({
505
+ path: { channel_id: this.channelId, message_id: this.id },
506
+ body: { content, mentions }
507
+ })
508
+ );
509
+ return this;
510
+ }
511
+ /** Delete this message. */
512
+ async delete() {
513
+ await this.mutate(
514
+ (c2) => c2.storage.deleteMessage({
515
+ path: { channel_id: this.channelId, message_id: this.id }
516
+ })
517
+ );
518
+ }
519
+ /** Post a reply in this message's thread. */
520
+ async reply(body) {
521
+ return this.thread().reply(body);
522
+ }
523
+ };
524
+
525
+ // src/entities/channels/channel.ts
526
+ var Channel = class _Channel extends PropertiedEntity {
527
+ /** Favorites identify channels as `channel`. */
528
+ entityType = "channel";
529
+ /** The properties service identifies channels as `CHANNEL`. */
530
+ propertyEntityType = "CHANNEL";
531
+ async fetch() {
532
+ return unwrap(
533
+ await this.client.storage.getChannel({ path: { channel_id: this.id } })
534
+ );
535
+ }
536
+ /** A handle to a channel by id. Details load on first access. */
537
+ static byId(client, id) {
538
+ return new _Channel(client, id);
539
+ }
540
+ /** Open (creating if needed) the DM channel with a user. */
541
+ static async dm(client, recipient) {
542
+ const { channel_id } = unwrap(
543
+ await client.storage.getOrCreateDm({
544
+ body: { recipient_id: recipient.id }
545
+ })
546
+ );
547
+ return new _Channel(client, channel_id);
548
+ }
549
+ /** Open (creating if needed) the private group channel with a set of users. */
550
+ static async private(client, recipients) {
551
+ const { channel_id } = unwrap(
552
+ await client.storage.getOrCreatePrivate({
553
+ body: { recipients: recipients.map((u2) => u2.id) }
554
+ })
555
+ );
556
+ return new _Channel(client, channel_id);
557
+ }
558
+ /** Create a channel. The caller becomes the owner. */
559
+ static async create(client, opts) {
560
+ const { id } = unwrap(
561
+ await client.storage.createChannel({
562
+ body: {
563
+ channel_type: opts.type,
564
+ name: opts.name ?? null,
565
+ participants: (opts.participants ?? []).map((u2) => u2.id),
566
+ team_id: opts.team?.id ?? null
567
+ }
568
+ })
569
+ );
570
+ return new _Channel(client, id);
571
+ }
572
+ /** The channel's display name, resolved from the viewer's perspective. */
573
+ name = this.field("channel_name");
574
+ /** The channel's type (e.g. `public`, `dm`, `private`). */
575
+ type = this.field("channel_type");
576
+ /**
577
+ * Post a message. Plain text, or a rich body composed with `msg`.
578
+ *
579
+ * Works with a channel webhook token as well as a normal one — see
580
+ * {@link postToChannel} for which endpoint that picks and what it costs.
581
+ */
582
+ async send(body, opts) {
583
+ const id = await postToChannel(
584
+ this.client,
585
+ opts?.thread ?? this,
586
+ toBody(body)
587
+ );
588
+ return Message.byId(this.client, this.id, id);
589
+ }
590
+ /** The messages in this channel, most recent first, auto-paginated. */
591
+ messages(opts) {
592
+ return paginate(async (cursor) => {
593
+ const page = unwrap(
594
+ await this.client.storage.getChannelMessages({
595
+ path: { channel_id: this.id },
596
+ query: {
597
+ ...opts?.pageSize ? { limit: opts.pageSize } : {},
598
+ ...cursor ? { cursor } : {}
599
+ }
600
+ })
601
+ );
602
+ return {
603
+ items: page.items.map((m2) => Message.from(this.client, m2)),
604
+ nextCursor: page.next_cursor
605
+ };
606
+ });
607
+ }
608
+ /** A handle to a message in this channel by id. */
609
+ message(id) {
610
+ return Message.byId(this.client, this.id, id);
611
+ }
612
+ /** Rename the channel. */
613
+ async rename(name) {
614
+ await this.mutate(
615
+ (c2) => c2.storage.patchChannel({
616
+ path: { channel_id: this.id },
617
+ body: { channel_name: name }
618
+ })
619
+ );
620
+ }
621
+ /** Delete the channel. This is not reversible. */
622
+ async delete() {
623
+ await this.mutate(
624
+ (c2) => c2.storage.deleteChannel({ path: { channel_id: this.id } })
625
+ );
626
+ }
627
+ /** Join the channel as the current user. */
628
+ async join() {
629
+ await this.mutate(
630
+ (c2) => c2.storage.joinChannel({ path: { channel_id: this.id } })
631
+ );
632
+ }
633
+ /** A reusable code that lets a user join this channel. */
634
+ async joinCode() {
635
+ const { join_code } = unwrap(
636
+ await this.client.storage.getChannelJoinLink({
637
+ path: { channel_id: this.id }
638
+ })
639
+ );
640
+ return join_code;
641
+ }
642
+ /** Leave the channel as the current user. */
643
+ async leave() {
644
+ await this.mutate(
645
+ (c2) => c2.storage.leaveChannel({ path: { channel_id: this.id } })
646
+ );
647
+ }
648
+ /** The channel's members, with their roles and join times. */
649
+ async participants() {
650
+ return unwrap(
651
+ await this.client.storage.getChannelParticipants({
652
+ path: { channel_id: this.id }
653
+ })
654
+ );
655
+ }
656
+ /** Add users to the channel. */
657
+ async addParticipants(users) {
658
+ await this.mutate(
659
+ (c2) => c2.storage.addParticipants({
660
+ path: { channel_id: this.id },
661
+ body: { participants: users.map((u2) => u2.id) }
662
+ })
663
+ );
664
+ }
665
+ /** Remove users from the channel. */
666
+ async removeParticipants(users) {
667
+ await this.mutate(
668
+ (c2) => c2.storage.removeParticipants({
669
+ path: { channel_id: this.id },
670
+ body: { participants: users.map((u2) => u2.id) }
671
+ })
672
+ );
673
+ }
674
+ /** Broadcast a typing indicator, optionally scoped to a thread. */
675
+ async typing(action, opts) {
676
+ unwrap(
677
+ await this.client.storage.postTyping({
678
+ path: { channel_id: this.id },
679
+ body: { action, thread_id: opts?.thread?.rootId ?? null }
680
+ })
681
+ );
682
+ }
683
+ /** The attachments posted in this channel, auto-paginated. */
684
+ attachments(opts) {
685
+ return paginate(async (cursor) => {
686
+ const page = unwrap(
687
+ await this.client.storage.getChannelAttachments({
688
+ path: { channel_id: this.id },
689
+ query: {
690
+ ...opts?.pageSize ? { limit: opts.pageSize } : {},
691
+ ...opts?.type ? { attachment_type: opts.type } : {},
692
+ ...cursor ? { cursor } : {}
693
+ }
694
+ })
695
+ );
696
+ return { items: page.items, nextCursor: page.next_cursor };
697
+ });
698
+ }
699
+ /** The channel's URL in the Macro web app. */
700
+ webUrl() {
701
+ return `${this.client.webAppUrl}/app/channel/${this.id}`;
702
+ }
703
+ /** Search channels by content, most relevant first, auto-paginated. */
704
+ static search = entitySearch({
705
+ type: "channel",
706
+ make: (client, hit) => new _Channel(client, hit.channel_id)
707
+ });
708
+ };
709
+
710
+ // src/entities/users/user.ts
711
+ var User = class _User extends PropertiedEntity {
712
+ /** Favorites identify users as `user`. */
713
+ entityType = "user";
714
+ /** The properties service identifies users as `USER`. */
715
+ propertyEntityType = "USER";
716
+ async fetch() {
717
+ const { names } = unwrap(
718
+ await this.client.auth.getUserNamesWithEmail({
719
+ body: { user_ids: [this.id] }
720
+ })
721
+ );
722
+ const entry = names.find((n2) => n2.id === this.id);
723
+ if (!entry) throw new MacroNotFoundError(`user ${this.id} not found`);
724
+ return entry;
725
+ }
726
+ /** A handle to a user by id. */
727
+ static byId(client, id) {
728
+ return new _User(client, id);
729
+ }
730
+ /** A handle to the current authenticated user. */
731
+ static async me(client) {
732
+ const { user_id } = unwrap(await client.auth.getUserInfo());
733
+ return new _User(client, user_id);
734
+ }
735
+ /**
736
+ * This user's display name, fetched from the auth service (falling back to
737
+ * your email contacts when the Macro profile has none).
738
+ *
739
+ * @returns The full name, or `undefined` if the user has no name on record.
740
+ */
741
+ async name() {
742
+ const entry = await this.detail.get();
743
+ const full = [entry.first_name, entry.last_name].filter(Boolean).join(" ");
744
+ return full || void 0;
745
+ }
746
+ /**
747
+ * This user's email address. Macro user ids encode it as `macro|<email>`,
748
+ * so this reads straight off the id — no auth-service endpoint returns
749
+ * emails for arbitrary users.
750
+ *
751
+ * @returns The email, or `undefined` if the id is not email-derived.
752
+ */
753
+ email() {
754
+ const email = this.id.startsWith("macro|") ? this.id.slice(6) : void 0;
755
+ return email?.includes("@") ? email : void 0;
756
+ }
757
+ /**
758
+ * Open (or create) your direct-message channel with this user.
759
+ *
760
+ * @returns The DM `Channel`.
761
+ */
762
+ dm() {
763
+ return Channel.dm(this.client, this);
764
+ }
765
+ toMention() {
766
+ return {
767
+ tag: wrapXml("m-user-mention", { userId: this.id }),
768
+ mention: { entity_type: "user", entity_id: this.id }
769
+ };
770
+ }
771
+ };
772
+
773
+ // node_modules/ts-pattern/dist/index.js
774
+ var t = /* @__PURE__ */ Symbol.for("@ts-pattern/matcher");
775
+ var e = /* @__PURE__ */ Symbol.for("@ts-pattern/isVariadic");
776
+ var n = "@ts-pattern/anonymous-select-key";
777
+ var r = (t2) => Boolean(t2 && "object" == typeof t2);
778
+ var i = (e2) => e2 && !!e2[t];
779
+ var o = (n2, s2, c2) => {
780
+ if (i(n2)) {
781
+ const e2 = n2[t](), { matched: r2, selections: i2 } = e2.match(s2);
782
+ return r2 && i2 && Object.keys(i2).forEach((t2) => c2(t2, i2[t2])), r2;
783
+ }
784
+ if (r(n2)) {
785
+ if (!r(s2)) return false;
786
+ if (Array.isArray(n2)) {
787
+ if (!Array.isArray(s2)) return false;
788
+ let t2 = [], r2 = [], u2 = [];
789
+ for (const o2 of n2.keys()) {
790
+ const s3 = n2[o2];
791
+ i(s3) && s3[e] ? u2.push(s3) : u2.length ? r2.push(s3) : t2.push(s3);
792
+ }
793
+ if (u2.length) {
794
+ if (u2.length > 1) throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");
795
+ if (s2.length < t2.length + r2.length) return false;
796
+ const e2 = s2.slice(0, t2.length), n3 = 0 === r2.length ? [] : s2.slice(-r2.length), i2 = s2.slice(t2.length, 0 === r2.length ? Infinity : -r2.length);
797
+ return t2.every((t3, n4) => o(t3, e2[n4], c2)) && r2.every((t3, e3) => o(t3, n3[e3], c2)) && (0 === u2.length || o(u2[0], i2, c2));
798
+ }
799
+ return n2.length === s2.length && n2.every((t3, e2) => o(t3, s2[e2], c2));
800
+ }
801
+ return Reflect.ownKeys(n2).every((e2) => {
802
+ const r2 = n2[e2];
803
+ return (e2 in s2 || i(u2 = r2) && "optional" === u2[t]().matcherType) && o(r2, s2[e2], c2);
804
+ var u2;
805
+ });
806
+ }
807
+ return Object.is(s2, n2);
808
+ };
809
+ var s = (e2) => {
810
+ var n2, o2, u2;
811
+ return r(e2) ? i(e2) ? null != (n2 = null == (o2 = (u2 = e2[t]()).getSelectionKeys) ? void 0 : o2.call(u2)) ? n2 : [] : Array.isArray(e2) ? c(e2, s) : c(Object.values(e2), s) : [];
812
+ };
813
+ var c = (t2, e2) => t2.reduce((t3, n2) => t3.concat(e2(n2)), []);
814
+ function u(...t2) {
815
+ if (1 === t2.length) {
816
+ const [e2] = t2;
817
+ return (t3) => o(e2, t3, () => {
818
+ });
819
+ }
820
+ if (2 === t2.length) {
821
+ const [e2, n2] = t2;
822
+ return o(e2, n2, () => {
823
+ });
824
+ }
825
+ throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${t2.length}.`);
826
+ }
827
+ function a(t2) {
828
+ return Object.assign(t2, { optional: () => h(t2), and: (e2) => d(t2, e2), or: (e2) => y(t2, e2), select: (e2) => void 0 === e2 ? v(t2) : v(e2, t2) });
829
+ }
830
+ function l(t2) {
831
+ return Object.assign(((t3) => Object.assign(t3, { [Symbol.iterator]() {
832
+ let n2 = 0;
833
+ const r2 = [{ value: Object.assign(t3, { [e]: true }), done: false }, { done: true, value: void 0 }];
834
+ return { next: () => {
835
+ var t4;
836
+ return null != (t4 = r2[n2++]) ? t4 : r2.at(-1);
837
+ } };
838
+ } }))(t2), { optional: () => l(h(t2)), select: (e2) => l(void 0 === e2 ? v(t2) : v(e2, t2)) });
839
+ }
840
+ function h(e2) {
841
+ return a({ [t]: () => ({ match: (t2) => {
842
+ let n2 = {};
843
+ const r2 = (t3, e3) => {
844
+ n2[t3] = e3;
845
+ };
846
+ return void 0 === t2 ? (s(e2).forEach((t3) => r2(t3, void 0)), { matched: true, selections: n2 }) : { matched: o(e2, t2, r2), selections: n2 };
847
+ }, getSelectionKeys: () => s(e2), matcherType: "optional" }) });
848
+ }
849
+ var f = (t2, e2) => {
850
+ for (const n2 of t2) if (!e2(n2)) return false;
851
+ return true;
852
+ };
853
+ var g = (t2, e2) => {
854
+ for (const [n2, r2] of t2.entries()) if (!e2(r2, n2)) return false;
855
+ return true;
856
+ };
857
+ var m = (t2, e2) => {
858
+ const n2 = Reflect.ownKeys(t2);
859
+ for (const r2 of n2) if (!e2(r2, t2[r2])) return false;
860
+ return true;
861
+ };
862
+ function d(...e2) {
863
+ return a({ [t]: () => ({ match: (t2) => {
864
+ let n2 = {};
865
+ const r2 = (t3, e3) => {
866
+ n2[t3] = e3;
867
+ };
868
+ return { matched: e2.every((e3) => o(e3, t2, r2)), selections: n2 };
869
+ }, getSelectionKeys: () => c(e2, s), matcherType: "and" }) });
870
+ }
871
+ function y(...e2) {
872
+ return a({ [t]: () => ({ match: (t2) => {
873
+ let n2 = {};
874
+ const r2 = (t3, e3) => {
875
+ n2[t3] = e3;
876
+ };
877
+ return c(e2, s).forEach((t3) => r2(t3, void 0)), { matched: e2.some((e3) => o(e3, t2, r2)), selections: n2 };
878
+ }, getSelectionKeys: () => c(e2, s), matcherType: "or" }) });
879
+ }
880
+ function p(e2) {
881
+ return { [t]: () => ({ match: (t2) => ({ matched: Boolean(e2(t2)) }) }) };
882
+ }
883
+ function v(...e2) {
884
+ const r2 = "string" == typeof e2[0] ? e2[0] : void 0, i2 = 2 === e2.length ? e2[1] : "string" == typeof e2[0] ? void 0 : e2[0];
885
+ return a({ [t]: () => ({ match: (t2) => {
886
+ let e3 = { [null != r2 ? r2 : n]: t2 };
887
+ return { matched: void 0 === i2 || o(i2, t2, (t3, n2) => {
888
+ e3[t3] = n2;
889
+ }), selections: e3 };
890
+ }, getSelectionKeys: () => [null != r2 ? r2 : n].concat(void 0 === i2 ? [] : s(i2)) }) });
891
+ }
892
+ function b(t2) {
893
+ return true;
894
+ }
895
+ function w(t2) {
896
+ return "number" == typeof t2;
897
+ }
898
+ function S(t2) {
899
+ return "string" == typeof t2;
900
+ }
901
+ function j(t2) {
902
+ return "bigint" == typeof t2;
903
+ }
904
+ var K = a(p(b));
905
+ var O = a(p(b));
906
+ var E = K;
907
+ var x = (t2) => Object.assign(a(t2), { startsWith: (e2) => {
908
+ return x(d(t2, (n2 = e2, p((t3) => S(t3) && t3.startsWith(n2)))));
909
+ var n2;
910
+ }, endsWith: (e2) => {
911
+ return x(d(t2, (n2 = e2, p((t3) => S(t3) && t3.endsWith(n2)))));
912
+ var n2;
913
+ }, minLength: (e2) => x(d(t2, ((t3) => p((e3) => S(e3) && e3.length >= t3))(e2))), length: (e2) => x(d(t2, ((t3) => p((e3) => S(e3) && e3.length === t3))(e2))), maxLength: (e2) => x(d(t2, ((t3) => p((e3) => S(e3) && e3.length <= t3))(e2))), includes: (e2) => {
914
+ return x(d(t2, (n2 = e2, p((t3) => S(t3) && t3.includes(n2)))));
915
+ var n2;
916
+ }, regex: (e2) => {
917
+ return x(d(t2, (n2 = e2, p((t3) => S(t3) && Boolean(t3.match(n2))))));
918
+ var n2;
919
+ } });
920
+ var A = x(p(S));
921
+ var N = (t2) => Object.assign(a(t2), { between: (e2, n2) => N(d(t2, ((t3, e3) => p((n3) => w(n3) && t3 <= n3 && e3 >= n3))(e2, n2))), lt: (e2) => N(d(t2, ((t3) => p((e3) => w(e3) && e3 < t3))(e2))), gt: (e2) => N(d(t2, ((t3) => p((e3) => w(e3) && e3 > t3))(e2))), lte: (e2) => N(d(t2, ((t3) => p((e3) => w(e3) && e3 <= t3))(e2))), gte: (e2) => N(d(t2, ((t3) => p((e3) => w(e3) && e3 >= t3))(e2))), int: () => N(d(t2, p((t3) => w(t3) && Number.isInteger(t3)))), finite: () => N(d(t2, p((t3) => w(t3) && Number.isFinite(t3)))), positive: () => N(d(t2, p((t3) => w(t3) && t3 > 0))), negative: () => N(d(t2, p((t3) => w(t3) && t3 < 0))) });
922
+ var P = N(p(w));
923
+ var k = (t2) => Object.assign(a(t2), { between: (e2, n2) => k(d(t2, ((t3, e3) => p((n3) => j(n3) && t3 <= n3 && e3 >= n3))(e2, n2))), lt: (e2) => k(d(t2, ((t3) => p((e3) => j(e3) && e3 < t3))(e2))), gt: (e2) => k(d(t2, ((t3) => p((e3) => j(e3) && e3 > t3))(e2))), lte: (e2) => k(d(t2, ((t3) => p((e3) => j(e3) && e3 <= t3))(e2))), gte: (e2) => k(d(t2, ((t3) => p((e3) => j(e3) && e3 >= t3))(e2))), positive: () => k(d(t2, p((t3) => j(t3) && t3 > 0))), negative: () => k(d(t2, p((t3) => j(t3) && t3 < 0))) });
924
+ var T = k(p(j));
925
+ var B = a(p(function(t2) {
926
+ return "boolean" == typeof t2;
927
+ }));
928
+ var _ = a(p(function(t2) {
929
+ return "symbol" == typeof t2;
930
+ }));
931
+ var W = a(p(function(t2) {
932
+ return null == t2;
933
+ }));
934
+ var $ = a(p(function(t2) {
935
+ return null != t2;
936
+ }));
937
+ var z = { __proto__: null, matcher: t, optional: h, array: function(...e2) {
938
+ return l({ [t]: () => ({ match: (t2) => {
939
+ if (!Array.isArray(t2)) return { matched: false };
940
+ if (0 === e2.length) return { matched: true };
941
+ const n2 = e2[0];
942
+ let r2 = {};
943
+ if (0 === t2.length) return s(n2).forEach((t3) => {
944
+ r2[t3] = [];
945
+ }), { matched: true, selections: r2 };
946
+ const i2 = (t3, e3) => {
947
+ r2[t3] = (r2[t3] || []).concat([e3]);
948
+ };
949
+ return { matched: t2.every((t3) => o(n2, t3, i2)), selections: r2 };
950
+ }, getSelectionKeys: () => 0 === e2.length ? [] : s(e2[0]) }) });
951
+ }, set: function(...e2) {
952
+ return a({ [t]: () => ({ match: (t2) => {
953
+ if (!(t2 instanceof Set)) return { matched: false };
954
+ let n2 = {};
955
+ if (0 === t2.size) return { matched: true, selections: n2 };
956
+ if (0 === e2.length) return { matched: true };
957
+ const r2 = (t3, e3) => {
958
+ n2[t3] = (n2[t3] || []).concat([e3]);
959
+ }, i2 = e2[0];
960
+ return { matched: f(t2, (t3) => o(i2, t3, r2)), selections: n2 };
961
+ }, getSelectionKeys: () => 0 === e2.length ? [] : s(e2[0]) }) });
962
+ }, map: function(...e2) {
963
+ return a({ [t]: () => ({ match: (t2) => {
964
+ if (!(t2 instanceof Map)) return { matched: false };
965
+ let n2 = {};
966
+ if (0 === t2.size) return { matched: true, selections: n2 };
967
+ const r2 = (t3, e3) => {
968
+ n2[t3] = (n2[t3] || []).concat([e3]);
969
+ };
970
+ if (0 === e2.length) return { matched: true };
971
+ var i2;
972
+ if (1 === e2.length) throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${null == (i2 = e2[0]) ? void 0 : i2.toString()}`);
973
+ const [s2, c2] = e2;
974
+ return { matched: g(t2, (t3, e3) => {
975
+ const n3 = o(s2, e3, r2), i3 = o(c2, t3, r2);
976
+ return n3 && i3;
977
+ }), selections: n2 };
978
+ }, getSelectionKeys: () => 0 === e2.length ? [] : [...s(e2[0]), ...s(e2[1])] }) });
979
+ }, record: function(...e2) {
980
+ return a({ [t]: () => ({ match: (t2) => {
981
+ if (null === t2 || "object" != typeof t2 || Array.isArray(t2)) return { matched: false };
982
+ var n2;
983
+ if (0 === e2.length) throw new Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${null == (n2 = e2[0]) ? void 0 : n2.toString()}`);
984
+ let r2 = {};
985
+ const i2 = (t3, e3) => {
986
+ r2[t3] = (r2[t3] || []).concat([e3]);
987
+ }, [s2, c2] = 1 === e2.length ? [A, e2[0]] : e2;
988
+ return { matched: m(t2, (t3, e3) => {
989
+ const n3 = "string" != typeof t3 || Number.isNaN(Number(t3)) ? null : Number(t3), r3 = null !== n3 && o(s2, n3, i2), u2 = o(s2, t3, i2), a2 = o(c2, e3, i2);
990
+ return (u2 || r3) && a2;
991
+ }), selections: r2 };
992
+ }, getSelectionKeys: () => 0 === e2.length ? [] : [...s(e2[0]), ...s(e2[1])] }) });
993
+ }, intersection: d, union: y, not: function(e2) {
994
+ return a({ [t]: () => ({ match: (t2) => ({ matched: !o(e2, t2, () => {
995
+ }) }), getSelectionKeys: () => [], matcherType: "not" }) });
996
+ }, when: p, select: v, any: K, unknown: O, _: E, string: A, number: P, bigint: T, boolean: B, symbol: _, nullish: W, nonNullable: $, instanceOf: function(t2) {
997
+ return a(p(/* @__PURE__ */ (function(t3) {
998
+ return (e2) => e2 instanceof t3;
999
+ })(t2)));
1000
+ }, shape: function(t2) {
1001
+ return a(p(u(t2)));
1002
+ } };
1003
+ var I = class extends Error {
1004
+ constructor(t2) {
1005
+ let e2;
1006
+ try {
1007
+ e2 = JSON.stringify(t2);
1008
+ } catch (n2) {
1009
+ e2 = t2;
1010
+ }
1011
+ super(`Pattern matching error: no pattern matches value ${e2}`), this.input = void 0, this.input = t2;
1012
+ }
1013
+ };
1014
+ var L = { matched: false, value: void 0 };
1015
+ function M(t2) {
1016
+ return new R(t2, L);
1017
+ }
1018
+ var R = class _R {
1019
+ constructor(t2, e2) {
1020
+ this.input = void 0, this.state = void 0, this.input = t2, this.state = e2;
1021
+ }
1022
+ with(...t2) {
1023
+ if (this.state.matched) return this;
1024
+ const e2 = t2[t2.length - 1], r2 = [t2[0]];
1025
+ let i2;
1026
+ 3 === t2.length && "function" == typeof t2[1] ? i2 = t2[1] : t2.length > 2 && r2.push(...t2.slice(1, t2.length - 1));
1027
+ let s2 = false, c2 = {};
1028
+ const u2 = (t3, e3) => {
1029
+ s2 = true, c2[t3] = e3;
1030
+ }, a2 = !r2.some((t3) => o(t3, this.input, u2)) || i2 && !Boolean(i2(this.input)) ? L : { matched: true, value: e2(s2 ? n in c2 ? c2[n] : c2 : this.input, this.input) };
1031
+ return new _R(this.input, a2);
1032
+ }
1033
+ when(t2, e2) {
1034
+ if (this.state.matched) return this;
1035
+ const n2 = Boolean(t2(this.input));
1036
+ return new _R(this.input, n2 ? { matched: true, value: e2(this.input, this.input) } : L);
1037
+ }
1038
+ otherwise(t2) {
1039
+ return this.state.matched ? this.state.value : t2(this.input);
1040
+ }
1041
+ exhaustive(t2 = F) {
1042
+ return this.state.matched ? this.state.value : t2(this.input);
1043
+ }
1044
+ run() {
1045
+ return this.exhaustive();
1046
+ }
1047
+ returnType() {
1048
+ return this;
1049
+ }
1050
+ narrow() {
1051
+ return this;
1052
+ }
1053
+ };
1054
+ function F(t2) {
1055
+ throw new I(t2);
1056
+ }
1057
+
1058
+ // src/events/hydrate/channel.ts
1059
+ var USER_PREFIX = "macro|";
1060
+ function userFromPrincipal(client, principalId) {
1061
+ return principalId.startsWith(USER_PREFIX) && principalId.length > USER_PREFIX.length ? User.byId(client, principalId.toLowerCase()) : void 0;
1062
+ }
1063
+ function hydrateChannelEvent(client, event) {
1064
+ return M(event).with({ event_type: "channel.created" }, ({ metadata }) => ({
1065
+ event_type: "channel.created",
1066
+ metadata,
1067
+ channel: Channel.byId(client, metadata.channel_id),
1068
+ actor: userFromPrincipal(client, metadata.actor),
1069
+ participants: metadata.participant_user_ids.map(
1070
+ (userId) => User.byId(client, userId)
1071
+ )
1072
+ })).with({ event_type: "channel.updated" }, ({ metadata }) => ({
1073
+ event_type: "channel.updated",
1074
+ metadata,
1075
+ channel: Channel.byId(client, metadata.channel_id),
1076
+ actor: userFromPrincipal(client, metadata.actor)
1077
+ })).with({ event_type: "channel.deleted" }, ({ metadata }) => ({
1078
+ event_type: "channel.deleted",
1079
+ metadata,
1080
+ channel: Channel.byId(client, metadata.channel_id),
1081
+ actor: userFromPrincipal(client, metadata.actor)
1082
+ })).with({ event_type: "channel.message_posted" }, ({ metadata }) => ({
1083
+ event_type: "channel.message_posted",
1084
+ metadata,
1085
+ channel: Channel.byId(client, metadata.channel_id),
1086
+ message: Message.byId(
1087
+ client,
1088
+ metadata.channel_id,
1089
+ metadata.message_id,
1090
+ metadata.mentions
1091
+ ),
1092
+ sender: userFromPrincipal(client, metadata.sender),
1093
+ thread: metadata.thread_id ? new Thread(client, metadata.channel_id, metadata.thread_id) : void 0
1094
+ })).with({ event_type: "channel.mentioned" }, ({ metadata }) => ({
1095
+ event_type: "channel.mentioned",
1096
+ metadata,
1097
+ channel: Channel.byId(client, metadata.channel_id),
1098
+ message: Message.byId(
1099
+ client,
1100
+ metadata.channel_id,
1101
+ metadata.message_id,
1102
+ []
1103
+ ),
1104
+ sender: userFromPrincipal(client, metadata.sender),
1105
+ thread: metadata.thread_id ? new Thread(client, metadata.channel_id, metadata.thread_id) : void 0
1106
+ })).with({ event_type: "channel.message_patched" }, ({ metadata }) => ({
1107
+ event_type: "channel.message_patched",
1108
+ metadata,
1109
+ channel: Channel.byId(client, metadata.channel_id),
1110
+ message: Message.byId(
1111
+ client,
1112
+ metadata.channel_id,
1113
+ metadata.message_id,
1114
+ []
1115
+ ),
1116
+ actor: userFromPrincipal(client, metadata.actor),
1117
+ thread: metadata.thread_id ? new Thread(client, metadata.channel_id, metadata.thread_id) : void 0
1118
+ })).with({ event_type: "channel.message_deleted" }, ({ metadata }) => ({
1119
+ event_type: "channel.message_deleted",
1120
+ metadata,
1121
+ channel: Channel.byId(client, metadata.channel_id),
1122
+ message: Message.byId(
1123
+ client,
1124
+ metadata.channel_id,
1125
+ metadata.message_id,
1126
+ []
1127
+ ),
1128
+ actor: userFromPrincipal(client, metadata.actor),
1129
+ thread: metadata.thread_id ? new Thread(client, metadata.channel_id, metadata.thread_id) : void 0
1130
+ })).with(
1131
+ { event_type: "channel.message_attachment_created" },
1132
+ ({ metadata }) => ({
1133
+ event_type: "channel.message_attachment_created",
1134
+ metadata,
1135
+ channel: Channel.byId(client, metadata.channel_id),
1136
+ message: Message.byId(
1137
+ client,
1138
+ metadata.channel_id,
1139
+ metadata.message_id,
1140
+ []
1141
+ ),
1142
+ actor: userFromPrincipal(client, metadata.actor)
1143
+ })
1144
+ ).with(
1145
+ { event_type: "channel.message_attachment_removed" },
1146
+ ({ metadata }) => ({
1147
+ event_type: "channel.message_attachment_removed",
1148
+ metadata,
1149
+ channel: Channel.byId(client, metadata.channel_id),
1150
+ message: Message.byId(
1151
+ client,
1152
+ metadata.channel_id,
1153
+ metadata.message_id,
1154
+ []
1155
+ ),
1156
+ actor: userFromPrincipal(client, metadata.actor)
1157
+ })
1158
+ ).with({ event_type: "channel.participant_added" }, ({ metadata }) => ({
1159
+ event_type: "channel.participant_added",
1160
+ metadata,
1161
+ channel: Channel.byId(client, metadata.channel_id),
1162
+ addedBy: userFromPrincipal(client, metadata.added_by),
1163
+ addedUsers: metadata.added_user_ids.map(
1164
+ (userId) => User.byId(client, userId)
1165
+ )
1166
+ })).with({ event_type: "channel.participant_removed" }, ({ metadata }) => ({
1167
+ event_type: "channel.participant_removed",
1168
+ metadata,
1169
+ channel: Channel.byId(client, metadata.channel_id),
1170
+ removedBy: User.byId(client, metadata.removed_by),
1171
+ removedUsers: metadata.removed_user_ids.map(
1172
+ (userId) => User.byId(client, userId)
1173
+ )
1174
+ })).exhaustive();
1175
+ }
1176
+
1177
+ // src/entities/projects/project.ts
1178
+ var Project = class _Project extends PropertiedEntity {
1179
+ /** Favorites identify projects as `project`. */
1180
+ entityType = "project";
1181
+ /** The properties service identifies projects as `PROJECT`. */
1182
+ propertyEntityType = "PROJECT";
1183
+ async fetch() {
1184
+ const { data } = unwrap(
1185
+ await this.client.storage.getProjectHandler({
1186
+ path: { id: this.id }
1187
+ })
1188
+ );
1189
+ return data.projectMetadata;
1190
+ }
1191
+ /** A handle to a project by id. Details load on first access. */
1192
+ static byId(client, id) {
1193
+ return new _Project(client, id);
1194
+ }
1195
+ /** Create a project, optionally nested inside a parent project. */
1196
+ static async create(client, opts) {
1197
+ const { data } = unwrap(
1198
+ await client.storage.createProjectHandler({
1199
+ body: {
1200
+ name: opts.name,
1201
+ projectParentId: opts.parent?.id ?? null
1202
+ }
1203
+ })
1204
+ );
1205
+ return new _Project(client, data.id, data);
1206
+ }
1207
+ /** The project's display name. */
1208
+ name = this.field("name");
1209
+ /** The parent project, if this project is nested. */
1210
+ parent = this.mappedField(
1211
+ "parentId",
1212
+ (id) => id ? _Project.byId(this.client, id) : void 0
1213
+ );
1214
+ /** When the project was created (RFC 3339 timestamp). */
1215
+ createdAt = this.field("createdAt");
1216
+ /** The items (documents, chats, subprojects) directly inside this project. */
1217
+ async items() {
1218
+ const { data } = unwrap(
1219
+ await this.client.storage.getProjectContentHandler({
1220
+ path: { id: this.id }
1221
+ })
1222
+ );
1223
+ return data.map((entry) => entry.item);
1224
+ }
1225
+ /** Rename the project. */
1226
+ async rename(name) {
1227
+ await this.mutate(
1228
+ (c2) => c2.storage.editProjectV2({
1229
+ path: { id: this.id },
1230
+ body: { name }
1231
+ })
1232
+ );
1233
+ }
1234
+ /**
1235
+ * Delete the project and its contents. Soft by default (reversible with
1236
+ * {@link restore}); pass `permanent: true` to delete irreversibly.
1237
+ */
1238
+ async delete(opts) {
1239
+ await this.mutate(
1240
+ (c2) => opts?.permanent ? c2.storage.permanentlyDeleteProject({ path: { id: this.id } }) : c2.storage.deleteProjectHandler({ path: { id: this.id } })
1241
+ );
1242
+ }
1243
+ /** Restore a soft-deleted project. */
1244
+ async restore() {
1245
+ await this.mutate(
1246
+ (c2) => c2.storage.revertDeleteProject({ path: { id: this.id } })
1247
+ );
1248
+ }
1249
+ /** Search projects by name and content, most relevant first, auto-paginated. */
1250
+ static search = entitySearch({
1251
+ filters: { project_filters: {} },
1252
+ type: "project",
1253
+ make: (client, hit) => new _Project(client, hit.id)
1254
+ });
1255
+ };
1256
+
1257
+ // src/entities/documents/comment.ts
1258
+ var Comment = class _Comment extends MacroEntity {
1259
+ constructor(client, documentId, commentId, seed) {
1260
+ super(client, String(commentId), seed);
1261
+ this.documentId = documentId;
1262
+ this.commentId = commentId;
1263
+ }
1264
+ documentId;
1265
+ commentId;
1266
+ /**
1267
+ * There is no single-comment GET, so a fetch loads the document's comment
1268
+ * threads and finds this comment in them.
1269
+ */
1270
+ async fetch() {
1271
+ const { data } = unwrap(
1272
+ await this.client.storage.getDocumentComments({
1273
+ path: { document_id: this.documentId }
1274
+ })
1275
+ );
1276
+ for (const thread of data) {
1277
+ const found = thread.comments.find((c2) => c2.commentId === this.commentId);
1278
+ if (found) return found;
1279
+ }
1280
+ throw new MacroNotFoundError(
1281
+ `comment ${this.commentId} not found on document ${this.documentId}`
1282
+ );
1283
+ }
1284
+ /** Build a comment from a comment-thread record (pre-seeded, no fetch). */
1285
+ static from(client, document, record) {
1286
+ return new _Comment(client, document.id, record.commentId, record);
1287
+ }
1288
+ /** The comment's text. */
1289
+ text = this.field("text");
1290
+ /** The id of the thread this comment belongs to. */
1291
+ threadId = this.field("threadId");
1292
+ /** When the comment was created. */
1293
+ createdAt = this.field("createdAt");
1294
+ /** When the comment was last updated. */
1295
+ updatedAt = this.field("updatedAt");
1296
+ /** The user who wrote this comment. */
1297
+ async author() {
1298
+ return User.byId(this.client, (await this.detail.get()).owner);
1299
+ }
1300
+ /**
1301
+ * Replace the comment's text. The endpoint requires the thread id in the
1302
+ * body, which is resolved from the comment's own record.
1303
+ */
1304
+ async edit(text) {
1305
+ const { threadId } = await this.detail.get();
1306
+ await this.mutate(
1307
+ (c2) => c2.storage.editComment({
1308
+ path: { comment_id: this.commentId },
1309
+ body: { text, threadId }
1310
+ })
1311
+ );
1312
+ return this;
1313
+ }
1314
+ /** Delete this comment. */
1315
+ async delete() {
1316
+ await this.mutate(
1317
+ (c2) => c2.storage.deleteComment({
1318
+ path: { comment_id: this.commentId },
1319
+ body: {}
1320
+ })
1321
+ );
1322
+ }
1323
+ };
1324
+
1325
+ // src/entities/documents/document.ts
1326
+ var Document = class _Document extends PropertiedEntity {
1327
+ async fetch() {
1328
+ const { data } = unwrap(
1329
+ await this.client.storage.getDocument({
1330
+ path: { document_id: this.id }
1331
+ })
1332
+ );
1333
+ return data.documentMetadata;
1334
+ }
1335
+ /** A handle to a document by id. Details load on first access. */
1336
+ static byId(client, id) {
1337
+ return new _Document(client, id);
1338
+ }
1339
+ /** Create a markdown document. */
1340
+ static async create(client, opts) {
1341
+ const { documentId } = unwrap(
1342
+ await client.storage.createMarkdownHandler({
1343
+ body: {
1344
+ documentName: opts.name,
1345
+ markdown: opts.markdown ?? null,
1346
+ projectId: opts.project?.id ?? null
1347
+ }
1348
+ })
1349
+ );
1350
+ return new _Document(client, documentId);
1351
+ }
1352
+ /**
1353
+ * Create a snippet: a reusable markdown document that can be inserted into
1354
+ * any markdown area.
1355
+ */
1356
+ static async createSnippet(client, opts) {
1357
+ const { documentId } = unwrap(
1358
+ await client.storage.createSnippetHandler({
1359
+ body: {
1360
+ snippetName: opts.name,
1361
+ markdown: opts.markdown ?? null,
1362
+ projectId: opts.project?.id ?? null
1363
+ }
1364
+ })
1365
+ );
1366
+ return new _Document(client, documentId);
1367
+ }
1368
+ /**
1369
+ * Create a skill: a markdown document containing instructions that AI reads
1370
+ * and follows when the skill is referenced in an AI input.
1371
+ */
1372
+ static async createSkill(client, opts) {
1373
+ const { documentId } = unwrap(
1374
+ await client.storage.createSkillHandler({
1375
+ body: {
1376
+ skillName: opts.name,
1377
+ markdown: opts.markdown ?? null,
1378
+ projectId: opts.project?.id ?? null
1379
+ }
1380
+ })
1381
+ );
1382
+ return new _Document(client, documentId);
1383
+ }
1384
+ /** The user's recent documents, most recent first, auto-paginated. */
1385
+ static recent(client, opts) {
1386
+ const limit = opts?.pageSize ?? 50;
1387
+ return paginate(async (cursor) => {
1388
+ const page = unwrap(
1389
+ await client.storage.getUserDocumentsHandler({
1390
+ query: {
1391
+ limit,
1392
+ offset: cursor ? Number(cursor) : 0,
1393
+ ...opts?.fileType !== void 0 ? { file_type: opts.fileType } : {}
1394
+ }
1395
+ })
1396
+ );
1397
+ const next = page.data?.next_offset;
1398
+ return {
1399
+ items: (page.data?.documents ?? []).map(
1400
+ (d2) => new _Document(client, d2.documentId)
1401
+ ),
1402
+ nextCursor: next != null ? String(next) : null
1403
+ };
1404
+ });
1405
+ }
1406
+ /**
1407
+ * The user's recently soft-deleted documents. The underlying endpoint also
1408
+ * returns deleted chats and projects; those are filtered out here.
1409
+ */
1410
+ static async recentlyDeleted(client) {
1411
+ const { data } = unwrap(await client.storage.recentlyDeleted({}));
1412
+ return data.items.filter((i2) => i2.type === "document").map((d2) => new _Document(client, d2.id));
1413
+ }
1414
+ /** Favorites identify documents as `document`. */
1415
+ entityType = "document";
1416
+ /** The properties service identifies documents as `DOCUMENT`. */
1417
+ propertyEntityType = "DOCUMENT";
1418
+ /** The document's display name. */
1419
+ name = this.field("documentName");
1420
+ /** The document's file type (e.g. `md`, `pdf`, `docx`). */
1421
+ fileType = this.field("fileType");
1422
+ /** The project this document belongs to, if any. */
1423
+ project = this.mappedField(
1424
+ "projectId",
1425
+ (id) => id ? Project.byId(this.client, id) : void 0
1426
+ );
1427
+ /** The user who owns the document. */
1428
+ owner = this.mappedField(
1429
+ "owner",
1430
+ (id) => User.byId(this.client, id)
1431
+ );
1432
+ /** The document this one was branched from, if any. */
1433
+ branchedFrom = this.mappedField(
1434
+ "branchedFromId",
1435
+ (id) => id ? _Document.byId(this.client, id) : void 0
1436
+ );
1437
+ /** When the document was created. */
1438
+ createdAt = this.field("createdAt");
1439
+ /** When the document was last updated. */
1440
+ updatedAt = this.field("updatedAt");
1441
+ /** When the document was deleted, if it has been. */
1442
+ deletedAt = this.field("deletedAt");
1443
+ /**
1444
+ * The document's raw content (markdown source for markdown documents),
1445
+ * downloaded via a presigned export URL.
1446
+ */
1447
+ async content() {
1448
+ const { presigned_url } = unwrap(
1449
+ await this.client.storage.exportDocument({
1450
+ path: { document_id: this.id }
1451
+ })
1452
+ );
1453
+ const res = await fetch(presigned_url);
1454
+ if (!res.ok)
1455
+ throw new MacroApiError(res.status, {
1456
+ message: "failed to download document content"
1457
+ });
1458
+ return res.text();
1459
+ }
1460
+ /** Rename the document. */
1461
+ async rename(name) {
1462
+ await this.mutate(
1463
+ (c2) => c2.storage.editDocument({
1464
+ path: { document_id: this.id },
1465
+ body: { documentName: name }
1466
+ })
1467
+ );
1468
+ }
1469
+ /** Move the document into a project (or out of one, with `null`). */
1470
+ async move(project) {
1471
+ await this.mutate(
1472
+ (c2) => c2.storage.editDocument({
1473
+ path: { document_id: this.id },
1474
+ body: { projectId: project?.id ?? "" }
1475
+ })
1476
+ );
1477
+ }
1478
+ /**
1479
+ * Delete the document. Soft by default (reversible with {@link restore});
1480
+ * pass `permanent: true` to delete irreversibly.
1481
+ */
1482
+ async delete(opts) {
1483
+ await this.mutate(
1484
+ (c2) => opts?.permanent ? c2.storage.permanentlyDeleteDocument({
1485
+ path: { document_id: this.id }
1486
+ }) : c2.storage.deleteDocument({ path: { document_id: this.id } })
1487
+ );
1488
+ }
1489
+ /** Restore a soft-deleted document. */
1490
+ async restore() {
1491
+ await this.mutate(
1492
+ (c2) => c2.storage.revertDeleteDocument({ path: { document_id: this.id } })
1493
+ );
1494
+ }
1495
+ /**
1496
+ * Copy the document under a new name, optionally from a specific version.
1497
+ * Returns a handle to the new document.
1498
+ */
1499
+ async copy(opts) {
1500
+ const { data } = unwrap(
1501
+ await this.client.storage.copyDocument({
1502
+ path: { document_id: this.id },
1503
+ query: opts.versionId !== void 0 ? { version_id: opts.versionId } : void 0,
1504
+ body: { documentName: opts.name }
1505
+ })
1506
+ );
1507
+ return new _Document(this.client, data.documentMetadata.documentId);
1508
+ }
1509
+ /** The document's comment threads, each with its comments. */
1510
+ async comments() {
1511
+ const { data } = unwrap(
1512
+ await this.client.storage.getDocumentComments({
1513
+ path: { document_id: this.id }
1514
+ })
1515
+ );
1516
+ return data.map(({ thread, comments }) => ({
1517
+ thread,
1518
+ comments: comments.map((c2) => Comment.from(this.client, this, c2))
1519
+ }));
1520
+ }
1521
+ /**
1522
+ * Add a comment. Starts a new unanchored thread, or replies to an existing
1523
+ * one when `threadId` is given. Returns the created comment.
1524
+ */
1525
+ async comment(text, opts) {
1526
+ const { comments } = await this.mutate(
1527
+ (c2) => c2.storage.createComment({
1528
+ path: { document_id: this.id },
1529
+ body: { text, threadId: opts?.threadId ?? null }
1530
+ })
1531
+ );
1532
+ const created = comments.reduce(
1533
+ (a2, b2) => !a2 || b2.commentId > a2.commentId ? b2 : a2,
1534
+ void 0
1535
+ );
1536
+ if (!created)
1537
+ throw new MacroError("create comment returned an empty thread");
1538
+ return Comment.from(this.client, this, created);
1539
+ }
1540
+ /** The document's short id (used in compact links and branch names). */
1541
+ async shortId() {
1542
+ return unwrap(
1543
+ await this.client.storage.getDocumentShortId({
1544
+ path: { document_id: this.id }
1545
+ })
1546
+ );
1547
+ }
1548
+ /** Whether the document is shared with the owner's team, and which team. */
1549
+ async teamShare() {
1550
+ return unwrap(
1551
+ await this.client.storage.getDocumentTeamShare({
1552
+ path: { document_id: this.id }
1553
+ })
1554
+ );
1555
+ }
1556
+ /** Share the document with the owner's team, or unshare it. */
1557
+ async setTeamShare(shared) {
1558
+ await this.mutate(
1559
+ (c2) => c2.storage.setDocumentTeamShare({
1560
+ path: { document_id: this.id },
1561
+ body: { shareWithTeam: shared }
1562
+ })
1563
+ );
1564
+ }
1565
+ /** GitHub pull requests associated with the document. */
1566
+ async githubPullRequests() {
1567
+ const { pullRequests } = unwrap(
1568
+ await this.client.storage.getDocumentGithubPullRequests({
1569
+ path: { document_id: this.id }
1570
+ })
1571
+ );
1572
+ return pullRequests;
1573
+ }
1574
+ /** The git branch name derived for the document (task documents). */
1575
+ async branchName() {
1576
+ const { branchName } = unwrap(
1577
+ await this.client.storage.getDocumentBranchName({
1578
+ path: { document_id: this.id }
1579
+ })
1580
+ );
1581
+ return branchName;
1582
+ }
1583
+ /** The document's URL in the Macro web app. */
1584
+ webUrl() {
1585
+ return `${this.client.webAppUrl}/app/md/${this.id}`;
1586
+ }
1587
+ /** Search documents by name and content, most relevant first, auto-paginated. */
1588
+ static search = entitySearch({
1589
+ filters: { document_filters: {} },
1590
+ type: "document",
1591
+ make: (client, hit) => new _Document(client, hit.document_id)
1592
+ });
1593
+ toMention() {
1594
+ const loaded = this.detail.peek();
1595
+ return {
1596
+ tag: wrapXml("m-document-mention", {
1597
+ documentId: this.id,
1598
+ documentName: loaded?.documentName ?? "",
1599
+ blockName: loaded?.fileType ?? "md"
1600
+ }),
1601
+ mention: { entity_type: "document", entity_id: this.id }
1602
+ };
1603
+ }
1604
+ };
1605
+
1606
+ // src/events/hydrate/document.ts
1607
+ function hydrateDocumentEvent(client, event) {
1608
+ return M(event).with({ event_type: "document.created" }, ({ metadata }) => ({
1609
+ event_type: "document.created",
1610
+ metadata,
1611
+ document: Document.byId(client, metadata.document_id),
1612
+ owner: User.byId(client, metadata.owner),
1613
+ project: metadata.project_id ? Project.byId(client, metadata.project_id) : void 0
1614
+ })).with({ event_type: "document.updated" }, ({ metadata }) => ({
1615
+ event_type: "document.updated",
1616
+ metadata,
1617
+ document: Document.byId(client, metadata.document_id),
1618
+ owner: User.byId(client, metadata.owner),
1619
+ actor: metadata.actor_user_id ? User.byId(client, metadata.actor_user_id) : void 0,
1620
+ project: metadata.project_id ? Project.byId(client, metadata.project_id) : void 0,
1621
+ previousProject: metadata.previous_project_id ? Project.byId(client, metadata.previous_project_id) : void 0
1622
+ })).with({ event_type: "document.deleted" }, ({ metadata }) => ({
1623
+ event_type: "document.deleted",
1624
+ metadata,
1625
+ document: Document.byId(client, metadata.document_id),
1626
+ actor: metadata.actor_user_id ? User.byId(client, metadata.actor_user_id) : void 0,
1627
+ project: metadata.project_id ? Project.byId(client, metadata.project_id) : void 0
1628
+ })).with({ event_type: "document.content_uploaded" }, ({ metadata }) => ({
1629
+ event_type: "document.content_uploaded",
1630
+ metadata,
1631
+ document: Document.byId(client, metadata.document_id),
1632
+ owner: User.byId(client, metadata.owner)
1633
+ })).with({ event_type: "document.sync_content_updated" }, ({ metadata }) => ({
1634
+ event_type: "document.sync_content_updated",
1635
+ metadata,
1636
+ document: Document.byId(client, metadata.document_id)
1637
+ })).with({ event_type: "document.purged" }, ({ metadata }) => ({
1638
+ event_type: "document.purged",
1639
+ metadata,
1640
+ document: Document.byId(client, metadata.document_id)
1641
+ })).with({ event_type: "document.copied" }, ({ metadata }) => ({
1642
+ event_type: "document.copied",
1643
+ metadata,
1644
+ document: Document.byId(client, metadata.document_id),
1645
+ sourceDocument: Document.byId(client, metadata.source_document_id),
1646
+ owner: User.byId(client, metadata.owner),
1647
+ project: metadata.project_id ? Project.byId(client, metadata.project_id) : void 0
1648
+ })).with({ event_type: "document.interaction" }, ({ metadata }) => ({
1649
+ event_type: "document.interaction",
1650
+ metadata,
1651
+ document: Document.byId(client, metadata.document_id)
1652
+ })).exhaustive();
1653
+ }
1654
+
1655
+ // src/events/verify.ts
1656
+ async function verifySignature(opts) {
1657
+ const enc = new TextEncoder();
1658
+ const key = await crypto.subtle.importKey(
1659
+ "raw",
1660
+ enc.encode(opts.secret),
1661
+ { name: "HMAC", hash: "SHA-256" },
1662
+ false,
1663
+ ["sign"]
1664
+ );
1665
+ const digest = await crypto.subtle.sign(
1666
+ "HMAC",
1667
+ key,
1668
+ enc.encode(`${opts.timestamp}.${opts.rawBody}`)
1669
+ );
1670
+ const hexDigest = new Uint8Array(digest).toHex();
1671
+ return `v1=${hexDigest}` === opts.signature;
1672
+ }
1673
+
1674
+ // src/events/receiver.ts
1675
+ var VALIDATION_EVENT = "webhook.validation.test";
1676
+ function hydrate(client, event) {
1677
+ return M(event).with(
1678
+ { event_type: z.string.startsWith("document.") },
1679
+ (documentEvent) => hydrateDocumentEvent(client, documentEvent)
1680
+ ).with(
1681
+ { event_type: z.string.startsWith("channel.") },
1682
+ (channelEvent) => hydrateChannelEvent(client, channelEvent)
1683
+ ).exhaustive();
1684
+ }
1685
+ var MacroEvents = class {
1686
+ constructor(client, secret) {
1687
+ this.client = client;
1688
+ this.secret = secret;
1689
+ }
1690
+ client;
1691
+ secret;
1692
+ handlers = /* @__PURE__ */ new Map();
1693
+ /**
1694
+ * Subscribe to an event across all entities.
1695
+ *
1696
+ * @returns An unsubscribe function.
1697
+ */
1698
+ on(event, handler) {
1699
+ const set = this.handlers.get(event) ?? /* @__PURE__ */ new Set();
1700
+ set.add(handler);
1701
+ this.handlers.set(event, set);
1702
+ return () => set.delete(handler);
1703
+ }
1704
+ /**
1705
+ * Subscribe to @-mentions of the authenticated caller: `channel.mentioned`
1706
+ * deliveries whose mentioned entity is this bot (bot auth) or this user
1707
+ * (user auth).
1708
+ *
1709
+ * `channel.mentioned` deliveries cover every mention in channels the
1710
+ * webhook's workspace can access (its `ids` filter, like all channel
1711
+ * events, holds channel ids); picking out "me" happens here, client-side.
1712
+ * The caller's identity is resolved lazily (once) on the first delivery.
1713
+ * The webhook itself is registered separately and once, e.g.
1714
+ * `macro.webhooks.create({ filters: [{ events: ['channel.mentioned'] }],
1715
+ * … })`.
1716
+ *
1717
+ * @returns An unsubscribe function.
1718
+ */
1719
+ onSelfMention(handler) {
1720
+ return this.on("channel.mentioned", async (event) => {
1721
+ const mentioned = event.metadata.mentioned.entity_id.toLowerCase();
1722
+ if (mentioned !== (await this.client.myPrincipalId()).toLowerCase()) {
1723
+ return;
1724
+ }
1725
+ await handler(event);
1726
+ });
1727
+ }
1728
+ /**
1729
+ * Feed a raw delivery in: verifies the signature, parses, and dispatches to
1730
+ * matching handlers.
1731
+ *
1732
+ * @throws {MacroError} if the signature is missing or invalid.
1733
+ */
1734
+ async handle(rawBody, headers) {
1735
+ const ok = await verifySignature({
1736
+ secret: this.secret,
1737
+ timestamp: headers.timestamp ?? "",
1738
+ rawBody,
1739
+ signature: headers.signature ?? ""
1740
+ });
1741
+ if (!ok) throw new MacroError("invalid webhook signature");
1742
+ if (headers.event === VALIDATION_EVENT) return;
1743
+ const event = JSON.parse(rawBody);
1744
+ if (!("event_type" in event)) return;
1745
+ const handlers = this.handlers.get(event.event_type);
1746
+ if (!handlers || handlers.size === 0) return;
1747
+ const payload = hydrate(this.client, event);
1748
+ await Promise.all([...handlers].map((handler) => handler(payload)));
1749
+ }
1750
+ /**
1751
+ * A Fetch-style handler to mount at your webhook route.
1752
+ *
1753
+ * @example
1754
+ * app.post('/webhook', macro.events.webhook()); // Hono
1755
+ */
1756
+ webhook() {
1757
+ return async (req) => {
1758
+ await this.handle(await req.text(), {
1759
+ event: req.headers.get("x-macro-event") ?? void 0,
1760
+ eventId: req.headers.get("x-macro-event-id") ?? void 0,
1761
+ timestamp: req.headers.get("x-macro-timestamp") ?? void 0,
1762
+ signature: req.headers.get("x-macro-signature") ?? void 0
1763
+ });
1764
+ return new Response("ok");
1765
+ };
1766
+ }
1767
+ };
1768
+
1769
+ // src/local-portmap.ts
1770
+ import { execSync } from "node:child_process";
1771
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
1772
+ import { join } from "node:path";
1773
+ var portmapName = "portmap.json";
1774
+ function resolveLocalPortmap() {
1775
+ const path = findPortmap();
1776
+ if (!path) return void 0;
1777
+ try {
1778
+ return JSON.parse(readFileSync(path, "utf8"));
1779
+ } catch (error) {
1780
+ throw new Error(`failed to read Macro local port map ${path}`, {
1781
+ cause: error
1782
+ });
1783
+ }
1784
+ }
1785
+ function findPortmap() {
1786
+ const root = execSync("git rev-parse --show-toplevel", {
1787
+ encoding: "utf8"
1788
+ }).trim();
1789
+ const generated = join(root, "infra", "local", "generated");
1790
+ if (!existsSync(generated)) return void 0;
1791
+ for (const instance of readdirSync(generated)) {
1792
+ const path = join(generated, instance, portmapName);
1793
+ if (existsSync(path)) return path;
1794
+ }
1795
+ return void 0;
1796
+ }
1797
+
1798
+ // src/utils/client.ts
1799
+ var MacroClient = class {
1800
+ agentHarness;
1801
+ auth;
1802
+ cognition;
1803
+ contacts;
1804
+ email;
1805
+ notification;
1806
+ properties;
1807
+ search;
1808
+ storage;
1809
+ webAppUrl;
1810
+ wsVerify;
1811
+ events;
1812
+ /** Resolved authentication config (distinct from `auth`, the auth-service SDK). */
1813
+ authConfig;
1814
+ /** Resolved service base urls: env defaults, then the local-stack portmap,
1815
+ * then `opts.hosts` overrides. */
1816
+ hosts;
1817
+ /** The local stack's generated port map; only set when env is `local`. */
1818
+ localPortmap;
1819
+ requestedAs;
1820
+ selfBotRecord;
1821
+ selfPrincipal;
1822
+ constructor(opts) {
1823
+ const env = resolveEnv(opts);
1824
+ const localPortmap = env === "local" ? resolveLocalPortmap() : void 0;
1825
+ const hosts = { ...HOSTS[env], ...localPortmap?.hosts, ...opts.hosts };
1826
+ this.hosts = hosts;
1827
+ this.localPortmap = localPortmap;
1828
+ const envWebUrl = typeof process !== "undefined" ? process.env.MACRO_WEB_URL : void 0;
1829
+ this.webAppUrl = opts.webAppUrl ?? envWebUrl ?? localPortmap?.webAppUrl ?? WEB_APP_URLS[env];
1830
+ this.authConfig = resolveAuth(opts);
1831
+ this.requestedAs = opts.requestedAs;
1832
+ if (this.requestedAs && this.authConfig.type !== "bot") {
1833
+ throw new Error(
1834
+ "requestedAs() requires bot auth \u2014 a user token always acts as its own user"
1835
+ );
1836
+ }
1837
+ this.wsVerify = opts.wsVerify;
1838
+ this.agentHarness = new Sdk({
1839
+ client: this.makeClient(hosts["agent-harness"])
1840
+ });
1841
+ this.auth = new Sdk2({ client: this.makeClient(hosts.auth) });
1842
+ this.cognition = new Sdk3({
1843
+ client: this.makeClient(hosts.cognition)
1844
+ });
1845
+ this.contacts = new Sdk4({
1846
+ client: this.makeClient(hosts.contacts)
1847
+ });
1848
+ this.email = new Sdk5({ client: this.makeClient(hosts.email) });
1849
+ this.notification = new Sdk6({
1850
+ client: this.makeClient(hosts.notification)
1851
+ });
1852
+ this.properties = new Sdk7({
1853
+ client: this.makeClient(hosts.properties)
1854
+ });
1855
+ this.search = new Sdk8({ client: this.makeClient(hosts.search) });
1856
+ this.storage = new Sdk9({ client: this.makeClient(hosts.storage) });
1857
+ const envWebhookSecret = typeof process !== "undefined" ? process.env.MACRO_WEBHOOK_SECRET : void 0;
1858
+ const webhookSecret = opts.webhookSecret ?? envWebhookSecret;
1859
+ if (webhookSecret) {
1860
+ this.events = new MacroEvents(this, webhookSecret);
1861
+ }
1862
+ }
1863
+ /** Whether requests have a user identity accepted by acting-user endpoints. */
1864
+ hasActingUser() {
1865
+ return this.authConfig.type === "user" || this.requestedAs !== void 0;
1866
+ }
1867
+ /**
1868
+ * The authenticated bot's own record, fetched once and cached. Bot auth
1869
+ * only. Failed lookups are not cached, so a later call retries.
1870
+ */
1871
+ selfBot() {
1872
+ this.selfBotRecord ??= new BotsNamespace(this).me().catch((error) => {
1873
+ this.selfBotRecord = void 0;
1874
+ throw error;
1875
+ });
1876
+ return this.selfBotRecord;
1877
+ }
1878
+ /**
1879
+ * The authenticated caller's mentionable principal — `bot|<uuid>` for bot
1880
+ * auth, `macro|<email>` for user auth — fetched once and cached. Failed
1881
+ * lookups are not cached, so a later call retries.
1882
+ */
1883
+ myPrincipalId() {
1884
+ this.selfPrincipal ??= (this.authConfig.type === "bot" ? this.selfBot().then((bot) => `bot|${bot.id}`) : User.me(this).then((user) => user.id)).catch((error) => {
1885
+ this.selfPrincipal = void 0;
1886
+ throw error;
1887
+ });
1888
+ return this.selfPrincipal;
1889
+ }
1890
+ makeClient(baseUrl) {
1891
+ const c2 = createClient({ baseUrl });
1892
+ c2.interceptors.request.use(async (request) => {
1893
+ const source = this.authConfig.token;
1894
+ const tok = typeof source === "function" ? await source() : source;
1895
+ if (this.authConfig.type === "bot") {
1896
+ request.headers.set("x-macro-bot-token", tok);
1897
+ if (!request.headers.has("x-macro-bot-scope")) {
1898
+ request.headers.set(
1899
+ "x-macro-bot-scope",
1900
+ this.authConfig.scope ?? (this.requestedAs ? "user" : "team")
1901
+ );
1902
+ }
1903
+ if (this.requestedAs) {
1904
+ request.headers.set(
1905
+ "x-macro-bot-for-macro-user-id",
1906
+ this.requestedAs
1907
+ );
1908
+ }
1909
+ } else {
1910
+ if (tok.startsWith("mbot_")) {
1911
+ throw new Error(
1912
+ "bot API key passed as a user token \u2014 use auth: { type: 'bot', token } (or MACRO_BOT_TOKEN)"
1913
+ );
1914
+ }
1915
+ request.headers.set("Authorization", `Bearer ${tok}`);
1916
+ }
1917
+ return request;
1918
+ });
1919
+ return c2;
1920
+ }
1921
+ };
1922
+ function resolveEnv(opts) {
1923
+ if (opts.env) return opts.env;
1924
+ const fromEnv = typeof process !== "undefined" ? process.env.MACRO_ENV : void 0;
1925
+ if (!fromEnv) return "prod";
1926
+ if (!(fromEnv in HOSTS)) {
1927
+ throw new Error(
1928
+ `invalid MACRO_ENV "${fromEnv}" \u2014 expected local, dev, or prod`
1929
+ );
1930
+ }
1931
+ return fromEnv;
1932
+ }
1933
+ function resolveAuth(opts) {
1934
+ if (opts.auth) return opts.auth;
1935
+ if (opts.token) return { type: "user", token: opts.token };
1936
+ const envApiKey = typeof process !== "undefined" ? process.env.MACRO_API_KEY : void 0;
1937
+ const envBotToken = typeof process !== "undefined" ? process.env.MACRO_BOT_TOKEN : void 0;
1938
+ if (envApiKey && envBotToken) {
1939
+ throw new Error(
1940
+ "both MACRO_API_KEY and MACRO_BOT_TOKEN are set \u2014 pass auth to new Macro() to pick one"
1941
+ );
1942
+ }
1943
+ if (envBotToken) return { type: "bot", token: envBotToken };
1944
+ return {
1945
+ type: "user",
1946
+ token: envApiKey ?? (() => {
1947
+ throw new Error(
1948
+ "no Macro API token \u2014 set MACRO_API_KEY / MACRO_BOT_TOKEN or pass token/auth to new Macro()"
1949
+ );
1950
+ })
1951
+ };
1952
+ }
1953
+
1954
+ // src/utils/lazy.ts
1955
+ var Lazy = class {
1956
+ constructor(loader, seed) {
1957
+ this.loader = loader;
1958
+ this.value = seed;
1959
+ }
1960
+ loader;
1961
+ value;
1962
+ inflight;
1963
+ get() {
1964
+ if (this.value !== void 0) return Promise.resolve(this.value);
1965
+ this.inflight ??= this.loader().then((v2) => {
1966
+ this.value = v2;
1967
+ return v2;
1968
+ });
1969
+ return this.inflight;
1970
+ }
1971
+ /** The cached value, if already loaded — never triggers a fetch. */
1972
+ peek() {
1973
+ return this.value;
1974
+ }
1975
+ /** Drop the cached value so the next read refetches. */
1976
+ clear() {
1977
+ this.value = void 0;
1978
+ this.inflight = void 0;
1979
+ }
1980
+ };
1981
+
1982
+ // src/utils/pagination.ts
1983
+ async function* paginate(fetchPage) {
1984
+ let cursor;
1985
+ do {
1986
+ const page = await fetchPage(cursor);
1987
+ yield* page.items;
1988
+ cursor = page.nextCursor ?? void 0;
1989
+ } while (cursor);
1990
+ }
1991
+
1992
+ // src/utils/unwrap.ts
1993
+ var MacroError = class extends Error {
1994
+ constructor(message) {
1995
+ super(message);
1996
+ this.name = "MacroError";
1997
+ }
1998
+ };
1999
+ var MacroApiError = class extends MacroError {
2000
+ constructor(status, data) {
2001
+ super(`Macro API error ${status}`);
2002
+ this.status = status;
2003
+ this.data = data;
2004
+ this.name = "MacroApiError";
2005
+ }
2006
+ status;
2007
+ data;
2008
+ };
2009
+ var MacroNotFoundError = class extends MacroError {
2010
+ constructor(message) {
2011
+ super(message);
2012
+ this.name = "MacroNotFoundError";
2013
+ }
2014
+ };
2015
+ function unwrap(res) {
2016
+ if (res.error !== void 0)
2017
+ throw new MacroApiError(res.response?.status ?? 0, res.error);
2018
+ return res.data;
2019
+ }
2020
+
2021
+ // src/entities/agent-sessions/agent-session.ts
2022
+ var AgentSession = class _AgentSession extends MacroEntity {
2023
+ /** A handle to an agent session by id. Details load on first access. */
2024
+ static byId(client, id) {
2025
+ return new _AgentSession(client, id);
2026
+ }
2027
+ /** Create a managed session, optionally delivering its first prompt. */
2028
+ static async createManaged(client, opts) {
2029
+ const { session } = unwrap(
2030
+ await client.agentHarness.createAgentSession({
2031
+ body: { prompt: opts?.prompt }
2032
+ })
2033
+ );
2034
+ return new _AgentSession(client, session.id, session);
2035
+ }
2036
+ async fetch() {
2037
+ return unwrap(
2038
+ await this.client.agentHarness.getAgentSession({
2039
+ path: { session_id: this.id }
2040
+ })
2041
+ );
2042
+ }
2043
+ /** The session's user-facing display name. */
2044
+ name = this.field("name");
2045
+ /** The model currently configured for the session. */
2046
+ model = this.field("model");
2047
+ /** The agent harness implementation serving the session. */
2048
+ harness = this.field("harness");
2049
+ /** The repository the agent works with, when one was supplied. */
2050
+ repoUrl = this.field("repoUrl");
2051
+ /** The directory in which the agent harness runs. */
2052
+ workspace = this.field("workspace");
2053
+ /** The session's latest runtime status. */
2054
+ status = this.field("status");
2055
+ /** Compute tier of the managed sandbox. */
2056
+ sandboxSize = this.field("sandboxSize");
2057
+ /** When the session was created. */
2058
+ createdAt = this.field("createdAt");
2059
+ /** When the session was last modified. */
2060
+ modifiedAt = this.field("modifiedAt");
2061
+ /** Rename this session. */
2062
+ async rename(name) {
2063
+ await this.mutate(
2064
+ (client) => client.agentHarness.renameAgentSession({
2065
+ path: { session_id: this.id },
2066
+ body: { name }
2067
+ })
2068
+ );
2069
+ }
2070
+ /** Resize this session's sandbox and remember the size as the owner's default. */
2071
+ async setSandboxSize(size) {
2072
+ const { size: next } = await this.mutate(
2073
+ (client) => client.agentHarness.putAgentSessionSandboxSize({
2074
+ path: { session_id: this.id },
2075
+ body: { size }
2076
+ })
2077
+ );
2078
+ return next;
2079
+ }
2080
+ /** The caller's default sandbox size for new `@coder` sessions. */
2081
+ static async defaultSandboxSize(client) {
2082
+ return unwrap(await client.agentHarness.getAgentSandboxSize()).size;
2083
+ }
2084
+ /** Set the caller's default sandbox size for the next `@coder` mention. */
2085
+ static async setDefaultSandboxSize(client, size) {
2086
+ return unwrap(
2087
+ await client.agentHarness.putAgentSandboxSize({
2088
+ body: { size }
2089
+ })
2090
+ ).size;
2091
+ }
2092
+ /** Send a prompt or lifecycle operation to the live agent session. */
2093
+ async control(action) {
2094
+ return this.mutate(
2095
+ (client) => client.agentHarness.controlAgentSession({
2096
+ path: { session_id: this.id },
2097
+ body: action
2098
+ })
2099
+ );
2100
+ }
2101
+ /** Read the complete raw protocol log for this session. */
2102
+ async log() {
2103
+ return unwrap(
2104
+ await this.client.agentHarness.getAgentSessionLog({
2105
+ path: { session_id: this.id }
2106
+ })
2107
+ );
2108
+ }
2109
+ /** Delete this session and any live resources it owns. */
2110
+ async delete() {
2111
+ await this.mutate(
2112
+ (client) => client.agentHarness.deleteAgentSession({
2113
+ path: { session_id: this.id }
2114
+ })
2115
+ );
2116
+ }
2117
+ };
2118
+
2119
+ // src/entities/agent-sessions/namespace.ts
2120
+ var AgentSessionNamespace = class {
2121
+ constructor(client) {
2122
+ this.client = client;
2123
+ }
2124
+ client;
2125
+ /** A handle to an agent session by id. Details load on first access. */
2126
+ byId(id) {
2127
+ return AgentSession.byId(this.client, id);
2128
+ }
2129
+ /** Create a managed agent session. */
2130
+ createManaged(opts) {
2131
+ return AgentSession.createManaged(this.client, opts);
2132
+ }
2133
+ /** The caller's default sandbox size for new `@coder` sessions. */
2134
+ defaultSandboxSize() {
2135
+ return AgentSession.defaultSandboxSize(this.client);
2136
+ }
2137
+ /** Set the caller's default sandbox size for the next `@coder` mention. */
2138
+ setDefaultSandboxSize(size) {
2139
+ return AgentSession.setDefaultSandboxSize(this.client, size);
2140
+ }
2141
+ };
2142
+
2143
+ // src/entities/calls/call-record.ts
2144
+ var CallRecord = class _CallRecord extends FavoritableEntity {
2145
+ /** Favorites identify call records as `call`. */
2146
+ entityType = "call";
2147
+ async fetch() {
2148
+ return unwrap(
2149
+ await this.client.storage.getCallRecord({ path: { call_id: this.id } })
2150
+ );
2151
+ }
2152
+ /** A handle to a call record by id. Details load on first access. */
2153
+ static byId(client, id) {
2154
+ return new _CallRecord(client, id);
2155
+ }
2156
+ /** The call's display name (user-supplied or AI-generated; unset while active). */
2157
+ name = this.field("customName");
2158
+ /** The channel the call belongs to. */
2159
+ channel = this.mappedField(
2160
+ "channelId",
2161
+ (id) => Channel.byId(this.client, id)
2162
+ );
2163
+ /** The display name of the channel the call belongs to. */
2164
+ channelName = this.field("channelName");
2165
+ /** The user who started the call. */
2166
+ creator = this.mappedField(
2167
+ "createdBy",
2168
+ (id) => User.byId(this.client, id)
2169
+ );
2170
+ /** Whether the call is still in progress. */
2171
+ isActive = this.field("isActive");
2172
+ /** The call's status (undefined until set). */
2173
+ status = this.field("status");
2174
+ /** The realtime room the call runs in. */
2175
+ roomName = this.field("roomName");
2176
+ /** When the call started. */
2177
+ startedAt = this.field("startedAt");
2178
+ /** When the call ended (undefined if still active). */
2179
+ endedAt = this.field("endedAt");
2180
+ /** Call duration in milliseconds (undefined if still active). */
2181
+ durationMs = this.field("durationMs");
2182
+ /** AI-generated summary of the call, once summarization has run. */
2183
+ summary = this.field("summary");
2184
+ /** Transcript segments, ordered by sequence number. */
2185
+ transcript = this.field("transcript");
2186
+ /** Participants, both active and historic. */
2187
+ participants = this.field("participants");
2188
+ /** Whether the recording is shared with the team. */
2189
+ shareWithTeam = this.field("shareWithTeam");
2190
+ /** URL of the call recording, once available. */
2191
+ recordingUrl = this.field("recordingUrl");
2192
+ /** URL of the recording preview (thumbnail), once available. */
2193
+ recordingPreviewUrl = this.field("recordingPreviewUrl");
2194
+ /** When the recording started, if it was recorded. */
2195
+ recordingStartedAt = this.field("recordingStartedAt");
2196
+ /** Rename the call or clear the custom name. */
2197
+ async rename(name) {
2198
+ await this.mutate(
2199
+ (c2) => c2.storage.editCallRecord({
2200
+ path: { call_id: this.id },
2201
+ body: { customName: name ?? "" }
2202
+ })
2203
+ );
2204
+ }
2205
+ /** Delete the call record. */
2206
+ async delete() {
2207
+ await this.mutate(
2208
+ (c2) => c2.storage.deleteCallRecord({ path: { call_id: this.id } })
2209
+ );
2210
+ }
2211
+ /** Search calls by name and transcript, most relevant first, auto-paginated. */
2212
+ static search = entitySearch({
2213
+ filters: { call_filters: {} },
2214
+ type: "call",
2215
+ make: (client, hit) => new _CallRecord(client, hit.call_id)
2216
+ });
2217
+ };
2218
+
2219
+ // src/entities/calls/namespace.ts
2220
+ var CallRecordNamespace = class {
2221
+ constructor(client) {
2222
+ this.client = client;
2223
+ }
2224
+ client;
2225
+ byId(id) {
2226
+ return CallRecord.byId(this.client, id);
2227
+ }
2228
+ search(query, opts) {
2229
+ return CallRecord.search(this.client, query, opts);
2230
+ }
2231
+ };
2232
+
2233
+ // src/entities/channels/namespace.ts
2234
+ var ChannelNamespace = class {
2235
+ constructor(client) {
2236
+ this.client = client;
2237
+ }
2238
+ client;
2239
+ byId(id) {
2240
+ return Channel.byId(this.client, id);
2241
+ }
2242
+ async dm(recipient) {
2243
+ return Channel.dm(this.client, recipient);
2244
+ }
2245
+ /** Open (creating if needed) the private group channel with a set of users. */
2246
+ async private(recipients) {
2247
+ return Channel.private(this.client, recipients);
2248
+ }
2249
+ /** Create a channel. The caller becomes the owner. */
2250
+ async create(opts) {
2251
+ return Channel.create(this.client, opts);
2252
+ }
2253
+ /** All channels the authenticated user is a member of. */
2254
+ async list() {
2255
+ const { items } = unwrap(await this.client.storage.getChannels());
2256
+ return items.map((ch) => Channel.byId(this.client, ch.id.toString()));
2257
+ }
2258
+ /**
2259
+ * Search channels by name (client-side fuzzy filter on the full channel list)
2260
+ * or by content (server-side unified search).
2261
+ */
2262
+ async *search(query, opts) {
2263
+ if (!opts?.searchOn || opts.searchOn === "name") {
2264
+ const { items } = unwrap(await this.client.storage.getChannels());
2265
+ const lower = query.toLowerCase();
2266
+ for (const ch of items) {
2267
+ if (ch.name?.toLowerCase().includes(lower)) {
2268
+ yield Channel.byId(this.client, ch.id.toString());
2269
+ }
2270
+ }
2271
+ } else {
2272
+ yield* Channel.search(this.client, query, opts);
2273
+ }
2274
+ }
2275
+ };
2276
+
2277
+ // src/entities/chats/chat.ts
2278
+ var Chat = class _Chat extends PropertiedEntity {
2279
+ /** Favorites identify chats as `chat`. */
2280
+ entityType = "chat";
2281
+ /** The properties service identifies chats as `CHAT`. */
2282
+ propertyEntityType = "CHAT";
2283
+ async fetch() {
2284
+ const { chat } = unwrap(
2285
+ await this.client.cognition.getChat({ path: { chat_id: this.id } })
2286
+ );
2287
+ return chat;
2288
+ }
2289
+ /** A handle to a chat by id. Details load on first access. */
2290
+ static byId(client, id) {
2291
+ return new _Chat(client, id);
2292
+ }
2293
+ /** Create a chat, optionally named and attached to a project. */
2294
+ static async create(client, opts) {
2295
+ const { id } = unwrap(
2296
+ await client.cognition.createChat({
2297
+ body: {
2298
+ name: opts?.name ?? null,
2299
+ projectId: opts?.project?.id ?? null
2300
+ }
2301
+ })
2302
+ );
2303
+ return new _Chat(client, id);
2304
+ }
2305
+ /** The chat's display name. */
2306
+ name = this.field("name");
2307
+ /** The model used to generate the chat (`provider/model` id), if set. */
2308
+ model = this.field("model");
2309
+ /** The project this chat belongs to, if any. */
2310
+ project = this.mappedField(
2311
+ "projectId",
2312
+ (id) => id ? Project.byId(this.client, id) : void 0
2313
+ );
2314
+ /** When the chat was created. */
2315
+ createdAt = this.field("createdAt");
2316
+ /** When the chat was last updated. */
2317
+ updatedAt = this.field("updatedAt");
2318
+ /** The messages in the chat, with their attachments. */
2319
+ messages = this.field("messages");
2320
+ /** Rename the chat. */
2321
+ async rename(name) {
2322
+ await this.mutate(
2323
+ (c2) => c2.cognition.patchChat({
2324
+ path: { chat_id: this.id },
2325
+ body: { name }
2326
+ })
2327
+ );
2328
+ }
2329
+ /**
2330
+ * Delete the chat. Soft by default (reversible with {@link restore});
2331
+ * pass `permanent: true` to delete irreversibly.
2332
+ */
2333
+ async delete(opts) {
2334
+ await this.mutate(
2335
+ (c2) => opts?.permanent ? c2.cognition.permanentlyDeleteChat({ path: { chat_id: this.id } }) : c2.cognition.deleteChat({ path: { chat_id: this.id } })
2336
+ );
2337
+ }
2338
+ /** Copy the chat, returning a handle to the new copy. */
2339
+ async copy() {
2340
+ const { id } = await this.mutate(
2341
+ (c2) => c2.cognition.copyChat({ path: { chat_id: this.id } })
2342
+ );
2343
+ return new _Chat(this.client, id);
2344
+ }
2345
+ /** Restore a soft-deleted chat. */
2346
+ async restore() {
2347
+ await this.mutate(
2348
+ (c2) => c2.cognition.revertDeleteChat({ path: { chat_id: this.id } })
2349
+ );
2350
+ }
2351
+ /** The chat's conversation history: titled records of messages with attachment ids. */
2352
+ async history() {
2353
+ const { conversation } = unwrap(
2354
+ await this.client.cognition.getChatHistoryHandler({
2355
+ path: { chat_id: this.id }
2356
+ })
2357
+ );
2358
+ return conversation;
2359
+ }
2360
+ /** The chat's URL in the Macro web app. */
2361
+ webUrl() {
2362
+ return `${this.client.webAppUrl}/app/chat/${this.id}`;
2363
+ }
2364
+ /** Search chats by name and content, most relevant first, auto-paginated. */
2365
+ static search = entitySearch({
2366
+ filters: { chat_filters: {} },
2367
+ type: "chat",
2368
+ make: (client, hit) => new _Chat(client, hit.chat_id)
2369
+ });
2370
+ toMention() {
2371
+ return {
2372
+ tag: wrapXml("m-document-mention", {
2373
+ documentId: this.id,
2374
+ documentName: this.detail.peek()?.name ?? "",
2375
+ blockName: "chat",
2376
+ blockParams: {}
2377
+ }),
2378
+ mention: { entity_type: "chat", entity_id: this.id }
2379
+ };
2380
+ }
2381
+ };
2382
+
2383
+ // src/entities/chats/namespace.ts
2384
+ var ChatNamespace = class {
2385
+ constructor(client) {
2386
+ this.client = client;
2387
+ }
2388
+ client;
2389
+ byId(id) {
2390
+ return Chat.byId(this.client, id);
2391
+ }
2392
+ create(opts) {
2393
+ return Chat.create(this.client, opts);
2394
+ }
2395
+ search(query, opts) {
2396
+ return Chat.search(this.client, query, opts);
2397
+ }
2398
+ };
2399
+
2400
+ // src/entities/teams/team.ts
2401
+ var Team = class _Team extends MacroEntity {
2402
+ async fetch() {
2403
+ const teams = unwrap(await this.client.auth.getUserTeams());
2404
+ const team = teams.find((t2) => t2.id === this.id);
2405
+ if (!team) throw new MacroNotFoundError(`team ${this.id} not found`);
2406
+ return team;
2407
+ }
2408
+ /** A handle to a team by id. Details load on first access. */
2409
+ static byId(client, id) {
2410
+ return new _Team(client, id);
2411
+ }
2412
+ /** The caller's current team. */
2413
+ static async current(client) {
2414
+ const res = unwrap(await client.auth.getTeam());
2415
+ if (!res) throw new MacroNotFoundError("caller has no current team");
2416
+ return new _Team(client, res.team.id, res.team);
2417
+ }
2418
+ /** The teams the caller belongs to. */
2419
+ static async list(client) {
2420
+ const teams = unwrap(await client.auth.getUserTeams());
2421
+ return teams.map((t2) => new _Team(client, t2.id, t2));
2422
+ }
2423
+ /** The team's display name. */
2424
+ name = this.field("name");
2425
+ /** The team's slug (its URL identifier). */
2426
+ slug = this.field("slug");
2427
+ /**
2428
+ * The team's default link-share scope for newly shared items, or null when
2429
+ * link sharing is off by default.
2430
+ */
2431
+ defaultLinkShare = this.field("default_link_share");
2432
+ /** The user who owns the team. */
2433
+ owner = this.mappedField(
2434
+ "owner_id",
2435
+ (id) => User.byId(this.client, id)
2436
+ );
2437
+ /**
2438
+ * The team's members, with their roles. The API only exposes members for
2439
+ * the caller's current team, so this rejects for any other team.
2440
+ */
2441
+ async members() {
2442
+ const res = unwrap(await this.client.auth.getTeam());
2443
+ if (!res || res.team.id !== this.id)
2444
+ throw new MacroError(
2445
+ "members are only available for the current team (see Team.current)"
2446
+ );
2447
+ return res.members.map((m2) => ({
2448
+ user: User.byId(this.client, m2.user_id),
2449
+ role: m2.role
2450
+ }));
2451
+ }
2452
+ };
2453
+
2454
+ // src/entities/crm/comment.ts
2455
+ var CrmComment = class _CrmComment {
2456
+ constructor(client, id, record) {
2457
+ this.client = client;
2458
+ this.id = id;
2459
+ this.record = record;
2460
+ }
2461
+ client;
2462
+ id;
2463
+ record;
2464
+ /** Wrap a record already in hand (e.g. from a list or create response). */
2465
+ static from(client, record) {
2466
+ return new _CrmComment(client, record.commentId, record);
2467
+ }
2468
+ /** The comment body (markdown). */
2469
+ get text() {
2470
+ return this.record.text;
2471
+ }
2472
+ /** The id of the thread this comment belongs to. */
2473
+ get threadId() {
2474
+ return this.record.threadId;
2475
+ }
2476
+ /** Macro user id of the comment author. */
2477
+ get owner() {
2478
+ return this.record.owner;
2479
+ }
2480
+ /** Macro user id of the actual sender, when distinct from {@link owner}. */
2481
+ get sender() {
2482
+ return this.record.sender ?? void 0;
2483
+ }
2484
+ /** Explicit ordering within the thread, if set. */
2485
+ get order() {
2486
+ return this.record.order ?? void 0;
2487
+ }
2488
+ /** Arbitrary client metadata attached to the comment. */
2489
+ get metadata() {
2490
+ return this.record.metadata;
2491
+ }
2492
+ /** When the comment was created. */
2493
+ get createdAt() {
2494
+ return this.record.createdAt;
2495
+ }
2496
+ /** When the comment was last updated. */
2497
+ get updatedAt() {
2498
+ return this.record.updatedAt;
2499
+ }
2500
+ /** When the comment was soft-deleted, if ever. */
2501
+ get deletedAt() {
2502
+ return this.record.deletedAt ?? void 0;
2503
+ }
2504
+ /** Replace this comment's text (markdown). */
2505
+ async edit(text) {
2506
+ this.record = unwrap(
2507
+ await this.client.storage.editCrmComment({
2508
+ path: { comment_id: this.id },
2509
+ body: { text }
2510
+ })
2511
+ );
2512
+ return this;
2513
+ }
2514
+ /** Soft-delete this comment; the thread goes too when it was the last live one. */
2515
+ async delete() {
2516
+ return unwrap(
2517
+ await this.client.storage.deleteCrmComment({
2518
+ path: { comment_id: this.id }
2519
+ })
2520
+ );
2521
+ }
2522
+ };
2523
+
2524
+ // src/entities/crm/contact.ts
2525
+ var Contact = class _Contact extends FavoritableEntity {
2526
+ /** Favorites identify CRM contacts as `crm_contact`. */
2527
+ entityType = "crm_contact";
2528
+ async fetch() {
2529
+ return unwrap(
2530
+ await this.client.storage.getContact({
2531
+ path: { contact_id: this.id }
2532
+ })
2533
+ );
2534
+ }
2535
+ /** A handle to a CRM contact by id. Details load on first access. */
2536
+ static byId(client, id) {
2537
+ return new _Contact(client, id);
2538
+ }
2539
+ /** Build a contact from an API record (pre-seeded, no fetch). */
2540
+ static from(client, data) {
2541
+ return new _Contact(client, data.id, data);
2542
+ }
2543
+ /** The contact's display name, if one has been observed. */
2544
+ name = this.field("name");
2545
+ /** The contact's email address. */
2546
+ email = this.field("email");
2547
+ /** The CRM company this contact belongs to. */
2548
+ company = this.mappedField(
2549
+ "companyId",
2550
+ (id) => Company.byId(this.client, id)
2551
+ );
2552
+ /** Whether the contact is hidden from CRM listings. */
2553
+ hidden = this.field("hidden");
2554
+ /** When the contact was first created in the CRM. */
2555
+ createdAt = this.field("createdAt");
2556
+ /** When the contact was last updated. */
2557
+ updatedAt = this.field("updatedAt");
2558
+ /** When the team first interacted with this contact. */
2559
+ firstInteraction = this.field("firstInteraction");
2560
+ /** When the team last interacted with this contact. */
2561
+ lastInteraction = this.field("lastInteraction");
2562
+ /** Hide the contact from CRM listings. Display-only; reversible with {@link unhide}. */
2563
+ async hide() {
2564
+ await this.setHidden(true);
2565
+ }
2566
+ /** Un-hide the contact, restoring it to CRM listings. */
2567
+ async unhide() {
2568
+ await this.setHidden(false);
2569
+ }
2570
+ async setHidden(hidden) {
2571
+ await this.mutate(
2572
+ (c2) => c2.storage.setContactHidden({
2573
+ path: { contact_id: this.id },
2574
+ body: { hidden }
2575
+ })
2576
+ );
2577
+ }
2578
+ /** Rename the contact for the caller's current team. */
2579
+ async rename(name) {
2580
+ await this.mutate(
2581
+ (c2) => c2.storage.setCrmContactName({
2582
+ path: { contact_id: this.id },
2583
+ body: { name }
2584
+ })
2585
+ );
2586
+ }
2587
+ /** The comment threads attached to this contact, with comments oldest first. */
2588
+ async comments() {
2589
+ const threads = unwrap(
2590
+ await this.client.storage.listCrmComments({
2591
+ path: { entity_type: "crm_contact", entity_id: this.id }
2592
+ })
2593
+ );
2594
+ return threads.map(({ thread, comments }) => ({
2595
+ thread,
2596
+ comments: comments.map((c2) => CrmComment.from(this.client, c2))
2597
+ }));
2598
+ }
2599
+ /** Add a comment: starts a new thread unless `body.threadId` targets an existing one. */
2600
+ async comment(body) {
2601
+ const { comments } = await this.mutate(
2602
+ (c2) => c2.storage.createCrmComment({
2603
+ path: { entity_type: "crm_contact", entity_id: this.id },
2604
+ body
2605
+ })
2606
+ );
2607
+ const created = comments.reduce(
2608
+ (a2, b2) => !a2 || b2.createdAt > a2.createdAt ? b2 : a2,
2609
+ void 0
2610
+ );
2611
+ if (!created)
2612
+ throw new MacroError("create comment returned an empty thread");
2613
+ return CrmComment.from(this.client, created);
2614
+ }
2615
+ /** Replace a comment's text (markdown). */
2616
+ async editComment(comment, text) {
2617
+ const record = await this.mutate(
2618
+ (c2) => c2.storage.editCrmComment({
2619
+ path: { comment_id: comment.id },
2620
+ body: { text }
2621
+ })
2622
+ );
2623
+ return CrmComment.from(this.client, record);
2624
+ }
2625
+ /** Soft-delete a comment; the thread goes too when it was the last live one. */
2626
+ async deleteComment(comment) {
2627
+ return this.mutate(
2628
+ (c2) => c2.storage.deleteCrmComment({ path: { comment_id: comment.id } })
2629
+ );
2630
+ }
2631
+ };
2632
+
2633
+ // src/entities/crm/company.ts
2634
+ var Company = class _Company extends PropertiedEntity {
2635
+ /** Favorites identify CRM companies as `crm_company`. */
2636
+ entityType = "crm_company";
2637
+ /** The properties service identifies CRM companies as `COMPANY`. */
2638
+ propertyEntityType = "COMPANY";
2639
+ async fetch() {
2640
+ return unwrap(
2641
+ await this.client.storage.getCompany({
2642
+ path: { company_id: this.id }
2643
+ })
2644
+ );
2645
+ }
2646
+ /** A handle to a CRM company by id. Details load on first access. */
2647
+ static byId(client, id) {
2648
+ return new _Company(client, id);
2649
+ }
2650
+ /** Build a company from an API record (pre-seeded, no fetch). */
2651
+ static from(client, data) {
2652
+ return new _Company(client, data.id, data);
2653
+ }
2654
+ /** The company's display name, if resolved. */
2655
+ name = this.field("name");
2656
+ /** The company's display description, if any. */
2657
+ description = this.field("description");
2658
+ /** Whether the company is hidden from CRM listings. */
2659
+ hidden = this.field("hidden");
2660
+ /** Whether email sync is enabled for this company. */
2661
+ emailSync = this.field("emailSync");
2662
+ /** The team that owns this company. */
2663
+ team = this.mappedField(
2664
+ "teamId",
2665
+ (id) => Team.byId(this.client, id)
2666
+ );
2667
+ /** When the company was first created in the CRM. */
2668
+ createdAt = this.field("createdAt");
2669
+ /** When the company was last updated. */
2670
+ updatedAt = this.field("updatedAt");
2671
+ /** The company's primary domain (e.g. `acme.com`), if any. */
2672
+ async domain() {
2673
+ const { domains } = await this.detail.get();
2674
+ return domains[0]?.domain;
2675
+ }
2676
+ /** All domains associated with the company, primary first. */
2677
+ async domains() {
2678
+ const { domains } = await this.detail.get();
2679
+ return domains.map((d2) => d2.domain);
2680
+ }
2681
+ /** The contacts attached to this company (hidden ones filtered for non-admins). */
2682
+ async contacts() {
2683
+ const records = unwrap(
2684
+ await this.client.storage.listCompanyContacts({
2685
+ path: { company_id: this.id }
2686
+ })
2687
+ );
2688
+ return records.map((r2) => Contact.from(this.client, r2));
2689
+ }
2690
+ /** Search CRM companies by name/domain, most relevant first, auto-paginated. */
2691
+ static search = entitySearch({
2692
+ filters: { crm_company_filters: {} },
2693
+ type: "company",
2694
+ includeCrm: true,
2695
+ make: (client, hit) => new _Company(client, hit.id)
2696
+ });
2697
+ /**
2698
+ * Hide the company from CRM listings: disables email sync and soft-hides
2699
+ * its contacts. Reversible with {@link unhide}.
2700
+ */
2701
+ async hide() {
2702
+ await this.setHidden(true);
2703
+ }
2704
+ /** Un-hide the company, restoring it and its contacts to CRM listings. */
2705
+ async unhide() {
2706
+ await this.setHidden(false);
2707
+ }
2708
+ async setHidden(hidden) {
2709
+ await this.mutate(
2710
+ (c2) => c2.storage.setCompanyHidden({
2711
+ path: { company_id: this.id },
2712
+ body: { hidden }
2713
+ })
2714
+ );
2715
+ }
2716
+ /**
2717
+ * Enable or disable team-wide email sync for this company. Rejects with 409
2718
+ * when enabling on a hidden company — {@link unhide} first.
2719
+ */
2720
+ async setEmailSync(enabled) {
2721
+ await this.mutate(
2722
+ (c2) => c2.storage.setEmailSync({
2723
+ path: { company_id: this.id },
2724
+ body: { email_sync: enabled }
2725
+ })
2726
+ );
2727
+ }
2728
+ /** Rename the company for the caller's current team. */
2729
+ async rename(name) {
2730
+ await this.mutate(
2731
+ (c2) => c2.storage.setCrmCompanyName({
2732
+ path: { company_id: this.id },
2733
+ body: { name }
2734
+ })
2735
+ );
2736
+ }
2737
+ /** Create a contact under this company. */
2738
+ async createContact(opts) {
2739
+ const contact = await this.mutate(
2740
+ (c2) => c2.storage.createCrmContact({
2741
+ path: { company_id: this.id },
2742
+ body: opts
2743
+ })
2744
+ );
2745
+ return Contact.from(this.client, contact);
2746
+ }
2747
+ /** The comment threads attached to this company, with comments oldest first. */
2748
+ async comments() {
2749
+ const threads = unwrap(
2750
+ await this.client.storage.listCrmComments({
2751
+ path: { entity_type: "crm_company", entity_id: this.id }
2752
+ })
2753
+ );
2754
+ return threads.map(({ thread, comments }) => ({
2755
+ thread,
2756
+ comments: comments.map((c2) => CrmComment.from(this.client, c2))
2757
+ }));
2758
+ }
2759
+ /** Add a comment: starts a new thread unless `body.threadId` targets an existing one. */
2760
+ async comment(body) {
2761
+ const { comments } = await this.mutate(
2762
+ (c2) => c2.storage.createCrmComment({
2763
+ path: { entity_type: "crm_company", entity_id: this.id },
2764
+ body
2765
+ })
2766
+ );
2767
+ const created = comments.reduce(
2768
+ (a2, b2) => !a2 || b2.createdAt > a2.createdAt ? b2 : a2,
2769
+ void 0
2770
+ );
2771
+ if (!created)
2772
+ throw new MacroError("create comment returned an empty thread");
2773
+ return CrmComment.from(this.client, created);
2774
+ }
2775
+ /** Replace a comment's text (markdown). */
2776
+ async editComment(comment, text) {
2777
+ const record = await this.mutate(
2778
+ (c2) => c2.storage.editCrmComment({
2779
+ path: { comment_id: comment.id },
2780
+ body: { text }
2781
+ })
2782
+ );
2783
+ return CrmComment.from(this.client, record);
2784
+ }
2785
+ /** Soft-delete a comment; the thread goes too when it was the last live one. */
2786
+ async deleteComment(comment) {
2787
+ return this.mutate(
2788
+ (c2) => c2.storage.deleteCrmComment({ path: { comment_id: comment.id } })
2789
+ );
2790
+ }
2791
+ };
2792
+
2793
+ // src/entities/crm/namespace.ts
2794
+ var CrmNamespace = class {
2795
+ constructor(client) {
2796
+ this.client = client;
2797
+ }
2798
+ client;
2799
+ /** A handle to a CRM company by id. */
2800
+ companyById(id) {
2801
+ return Company.byId(this.client, id);
2802
+ }
2803
+ /** A handle to a CRM contact by id. */
2804
+ contactById(id) {
2805
+ return Contact.byId(this.client, id);
2806
+ }
2807
+ /** Resolve a CRM contact by email in the caller's current team, if present. */
2808
+ async contactByEmail(email) {
2809
+ const { contact } = unwrap(
2810
+ await this.client.storage.getContactByEmail({
2811
+ query: { email }
2812
+ })
2813
+ );
2814
+ return contact ? Contact.from(this.client, contact) : void 0;
2815
+ }
2816
+ /** Create a CRM company for the caller's current team. */
2817
+ async createCompany(opts) {
2818
+ return Company.from(
2819
+ this.client,
2820
+ unwrap(await this.client.storage.createCrmCompany({ body: opts }))
2821
+ );
2822
+ }
2823
+ /** The caller's current team's CRM settings. */
2824
+ async settings() {
2825
+ return unwrap(await this.client.storage.getCrmTeamSettings());
2826
+ }
2827
+ /** Partially update the caller's current team's CRM settings. */
2828
+ async updateSettings(settings) {
2829
+ return unwrap(
2830
+ await this.client.storage.putCrmTeamSettings({ body: settings })
2831
+ );
2832
+ }
2833
+ /** Search CRM companies by name/domain, most relevant first, auto-paginated. */
2834
+ searchCompanies(query) {
2835
+ return Company.search(this.client, query);
2836
+ }
2837
+ };
2838
+
2839
+ // src/entities/documents/system-skill.ts
2840
+ var SystemSkill = class _SystemSkill {
2841
+ constructor(id, name) {
2842
+ this.id = id;
2843
+ this.name = name;
2844
+ }
2845
+ id;
2846
+ name;
2847
+ /** The built-in system skills, in display order. */
2848
+ static async list(client) {
2849
+ const { skills } = unwrap(await client.storage.getSystemSkillsHandler());
2850
+ return skills.map((skill) => new _SystemSkill(skill.id, skill.name));
2851
+ }
2852
+ };
2853
+
2854
+ // src/entities/documents/namespace.ts
2855
+ var DocumentNamespace = class {
2856
+ constructor(client) {
2857
+ this.client = client;
2858
+ }
2859
+ client;
2860
+ /** A handle to a document by id. Details load on first access. */
2861
+ byId(id) {
2862
+ return Document.byId(this.client, id);
2863
+ }
2864
+ /** Create a markdown document. */
2865
+ create(opts) {
2866
+ return Document.create(this.client, opts);
2867
+ }
2868
+ /** Create a snippet: a reusable markdown document. */
2869
+ createSnippet(opts) {
2870
+ return Document.createSnippet(this.client, opts);
2871
+ }
2872
+ /** Create a skill: markdown instructions that AI reads and follows. */
2873
+ createSkill(opts) {
2874
+ return Document.createSkill(this.client, opts);
2875
+ }
2876
+ /**
2877
+ * The built-in system skills: static AI instructions with no document
2878
+ * behind them. Unlike user skills they cannot be opened or edited.
2879
+ */
2880
+ systemSkills() {
2881
+ return SystemSkill.list(this.client);
2882
+ }
2883
+ /** Search documents by name and content, most relevant first, auto-paginated. */
2884
+ search(query, opts) {
2885
+ return Document.search(this.client, query, opts);
2886
+ }
2887
+ /** The user's recent documents, most recent first, auto-paginated. */
2888
+ recent(opts) {
2889
+ return Document.recent(this.client, opts);
2890
+ }
2891
+ /** The user's recently soft-deleted documents. */
2892
+ recentlyDeleted() {
2893
+ return Document.recentlyDeleted(this.client);
2894
+ }
2895
+ };
2896
+
2897
+ // src/entities/email/attachment.ts
2898
+ var EmailAttachment = class _EmailAttachment extends MacroEntity {
2899
+ async fetch() {
2900
+ const { attachment } = unwrap(
2901
+ await this.client.email.getAttachment({ path: { id: this.id } })
2902
+ );
2903
+ return attachment;
2904
+ }
2905
+ /** A handle to an attachment by id. Fields load on first access. */
2906
+ static byId(client, id) {
2907
+ return new _EmailAttachment(client, id);
2908
+ }
2909
+ /** Build an attachment from an already-fetched record (pre-seeded, no fetch). */
2910
+ static from(client, data) {
2911
+ return new _EmailAttachment(client, data.db_id, data);
2912
+ }
2913
+ /** The attachment's original filename. */
2914
+ filename = this.field("filename");
2915
+ /** The attachment's MIME type. */
2916
+ mimeType = this.field("mime_type");
2917
+ /** The attachment's size in bytes. */
2918
+ size = this.field("size_bytes");
2919
+ /** A URL to the attachment's raw data, when available. */
2920
+ dataUrl = this.field("data_url");
2921
+ /** The attachment's static-file-service id, when it has been stored there. */
2922
+ sfsId = this.field("sfs_id");
2923
+ /** The attachment's Content-ID header value (for inline attachments). */
2924
+ contentId = this.field("content_id");
2925
+ /**
2926
+ * The Macro document holding this attachment's content. Get-or-create: the
2927
+ * server returns the existing document's id, or downloads the attachment
2928
+ * from the provider and uploads it as a new document first (deduplicated
2929
+ * behind a server-side lock).
2930
+ */
2931
+ async toDocument() {
2932
+ const { document_id } = unwrap(
2933
+ await this.client.email.getAttachmentDocumentId({
2934
+ path: { id: this.id }
2935
+ })
2936
+ );
2937
+ return Document.byId(this.client, document_id);
2938
+ }
2939
+ };
2940
+
2941
+ // src/entities/email/label.ts
2942
+ var Label = class _Label extends MacroEntity {
2943
+ async fetch() {
2944
+ const { labels } = unwrap(await this.client.email.listLabels());
2945
+ const label = labels.find((l2) => l2.id === this.id);
2946
+ if (!label) throw new MacroNotFoundError(`label ${this.id} not found`);
2947
+ return label;
2948
+ }
2949
+ /** A handle to a label by id. Details load on first access. */
2950
+ static byId(client, id) {
2951
+ return new _Label(client, id);
2952
+ }
2953
+ /** All labels across the user's inboxes. */
2954
+ static async list(client) {
2955
+ const { labels } = unwrap(await client.email.listLabels());
2956
+ return labels.map((l2) => new _Label(client, l2.id, l2));
2957
+ }
2958
+ /** Create a user label. */
2959
+ static async create(client, name) {
2960
+ const { label } = unwrap(
2961
+ await client.email.createLabel({ body: { label_name: name } })
2962
+ );
2963
+ if (!label.id) throw new MacroError("created label has no id");
2964
+ return new _Label(client, label.id);
2965
+ }
2966
+ /** Delete this label. */
2967
+ async delete() {
2968
+ unwrap(await this.client.email.deleteLabel({ path: { id: this.id } }));
2969
+ }
2970
+ /** The label's display name. */
2971
+ name = this.field("name");
2972
+ /** The inbox (email link) this label belongs to. */
2973
+ linkId = this.field("linkId");
2974
+ /** Whether this is a system label or a user-created one. */
2975
+ type = this.field("type");
2976
+ /** When the label was created. */
2977
+ createdAt = this.field("createdAt");
2978
+ /** Whether the label is shown in the label list. */
2979
+ labelListVisibility = this.field("labelListVisibility");
2980
+ /** Whether the label is shown in the message list. */
2981
+ messageListVisibility = this.field("messageListVisibility");
2982
+ };
2983
+
2984
+ // src/entities/email/link.ts
2985
+ var Link = class _Link extends MacroEntity {
2986
+ async fetch() {
2987
+ const { links } = unwrap(await this.client.email.listLinks());
2988
+ const link = links.find((l2) => l2.id === this.id);
2989
+ if (!link) throw new MacroNotFoundError(`email link ${this.id} not found`);
2990
+ return link;
2991
+ }
2992
+ /** A handle to an email link by id. Details load on first access. */
2993
+ static byId(client, id) {
2994
+ return new _Link(client, id);
2995
+ }
2996
+ /** The caller's connected email links. */
2997
+ static async list(client) {
2998
+ const { links } = unwrap(await client.email.listLinks());
2999
+ return links.map((l2) => new _Link(client, l2.id, l2));
3000
+ }
3001
+ /** The inbox's email address. */
3002
+ emailAddress = this.field("email_address");
3003
+ /** The email provider (e.g. `GMAIL`). */
3004
+ provider = this.field("provider");
3005
+ /** Whether this is the user's primary inbox. */
3006
+ isPrimary = this.field("is_primary");
3007
+ /** Whether syncing is currently active for this inbox. */
3008
+ isSyncActive = this.field("is_sync_active");
3009
+ /** The inbox's sync status. */
3010
+ syncStatus = this.field("sync_status");
3011
+ /** Whether the inbox needs to be re-authenticated. */
3012
+ needsReauth = this.field("needs_reauth");
3013
+ /** The inbox's avatar URL, if any. */
3014
+ photoUrl = this.field("photo_url");
3015
+ };
3016
+
3017
+ // src/entities/email/thread.ts
3018
+ var EmailThread = class _EmailThread extends PropertiedEntity {
3019
+ /** Favorites identify email threads as `email_thread`. */
3020
+ entityType = "email_thread";
3021
+ /** The properties service identifies email threads as `THREAD`. */
3022
+ propertyEntityType = "THREAD";
3023
+ async fetch() {
3024
+ const { thread } = unwrap(
3025
+ await this.client.email.getThread({
3026
+ path: { thread_id: this.id },
3027
+ query: { limit: 100 }
3028
+ })
3029
+ );
3030
+ return thread;
3031
+ }
3032
+ /** A handle to a thread by id. Details load on first access. */
3033
+ static byId(client, id) {
3034
+ return new _EmailThread(client, id);
3035
+ }
3036
+ /** When the thread was created. */
3037
+ createdAt = this.field("created_at");
3038
+ /** When the thread was last updated. */
3039
+ updatedAt = this.field("updated_at");
3040
+ /** Whether the thread has been read. */
3041
+ isRead = this.field("is_read");
3042
+ /** Whether the thread is visible in the inbox (i.e. not archived). */
3043
+ inboxVisible = this.field("inbox_visible");
3044
+ /** The viewer's access level to this thread. */
3045
+ accessLevel = this.field("access_level");
3046
+ /** The provider-internal thread id (e.g. Gmail/Outlook), if any. */
3047
+ providerId = this.field("provider_id");
3048
+ /** The inbox (email link) that owns this thread. */
3049
+ link = this.mappedField(
3050
+ "link_id",
3051
+ (id) => Link.byId(this.client, id)
3052
+ );
3053
+ /** The project this thread is attached to, if any. */
3054
+ project = this.mappedField(
3055
+ "project_id",
3056
+ (id) => id ? Project.byId(this.client, id) : void 0
3057
+ );
3058
+ /** Timestamp of the latest inbound message, if any. */
3059
+ latestInboundAt = this.field("latest_inbound_message_ts");
3060
+ /** Timestamp of the latest outbound message, if any. */
3061
+ latestOutboundAt = this.field("latest_outbound_message_ts");
3062
+ /** Timestamp of the latest non-spam message, if any. */
3063
+ latestNonSpamAt = this.field("latest_non_spam_message_ts");
3064
+ /** The thread's subject, from its first message with one. */
3065
+ async subject() {
3066
+ const { messages } = await this.detail.get();
3067
+ for (const m2 of messages) if (m2.subject) return m2.subject;
3068
+ return void 0;
3069
+ }
3070
+ /**
3071
+ * Everyone on the thread (senders and recipients), deduped by email.
3072
+ * Derived from the thread's first 100 messages.
3073
+ */
3074
+ async participants() {
3075
+ const { messages } = await this.detail.get();
3076
+ const seen = /* @__PURE__ */ new Map();
3077
+ for (const m2 of messages) {
3078
+ for (const c2 of [m2.from, ...m2.to, ...m2.cc, ...m2.bcc]) {
3079
+ if (c2 && !seen.has(c2.email)) seen.set(c2.email, c2);
3080
+ }
3081
+ }
3082
+ return [...seen.values()];
3083
+ }
3084
+ /** The messages in this thread, pre-seeded from the list endpoint. */
3085
+ async messages(opts) {
3086
+ const records = unwrap(
3087
+ await this.client.email.getThreadMessagesHandler({
3088
+ path: { id: this.id },
3089
+ query: {
3090
+ ...opts?.since ? { since: opts.since } : {},
3091
+ ...opts?.limit ? { limit: opts.limit } : {}
3092
+ }
3093
+ })
3094
+ );
3095
+ return records.map((r2) => EmailMessage.from(this.client, r2));
3096
+ }
3097
+ /** The attachments across this thread's first 100 messages, pre-seeded from the thread detail. */
3098
+ async attachments() {
3099
+ const { messages } = await this.detail.get();
3100
+ return messages.flatMap(
3101
+ (m2) => m2.attachments.map((a2) => EmailAttachment.from(this.client, a2))
3102
+ );
3103
+ }
3104
+ /** Send a reply within this thread. Returns a handle when the API reports the created message's id. */
3105
+ async reply(opts) {
3106
+ const subject = opts.subject ?? await this.subject() ?? "";
3107
+ const { message } = await this.mutate(
3108
+ (c2) => c2.email.sendMessage({
3109
+ body: {
3110
+ message: {
3111
+ thread_db_id: this.id,
3112
+ replying_to_id: opts.replyingTo?.id ?? null,
3113
+ to: opts.to,
3114
+ cc: opts.cc ?? null,
3115
+ bcc: opts.bcc ?? null,
3116
+ subject,
3117
+ body_text: opts.bodyText
3118
+ }
3119
+ }
3120
+ })
3121
+ );
3122
+ return message.db_id ? EmailMessage.byId(this.client, message.db_id) : void 0;
3123
+ }
3124
+ /** Archive the thread (or unarchive with `false`). */
3125
+ async archive(archived = true) {
3126
+ await this.mutate(
3127
+ (c2) => c2.email.archiveThread({
3128
+ path: { id: this.id },
3129
+ body: { value: archived }
3130
+ })
3131
+ );
3132
+ }
3133
+ /** Mark the thread as seen. */
3134
+ async markSeen() {
3135
+ await this.mutate((c2) => c2.email.threadSeen({ path: { id: this.id } }));
3136
+ }
3137
+ /** Add a label to every message in the thread. */
3138
+ async addLabel(label) {
3139
+ await this.mutate(
3140
+ (c2) => c2.email.addRemoveThreadLabel({
3141
+ path: { id: this.id },
3142
+ body: { label_id: label.id, value: true }
3143
+ })
3144
+ );
3145
+ }
3146
+ /** Remove a label from every message in the thread. */
3147
+ async removeLabel(label) {
3148
+ await this.mutate(
3149
+ (c2) => c2.email.addRemoveThreadLabel({
3150
+ path: { id: this.id },
3151
+ body: { label_id: label.id, value: false }
3152
+ })
3153
+ );
3154
+ }
3155
+ /** Attach the thread to a project, or clear the project with `null`. */
3156
+ async moveToProject(project) {
3157
+ await this.mutate(
3158
+ (c2) => c2.email.updateThreadProject({
3159
+ path: { thread_id: this.id },
3160
+ body: { projectId: project?.id ?? null }
3161
+ })
3162
+ );
3163
+ }
3164
+ /** Search email threads by subject and content, most relevant first, auto-paginated. */
3165
+ static search = entitySearch({
3166
+ filters: { email_filters: {} },
3167
+ type: "email",
3168
+ make: (client, hit) => new _EmailThread(client, hit.thread_id)
3169
+ });
3170
+ };
3171
+
3172
+ // src/entities/email/message.ts
3173
+ var EmailMessage = class _EmailMessage extends MacroEntity {
3174
+ async fetch() {
3175
+ return unwrap(
3176
+ await this.client.email.getMessage({ path: { id: this.id } })
3177
+ );
3178
+ }
3179
+ /** A handle to a message by id. Fields load on first access. */
3180
+ static byId(client, id) {
3181
+ return new _EmailMessage(client, id);
3182
+ }
3183
+ /** Build a message from an already-fetched record (pre-seeded, no fetch). */
3184
+ static from(client, data) {
3185
+ return new _EmailMessage(client, data.db_id, data);
3186
+ }
3187
+ /** Send a new email message. Returns a handle when the API reports the created message's id. */
3188
+ static async send(client, opts) {
3189
+ const { message } = unwrap(
3190
+ await client.email.sendMessage({
3191
+ body: {
3192
+ message: {
3193
+ to: opts.to,
3194
+ cc: opts.cc ?? null,
3195
+ bcc: opts.bcc ?? null,
3196
+ subject: opts.subject,
3197
+ body_text: opts.bodyText
3198
+ }
3199
+ }
3200
+ })
3201
+ );
3202
+ return message.db_id ? _EmailMessage.byId(client, message.db_id) : void 0;
3203
+ }
3204
+ /** The message's subject line. */
3205
+ subject = this.field("subject");
3206
+ /** The sender. */
3207
+ from = this.field("from");
3208
+ /** The To recipients. */
3209
+ to = this.field("to");
3210
+ /** The Cc recipients. */
3211
+ cc = this.field("cc");
3212
+ /** The Bcc recipients. */
3213
+ bcc = this.field("bcc");
3214
+ /** The parsed message body, as the API returns it. */
3215
+ body = this.field("body_parsed");
3216
+ /** The provider-internal date of the message. */
3217
+ sentAt = this.field("internal_date_ts");
3218
+ /** Labels on this message. */
3219
+ labels = this.field("labels");
3220
+ /** The inbox (email link) this message belongs to. */
3221
+ link = this.mappedField(
3222
+ "link_id",
3223
+ (id) => Link.byId(this.client, id)
3224
+ );
3225
+ /** Add a label to this message. */
3226
+ async addLabel(label) {
3227
+ await this.mutate(
3228
+ (c2) => c2.email.addRemoveLabel({
3229
+ body: {
3230
+ label_id: label.id,
3231
+ message_ids: [this.id],
3232
+ value: true
3233
+ }
3234
+ })
3235
+ );
3236
+ }
3237
+ /** Remove a label from this message. */
3238
+ async removeLabel(label) {
3239
+ await this.mutate(
3240
+ (c2) => c2.email.addRemoveLabel({
3241
+ body: {
3242
+ label_id: label.id,
3243
+ message_ids: [this.id],
3244
+ value: false
3245
+ }
3246
+ })
3247
+ );
3248
+ }
3249
+ /** The thread this message belongs to. */
3250
+ async thread() {
3251
+ return EmailThread.byId(
3252
+ this.client,
3253
+ (await this.detail.get()).thread_db_id
3254
+ );
3255
+ }
3256
+ };
3257
+
3258
+ // src/entities/email/namespace.ts
3259
+ var EmailNamespace = class {
3260
+ constructor(client) {
3261
+ this.client = client;
3262
+ }
3263
+ client;
3264
+ /** A handle to an email thread by id. */
3265
+ byId(id) {
3266
+ return EmailThread.byId(this.client, id);
3267
+ }
3268
+ /** A handle to an email message by id. */
3269
+ message(id) {
3270
+ return EmailMessage.byId(this.client, id);
3271
+ }
3272
+ /** A handle to an email attachment by id. */
3273
+ attachment(id) {
3274
+ return EmailAttachment.byId(this.client, id);
3275
+ }
3276
+ /** A handle to a connected inbox (email link) by id. */
3277
+ link(id) {
3278
+ return Link.byId(this.client, id);
3279
+ }
3280
+ /** The caller's connected inboxes (email links). */
3281
+ links() {
3282
+ return Link.list(this.client);
3283
+ }
3284
+ /** Send a new email message. */
3285
+ send(opts) {
3286
+ return EmailMessage.send(this.client, opts);
3287
+ }
3288
+ /** Search email threads by subject and content. */
3289
+ search(query, opts) {
3290
+ return EmailThread.search(this.client, query, opts);
3291
+ }
3292
+ /** The threads in the inbox, most recent first, auto-paginated. */
3293
+ inbox(opts) {
3294
+ return paginate(async (cursor) => {
3295
+ const page = unwrap(
3296
+ await this.client.email.previewsInboxCursor({
3297
+ path: { view: "inbox" },
3298
+ query: {
3299
+ ...opts?.pageSize ? { limit: opts.pageSize } : {},
3300
+ ...opts?.sort ? { sort_method: opts.sort } : {},
3301
+ ...cursor ? { cursor } : {}
3302
+ }
3303
+ })
3304
+ );
3305
+ return {
3306
+ items: page.items.map((t2) => EmailThread.byId(this.client, t2.id)),
3307
+ nextCursor: page.next_cursor
3308
+ };
3309
+ });
3310
+ }
3311
+ /** A handle to a label by id. */
3312
+ label(id) {
3313
+ return Label.byId(this.client, id);
3314
+ }
3315
+ /** All labels across the user's inboxes. */
3316
+ labels() {
3317
+ return Label.list(this.client);
3318
+ }
3319
+ /** Create a user label. Returns the created label. */
3320
+ createLabel(name) {
3321
+ return Label.create(this.client, name);
3322
+ }
3323
+ /** Delete a label. */
3324
+ async deleteLabel(label) {
3325
+ unwrap(await this.client.email.deleteLabel({ path: { id: label.id } }));
3326
+ }
3327
+ /** Block an email sender. */
3328
+ async blockSender(email) {
3329
+ unwrap(
3330
+ await this.client.email.blockSender({ body: { email_address: email } })
3331
+ );
3332
+ }
3333
+ /** Unblock a previously blocked sender. */
3334
+ async unblockSender(email) {
3335
+ unwrap(
3336
+ await this.client.email.unblockSender({
3337
+ body: { email_address: email }
3338
+ })
3339
+ );
3340
+ }
3341
+ /** The email addresses currently blocked. */
3342
+ async blockedSenders() {
3343
+ return unwrap(await this.client.email.listBlockedSenders()).blocked_emails;
3344
+ }
3345
+ };
3346
+
3347
+ // src/entities/favorites/namespace.ts
3348
+ var FavoritesNamespace = class {
3349
+ constructor(client) {
3350
+ this.client = client;
3351
+ }
3352
+ client;
3353
+ /** The user's favorites, in manual order. */
3354
+ async list() {
3355
+ const { favorites } = unwrap(await this.client.storage.listFavorites({}));
3356
+ return favorites;
3357
+ }
3358
+ /**
3359
+ * Favorite an entity. Returns the favorite record.
3360
+ */
3361
+ async add(entity) {
3362
+ return unwrap(
3363
+ await this.client.storage.addFavorite({
3364
+ body: { entityId: entity.id, entityType: entity.entityType }
3365
+ })
3366
+ );
3367
+ }
3368
+ /** Remove an entity from the user's favorites. */
3369
+ async remove(entity) {
3370
+ unwrap(
3371
+ await this.client.storage.removeFavoriteByEntity({
3372
+ path: { entity_type: entity.entityType, entity_id: entity.id }
3373
+ })
3374
+ );
3375
+ }
3376
+ /** Reorder the favorites: pass every favorited entity in the desired order. */
3377
+ async reorder(favorites) {
3378
+ unwrap(
3379
+ await this.client.storage.reorderFavorites({
3380
+ body: { favorites }
3381
+ })
3382
+ );
3383
+ }
3384
+ };
3385
+
3386
+ // src/entities/foreign/foreign-entity.ts
3387
+ var ForeignEntity = class _ForeignEntity extends FavoritableEntity {
3388
+ /** Favorites identify foreign entities as `foreign_entity`. */
3389
+ entityType = "foreign_entity";
3390
+ async fetch() {
3391
+ return unwrap(
3392
+ await this.client.storage.getForeignEntity({ path: { id: this.id } })
3393
+ );
3394
+ }
3395
+ /** A handle to a foreign entity by its internal record id. Details load on first access. */
3396
+ static byId(client, id) {
3397
+ return new _ForeignEntity(client, id);
3398
+ }
3399
+ /** The identifier assigned by the external system. */
3400
+ foreignEntityId = this.field("foreignEntityId");
3401
+ /** The source system that owns the external identifier (e.g. `github_pull_request`). */
3402
+ source = this.field("foreignEntitySource");
3403
+ /** The internal entity id this foreign entity is stored for. */
3404
+ storedForId = this.field("storedForId");
3405
+ /** The internal auth entity namespace this foreign entity is stored for. */
3406
+ storedForAuthEntity = this.field("storedForAuthEntity");
3407
+ /** When the record was created (ISO timestamp). */
3408
+ createdAt = this.field("createdAt");
3409
+ /** When the record was last updated (ISO timestamp). */
3410
+ updatedAt = this.field("updatedAt");
3411
+ /** Arbitrary source-specific metadata stored with the mapping. */
3412
+ async metadata() {
3413
+ return (await this.detail.get()).metadata;
3414
+ }
3415
+ };
3416
+
3417
+ // src/entities/foreign/namespace.ts
3418
+ var ForeignEntityNamespace = class {
3419
+ constructor(client) {
3420
+ this.client = client;
3421
+ }
3422
+ client;
3423
+ byId(id) {
3424
+ return ForeignEntity.byId(this.client, id);
3425
+ }
3426
+ };
3427
+
3428
+ // src/entities/notifications/notification.ts
3429
+ var Notification = class _Notification extends MacroEntity {
3430
+ async fetch() {
3431
+ return unwrap(
3432
+ await this.client.notification.getTypedNotificationById({
3433
+ path: { notification_id: this.id }
3434
+ })
3435
+ );
3436
+ }
3437
+ /** A handle to a notification by id. Details load on first access. */
3438
+ static byId(client, id) {
3439
+ return new _Notification(client, id);
3440
+ }
3441
+ /** Build a notification from a list-endpoint record (pre-seeded, no fetch). */
3442
+ static from(client, data) {
3443
+ return new _Notification(client, data.id, data);
3444
+ }
3445
+ /** The viewer's notification feed, most recent first, auto-paginated. */
3446
+ static list(client, opts) {
3447
+ return paginate(async (cursor) => {
3448
+ const page = unwrap(
3449
+ await client.notification.listTypedNotifications({
3450
+ query: {
3451
+ ...opts?.pageSize ? { limit: opts.pageSize } : {},
3452
+ ...cursor ? { cursor } : {}
3453
+ }
3454
+ })
3455
+ );
3456
+ return {
3457
+ items: page.items.map((n2) => _Notification.from(client, n2)),
3458
+ nextCursor: page.next_cursor
3459
+ };
3460
+ });
3461
+ }
3462
+ /** The notification event type (e.g. `channel_mention`). */
3463
+ type = this.field("notification_event_type");
3464
+ /** When the notification was created. */
3465
+ createdAt = this.field("created_at");
3466
+ /** When the notification was last updated. */
3467
+ updatedAt = this.field("updated_at");
3468
+ /** Whether the notification is marked as done. */
3469
+ done = this.field("done");
3470
+ /** Whether the notification has been sent (delivered out of band). */
3471
+ sent = this.field("sent");
3472
+ /** When the notification was viewed, if it has been seen. */
3473
+ viewedAt = this.field("viewed_at");
3474
+ /** When the notification was deleted, if it has been. */
3475
+ deletedAt = this.field("deleted_at");
3476
+ /** The user who owns (receives) this notification. */
3477
+ owner = this.mappedField(
3478
+ "owner_id",
3479
+ (id) => User.byId(this.client, id)
3480
+ );
3481
+ /** The user who triggered the notification, if any. */
3482
+ sender = this.mappedField(
3483
+ "sender_id",
3484
+ (id) => id ? User.byId(this.client, id) : void 0
3485
+ );
3486
+ /** The typed notification payload (tagged by event type). */
3487
+ metadata = this.field("notification_metadata");
3488
+ /** Whether the notification has been seen (viewed at least once). */
3489
+ async seen() {
3490
+ return await this.viewedAt() !== void 0;
3491
+ }
3492
+ /** Mark the notification as seen. */
3493
+ async markSeen() {
3494
+ await this.mutate(
3495
+ (c2) => c2.notification.bulkMarkNotificationsSeen({
3496
+ body: { notificationIds: [this.id] }
3497
+ })
3498
+ );
3499
+ }
3500
+ /** Mark the notification as done. */
3501
+ async markDone() {
3502
+ await this.mutate(
3503
+ (c2) => c2.notification.bulkMarkNotificationsDone({
3504
+ body: { notificationIds: [this.id] }
3505
+ })
3506
+ );
3507
+ }
3508
+ /** Move the notification back to not-done. */
3509
+ async markUndone() {
3510
+ await this.mutate(
3511
+ (c2) => c2.notification.bulkMarkNotificationsUndone({
3512
+ body: { notificationIds: [this.id] }
3513
+ })
3514
+ );
3515
+ }
3516
+ /** Delete the notification. */
3517
+ async delete() {
3518
+ await this.mutate(
3519
+ (c2) => c2.notification.deleteUserNotificationV2({
3520
+ path: { notification_id: this.id }
3521
+ })
3522
+ );
3523
+ }
3524
+ };
3525
+
3526
+ // src/entities/notifications/namespace.ts
3527
+ var NotificationNamespace = class {
3528
+ constructor(client) {
3529
+ this.client = client;
3530
+ }
3531
+ client;
3532
+ /** A handle to a notification by id. */
3533
+ byId(id) {
3534
+ return Notification.byId(this.client, id);
3535
+ }
3536
+ /** The viewer's notification feed, most recent first, auto-paginated. */
3537
+ list(opts) {
3538
+ return Notification.list(this.client, opts);
3539
+ }
3540
+ /** Mark a batch of notifications as seen. */
3541
+ async markSeen(ids) {
3542
+ unwrap(
3543
+ await this.client.notification.bulkMarkNotificationsSeen({
3544
+ body: { notificationIds: ids }
3545
+ })
3546
+ );
3547
+ }
3548
+ /** Mark a batch of notifications as done. */
3549
+ async markDone(ids) {
3550
+ unwrap(
3551
+ await this.client.notification.bulkMarkNotificationsDone({
3552
+ body: { notificationIds: ids }
3553
+ })
3554
+ );
3555
+ }
3556
+ /** Delete a batch of notifications. */
3557
+ async delete(ids) {
3558
+ unwrap(
3559
+ await this.client.notification.bulkDeleteUserNotificationsV2({
3560
+ body: { notificationIds: ids }
3561
+ })
3562
+ );
3563
+ }
3564
+ /** The viewer's notification type preferences (disabled types). */
3565
+ async preferences() {
3566
+ return unwrap(
3567
+ await this.client.notification.getNotificationTypePreferences()
3568
+ );
3569
+ }
3570
+ /** Re-enable delivery of a notification type. */
3571
+ async enableType(type) {
3572
+ unwrap(
3573
+ await this.client.notification.enableNotificationType({
3574
+ path: { notification_event_type: type }
3575
+ })
3576
+ );
3577
+ }
3578
+ /** Disable delivery of a notification type. */
3579
+ async disableType(type) {
3580
+ unwrap(
3581
+ await this.client.notification.disableNotificationType({
3582
+ path: { notification_event_type: type }
3583
+ })
3584
+ );
3585
+ }
3586
+ };
3587
+
3588
+ // src/entities/pins/namespace.ts
3589
+ var PinsNamespace = class {
3590
+ constructor(client) {
3591
+ this.client = client;
3592
+ }
3593
+ client;
3594
+ /** The user's pinned items, with their pin indices. */
3595
+ async list() {
3596
+ const { data } = unwrap(await this.client.storage.getPinsHandler({}));
3597
+ return data?.recent ?? [];
3598
+ }
3599
+ /** Pin an entity to a slot. `index` is the slot to put it in. */
3600
+ async add(entity, opts) {
3601
+ unwrap(
3602
+ await this.client.storage.addPinHandler({
3603
+ path: { pinned_item_id: entity.id },
3604
+ body: { pinType: entity.entityType, pinIndex: opts.index }
3605
+ })
3606
+ );
3607
+ }
3608
+ /** Unpin an entity. */
3609
+ async remove(entity) {
3610
+ unwrap(
3611
+ await this.client.storage.removePinHandler({
3612
+ path: { pinned_item_id: entity.id },
3613
+ body: { pinType: entity.entityType }
3614
+ })
3615
+ );
3616
+ }
3617
+ /** Reorder pins: pass each pinned item with its type and new index. */
3618
+ async reorder(pins) {
3619
+ unwrap(await this.client.storage.reorderPinsHandler({ body: pins }));
3620
+ }
3621
+ };
3622
+
3623
+ // src/entities/projects/namespace.ts
3624
+ var ProjectNamespace = class {
3625
+ constructor(client) {
3626
+ this.client = client;
3627
+ }
3628
+ client;
3629
+ byId(id) {
3630
+ return Project.byId(this.client, id);
3631
+ }
3632
+ create(opts) {
3633
+ return Project.create(this.client, opts);
3634
+ }
3635
+ search(query, opts) {
3636
+ return Project.search(this.client, query, opts);
3637
+ }
3638
+ };
3639
+
3640
+ // src/entities/properties/property-option.ts
3641
+ var PropertyOption = class _PropertyOption {
3642
+ constructor(client, definitionId, id, record) {
3643
+ this.client = client;
3644
+ this.definitionId = definitionId;
3645
+ this.id = id;
3646
+ this.record = record;
3647
+ }
3648
+ client;
3649
+ definitionId;
3650
+ id;
3651
+ record;
3652
+ /** Wrap a record already in hand (e.g. from a list or create response). */
3653
+ static from(client, definitionId, record) {
3654
+ return new _PropertyOption(client, definitionId, record.id, record);
3655
+ }
3656
+ /** The option's value (string or number, per the property's data type). */
3657
+ get value() {
3658
+ return this.record.value;
3659
+ }
3660
+ /** The option's display color, if set. */
3661
+ get color() {
3662
+ return this.record.color ?? void 0;
3663
+ }
3664
+ /** The option's position among its definition's options. */
3665
+ get displayOrder() {
3666
+ return this.record.display_order;
3667
+ }
3668
+ /** When the option was created. */
3669
+ get createdAt() {
3670
+ return this.record.created_at;
3671
+ }
3672
+ /** When the option was last updated. */
3673
+ get updatedAt() {
3674
+ return this.record.updated_at;
3675
+ }
3676
+ /** Update this option's label, color, or display order. */
3677
+ async update(updates) {
3678
+ this.record = unwrap(
3679
+ await this.client.properties.updatePropertyOption({
3680
+ path: { definition_id: this.definitionId, option_id: this.id },
3681
+ body: updates
3682
+ })
3683
+ );
3684
+ return this;
3685
+ }
3686
+ /** Delete this option from its property definition. */
3687
+ async delete() {
3688
+ unwrap(
3689
+ await this.client.properties.deletePropertyOption({
3690
+ path: { definition_id: this.definitionId, option_id: this.id }
3691
+ })
3692
+ );
3693
+ }
3694
+ };
3695
+
3696
+ // src/entities/properties/property-definition.ts
3697
+ var PropertyDefinition = class _PropertyDefinition {
3698
+ constructor(client, id, seed) {
3699
+ this.client = client;
3700
+ this.id = id;
3701
+ this.detail = new Lazy(() => this.fetch(), seed);
3702
+ }
3703
+ client;
3704
+ id;
3705
+ detail;
3706
+ async fetch() {
3707
+ return unwrap(
3708
+ await this.client.properties.getPropertyDefinition({
3709
+ path: { definition_id: this.id }
3710
+ })
3711
+ );
3712
+ }
3713
+ /** Create a new property definition. */
3714
+ static async create(client, opts) {
3715
+ const record = unwrap(
3716
+ await client.properties.createPropertyDefinition({
3717
+ body: {
3718
+ display_name: opts.displayName,
3719
+ scope: opts.scope,
3720
+ data_type: opts.dataType
3721
+ }
3722
+ })
3723
+ );
3724
+ return new _PropertyDefinition(client, record.id, record);
3725
+ }
3726
+ /** A handle to an existing definition by id. Fields load lazily on first access. */
3727
+ static byId(client, id) {
3728
+ return new _PropertyDefinition(client, id);
3729
+ }
3730
+ /** Wrap a record already in hand (e.g. from a list response). */
3731
+ static fromRecord(client, record) {
3732
+ return new _PropertyDefinition(client, record.id, record);
3733
+ }
3734
+ get displayName() {
3735
+ return this.detail.get().then((r2) => r2.display_name);
3736
+ }
3737
+ get dataType() {
3738
+ return this.detail.get().then((r2) => r2.data_type);
3739
+ }
3740
+ get owner() {
3741
+ return this.detail.get().then((r2) => r2.owner);
3742
+ }
3743
+ get isSystem() {
3744
+ return this.detail.get().then((r2) => r2.is_system);
3745
+ }
3746
+ get isMultiSelect() {
3747
+ return this.detail.get().then((r2) => r2.is_multi_select);
3748
+ }
3749
+ get createdAt() {
3750
+ return this.detail.get().then((r2) => r2.created_at);
3751
+ }
3752
+ get updatedAt() {
3753
+ return this.detail.get().then((r2) => r2.updated_at);
3754
+ }
3755
+ /** Delete this property definition. */
3756
+ async delete() {
3757
+ return unwrap(
3758
+ await this.client.properties.deletePropertyDefinition({
3759
+ path: { definition_id: this.id }
3760
+ })
3761
+ );
3762
+ }
3763
+ /** The selectable options for this definition (select-type properties). */
3764
+ async options() {
3765
+ const records = unwrap(
3766
+ await this.client.properties.getPropertyOptions({
3767
+ path: { definition_id: this.id }
3768
+ })
3769
+ );
3770
+ return records.map((r2) => PropertyOption.from(this.client, this.id, r2));
3771
+ }
3772
+ /** Add an option to this select-type property. */
3773
+ async addOption(option) {
3774
+ const record = unwrap(
3775
+ await this.client.properties.addPropertyOption({
3776
+ path: { definition_id: this.id },
3777
+ body: option
3778
+ })
3779
+ );
3780
+ return PropertyOption.from(this.client, this.id, record);
3781
+ }
3782
+ /** Update an option (label, color, display order). */
3783
+ async updateOption(option, updates) {
3784
+ const record = unwrap(
3785
+ await this.client.properties.updatePropertyOption({
3786
+ path: { definition_id: this.id, option_id: option.id },
3787
+ body: updates
3788
+ })
3789
+ );
3790
+ return PropertyOption.from(this.client, this.id, record);
3791
+ }
3792
+ /** Delete an option from this property. */
3793
+ async deleteOption(option) {
3794
+ return unwrap(
3795
+ await this.client.properties.deletePropertyOption({
3796
+ path: { definition_id: this.id, option_id: option.id }
3797
+ })
3798
+ );
3799
+ }
3800
+ };
3801
+
3802
+ // src/entities/properties/namespace.ts
3803
+ var PropertiesNamespace = class {
3804
+ constructor(client) {
3805
+ this.client = client;
3806
+ }
3807
+ client;
3808
+ /** List property definitions visible to the user, pre-hydrated with their records. */
3809
+ async list(opts) {
3810
+ const raw = unwrap(
3811
+ await this.client.properties.listProperties({
3812
+ query: {
3813
+ scope: opts?.scope ?? "all",
3814
+ ...opts?.forEntityType !== void 0 ? { for_entity_type: opts.forEntityType } : {}
3815
+ }
3816
+ })
3817
+ );
3818
+ return raw.map((item) => {
3819
+ const record = "definition" in item ? item.definition : item;
3820
+ return PropertyDefinition.fromRecord(this.client, record);
3821
+ });
3822
+ }
3823
+ /** Create a new custom property definition. */
3824
+ create(opts) {
3825
+ return PropertyDefinition.create(this.client, opts);
3826
+ }
3827
+ /** A handle to an existing property definition by id. */
3828
+ definition(id) {
3829
+ return PropertyDefinition.byId(this.client, id);
3830
+ }
3831
+ /** Get properties for multiple entities in a single request. */
3832
+ async bulkEntityProperties(request) {
3833
+ return unwrap(
3834
+ await this.client.properties.getBulkEntityProperties({ body: request })
3835
+ );
3836
+ }
3837
+ /** Apply one multi-select option delta to several entity handles. */
3838
+ async updateEntityPropertyOptions(entities, change) {
3839
+ const response = unwrap(
3840
+ await this.client.properties.bulkUpdateEntitiesPropertyOptions({
3841
+ body: {
3842
+ entities: entities.map((entity) => entity.propertyReference()),
3843
+ property_id: change.property.id,
3844
+ ...change.add ? { add_option_ids: change.add.map((option) => option.id) } : {},
3845
+ ...change.remove ? { remove_option_ids: change.remove.map((option) => option.id) } : {}
3846
+ }
3847
+ })
3848
+ );
3849
+ return response.results;
3850
+ }
3851
+ /** Add a select option to a multi-select property value on an entity. */
3852
+ async addEntityPropertyOption(opts) {
3853
+ return unwrap(
3854
+ await this.client.properties.addEntityPropertyOption({
3855
+ path: {
3856
+ ...opts.entity.propertyReference(),
3857
+ property_id: opts.property.id,
3858
+ option_id: opts.option.id
3859
+ }
3860
+ })
3861
+ );
3862
+ }
3863
+ /** Remove a select option from a multi-select property value on an entity. */
3864
+ async removeEntityPropertyOption(opts) {
3865
+ return unwrap(
3866
+ await this.client.properties.removeEntityPropertyOption({
3867
+ path: {
3868
+ ...opts.entity.propertyReference(),
3869
+ property_id: opts.property.id,
3870
+ option_id: opts.option.id
3871
+ }
3872
+ })
3873
+ );
3874
+ }
3875
+ /** The user's tag sets: their personal set, plus their team's when on a team. */
3876
+ async tags() {
3877
+ return unwrap(await this.client.properties.listTags({}));
3878
+ }
3879
+ };
3880
+
3881
+ // src/entities/tasks/task.ts
3882
+ var STATUS_PROPERTY_ID = "00000001-0000-0000-0000-000000000002";
3883
+ var COMPLETED_STATUS_OPTION_ID = "00000001-0000-0000-0002-000000000004";
3884
+ var Task = class _Task extends Document {
3885
+ /** A handle to a task by document id. Details load on first access. */
3886
+ static byId(client, id) {
3887
+ return new _Task(client, id);
3888
+ }
3889
+ /**
3890
+ * Create a task. `team` scopes the team task number and may be omitted
3891
+ * when the creator belongs to exactly one team; `shareWithTeam` defaults
3892
+ * to true.
3893
+ */
3894
+ static async create(client, opts) {
3895
+ const { documentId } = unwrap(
3896
+ await client.storage.createTaskHandler({
3897
+ body: {
3898
+ taskName: opts.name,
3899
+ markdown: opts.markdown ?? null,
3900
+ projectId: opts.project?.id ?? null,
3901
+ teamId: opts.team?.id ?? null,
3902
+ shareWithTeam: opts.shareWithTeam ?? true
3903
+ }
3904
+ })
3905
+ );
3906
+ return new _Task(client, documentId);
3907
+ }
3908
+ /**
3909
+ * Whether the task is completed (its Status property is "Completed");
3910
+ * `undefined` if the document is not a task.
3911
+ */
3912
+ async completed() {
3913
+ const { subType } = await this.detail.get();
3914
+ if (subType !== "task") return void 0;
3915
+ const properties = await this.properties();
3916
+ const value = properties.find(
3917
+ (p2) => p2.definition.id === STATUS_PROPERTY_ID
3918
+ )?.value;
3919
+ return value?.type === "SelectOption" && value.value.includes(COMPLETED_STATUS_OPTION_ID);
3920
+ }
3921
+ /** The task's URL in the Macro web app. */
3922
+ webUrl() {
3923
+ return `${this.client.webAppUrl}/app/task/${this.id}`;
3924
+ }
3925
+ /** Search tasks by name and content, most relevant first, auto-paginated. */
3926
+ static search = entitySearch({
3927
+ filters: { document_filters: { sub_types: ["task"], task_filters: {} } },
3928
+ type: "document",
3929
+ make: (client, hit) => new _Task(client, hit.document_id)
3930
+ });
3931
+ };
3932
+
3933
+ // src/entities/tasks/namespace.ts
3934
+ var TaskNamespace = class {
3935
+ constructor(client) {
3936
+ this.client = client;
3937
+ }
3938
+ client;
3939
+ /** A handle to a task by document id. Details load on first access. */
3940
+ byId(id) {
3941
+ return Task.byId(this.client, id);
3942
+ }
3943
+ /** Create a task. */
3944
+ create(opts) {
3945
+ return Task.create(this.client, opts);
3946
+ }
3947
+ /** Search tasks by name and content, most relevant first, auto-paginated. */
3948
+ search(query, opts) {
3949
+ return Task.search(this.client, query, opts);
3950
+ }
3951
+ };
3952
+
3953
+ // src/entities/teams/namespace.ts
3954
+ var TeamNamespace = class {
3955
+ constructor(client) {
3956
+ this.client = client;
3957
+ }
3958
+ client;
3959
+ /** A handle to a team by id. */
3960
+ byId(id) {
3961
+ return Team.byId(this.client, id);
3962
+ }
3963
+ /** The caller's current team. */
3964
+ current() {
3965
+ return Team.current(this.client);
3966
+ }
3967
+ /** The teams the caller belongs to. */
3968
+ list() {
3969
+ return Team.list(this.client);
3970
+ }
3971
+ };
3972
+
3973
+ // src/entities/users/namespace.ts
3974
+ var UserNamespace = class {
3975
+ constructor(client) {
3976
+ this.client = client;
3977
+ }
3978
+ client;
3979
+ /** A handle to a user by id. */
3980
+ byId(id) {
3981
+ return User.byId(this.client, id);
3982
+ }
3983
+ /** The current authenticated user. */
3984
+ me() {
3985
+ return User.me(this.client);
3986
+ }
3987
+ };
3988
+
3989
+ // src/entities/webhooks/webhook.ts
3990
+ var Webhook = class _Webhook extends MacroEntity {
3991
+ /**
3992
+ * The signing secret used to verify deliveries, present only on the handle
3993
+ * returned by {@link create}. `undefined` for `byId` and listed handles.
3994
+ */
3995
+ signingSecret;
3996
+ constructor(client, id, seed, signingSecret) {
3997
+ super(client, id, seed);
3998
+ this.signingSecret = signingSecret;
3999
+ }
4000
+ async fetch() {
4001
+ return unwrap(
4002
+ await this.client.storage.getWebhook({
4003
+ path: { webhook_id: this.id }
4004
+ })
4005
+ );
4006
+ }
4007
+ /** Register a webhook. */
4008
+ static async create(client, opts) {
4009
+ const record = unwrap(
4010
+ await client.storage.createWebhook({
4011
+ body: {
4012
+ endpoint_url: opts.url,
4013
+ namespace: opts.namespace,
4014
+ name: opts.name,
4015
+ filters: opts.filters,
4016
+ scope: opts.scope ?? "user",
4017
+ ...opts.headers !== void 0 ? { headers: opts.headers } : {}
4018
+ }
4019
+ })
4020
+ );
4021
+ return new _Webhook(client, record.id, record, record.signing_secret);
4022
+ }
4023
+ /** A handle to a webhook by id. Details load on first access. */
4024
+ static byId(client, id) {
4025
+ return new _Webhook(client, id);
4026
+ }
4027
+ /** Wrap an already-loaded record. */
4028
+ static fromRecord(client, record) {
4029
+ return new _Webhook(client, record.id, record);
4030
+ }
4031
+ /** The webhook's display name. */
4032
+ name = this.field("name");
4033
+ /**
4034
+ * The caller-chosen namespace, unique among the owning workspace's webhooks.
4035
+ * Fixed at creation time; it cannot be patched.
4036
+ */
4037
+ namespace = this.field("namespace");
4038
+ /** The HTTPS endpoint URL deliveries are sent to. */
4039
+ endpointUrl = this.field("endpoint_url");
4040
+ /** The webhook's lifecycle status. */
4041
+ status = this.field("status");
4042
+ /** Whether the current endpoint configuration has passed validation. */
4043
+ isValid = this.field("is_valid");
4044
+ /** The event/entity-id filters that gate deliveries. */
4045
+ filters = this.field("filters");
4046
+ /** When the webhook was created. */
4047
+ createdAt = this.field("created_at");
4048
+ /** The owning workspace id: the creator's user id for a personal webhook, or a team id for a team webhook. */
4049
+ workspaceId = this.field("workspace_id");
4050
+ /** The user who registered this webhook. */
4051
+ createdBy = this.mappedField(
4052
+ "created_by_user_id",
4053
+ (id) => User.byId(this.client, id)
4054
+ );
4055
+ /**
4056
+ * Whether this webhook is owned by the caller personally (`user`) or by
4057
+ * their team (`team`). Derived from ownership: a personal webhook's owning
4058
+ * workspace is the creator's own user id, whereas a team webhook's workspace
4059
+ * is a distinct team id.
4060
+ */
4061
+ async scope() {
4062
+ const record = await this.detail.get();
4063
+ return record.workspace_id === record.created_by_user_id ? "user" : "team";
4064
+ }
4065
+ /** Update the webhook. */
4066
+ async update(body) {
4067
+ await this.mutate(
4068
+ (client) => client.storage.patchWebhook({
4069
+ path: { webhook_id: this.id },
4070
+ body
4071
+ })
4072
+ );
4073
+ }
4074
+ /** Rename the webhook. */
4075
+ async rename(name) {
4076
+ await this.update({ name });
4077
+ }
4078
+ /** Point the webhook at a new HTTPS endpoint URL. */
4079
+ async setUrl(url) {
4080
+ await this.update({ endpoint_url: url });
4081
+ }
4082
+ /** Replace the webhook's delivery filters (must be non-empty). */
4083
+ async setFilters(filters) {
4084
+ await this.update({ filters });
4085
+ }
4086
+ /** Pause deliveries. */
4087
+ async pause() {
4088
+ await this.update({ status: "paused" });
4089
+ }
4090
+ /** Resume deliveries. */
4091
+ async resume() {
4092
+ await this.update({ status: "active" });
4093
+ }
4094
+ /** Delete the webhook. */
4095
+ async delete() {
4096
+ await this.mutate(
4097
+ (client) => client.storage.deleteWebhook({
4098
+ path: { webhook_id: this.id }
4099
+ })
4100
+ );
4101
+ }
4102
+ /**
4103
+ * Send a signed validation test delivery to the endpoint and report whether
4104
+ * it was accepted. Drops the cached detail so a subsequent {@link isValid}
4105
+ * read reflects the new validation state.
4106
+ */
4107
+ async validate() {
4108
+ return this.mutate(
4109
+ (client) => client.storage.validateWebhook({
4110
+ path: { webhook_id: this.id }
4111
+ })
4112
+ );
4113
+ }
4114
+ };
4115
+
4116
+ // src/entities/webhooks/namespace.ts
4117
+ var WebhooksNamespace = class {
4118
+ constructor(client) {
4119
+ this.client = client;
4120
+ }
4121
+ client;
4122
+ /**
4123
+ * Register a webhook. `namespace` must be unique among the owning
4124
+ * workspace's webhooks (the endpoint returns 409 on a clash) and cannot be
4125
+ * changed later. `filters` must be non-empty (each entry matches event
4126
+ * names, optionally narrowed to entity ids); `scope` defaults to `'user'`.
4127
+ */
4128
+ create(opts) {
4129
+ return Webhook.create(this.client, opts);
4130
+ }
4131
+ /** A handle to an existing webhook by id. Details load on first access. */
4132
+ byId(id) {
4133
+ return Webhook.byId(this.client, id);
4134
+ }
4135
+ /**
4136
+ * The caller's webhooks across their personal and team workspaces, newest
4137
+ * first. Each returned handle already holds its record.
4138
+ */
4139
+ async list() {
4140
+ const { webhooks } = unwrap(await this.client.storage.listWebhooks());
4141
+ return webhooks.map((record) => Webhook.fromRecord(this.client, record));
4142
+ }
4143
+ };
4144
+
4145
+ // src/macro.ts
4146
+ var Macro = class _Macro {
4147
+ agentSessions;
4148
+ bots;
4149
+ calls;
4150
+ channels;
4151
+ chats;
4152
+ crm;
4153
+ documents;
4154
+ email;
4155
+ favorites;
4156
+ foreignEntities;
4157
+ notifications;
4158
+ pins;
4159
+ projects;
4160
+ properties;
4161
+ tasks;
4162
+ teams;
4163
+ users;
4164
+ webhooks;
4165
+ /** Base URL of the Macro web app, used to build entity URLs. */
4166
+ webAppUrl;
4167
+ /** Direct access to the underlying hey-api service clients. */
4168
+ _client;
4169
+ opts;
4170
+ constructor(opts) {
4171
+ this.opts = opts;
4172
+ const client = new MacroClient(opts);
4173
+ this._client = client;
4174
+ this.agentSessions = new AgentSessionNamespace(client);
4175
+ this.bots = new BotsNamespace(client);
4176
+ this.calls = new CallRecordNamespace(client);
4177
+ this.channels = new ChannelNamespace(client);
4178
+ this.chats = new ChatNamespace(client);
4179
+ this.crm = new CrmNamespace(client);
4180
+ this.documents = new DocumentNamespace(client);
4181
+ this.email = new EmailNamespace(client);
4182
+ this.favorites = new FavoritesNamespace(client);
4183
+ this.foreignEntities = new ForeignEntityNamespace(client);
4184
+ this.notifications = new NotificationNamespace(client);
4185
+ this.pins = new PinsNamespace(client);
4186
+ this.projects = new ProjectNamespace(client);
4187
+ this.properties = new PropertiesNamespace(client);
4188
+ this.tasks = new TaskNamespace(client);
4189
+ this.teams = new TeamNamespace(client);
4190
+ this.users = new UserNamespace(client);
4191
+ this.webhooks = new WebhooksNamespace(client);
4192
+ this.events = client.events;
4193
+ this.webAppUrl = client.webAppUrl;
4194
+ }
4195
+ /**
4196
+ * The authenticated caller's mentionable principal — `bot|<uuid>` for bot
4197
+ * auth, `macro|<email>` for user auth — fetched once and cached.
4198
+ */
4199
+ myPrincipalId() {
4200
+ return this._client.myPrincipalId();
4201
+ }
4202
+ /** Clone of this SDK acting on behalf of `user` (sent as
4203
+ * `x-macro-bot-for-macro-user-id`). Bot auth only — throws for user auth,
4204
+ * since a user token always acts as its own user. */
4205
+ requestedAs(user) {
4206
+ return new _Macro({ ...this.opts, requestedAs: user.id });
4207
+ }
4208
+ };
4209
+ export {
4210
+ Macro,
4211
+ here,
4212
+ msg,
4213
+ toBody,
4214
+ wrapXml
4215
+ };