@todoist/comms-sdk 0.0.1 → 5.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 (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -39
  3. package/dist/esm/authentication.js +247 -0
  4. package/dist/esm/clients/add-comment-helper.js +41 -0
  5. package/dist/esm/clients/attachments-client.js +99 -0
  6. package/dist/esm/clients/base-client.js +30 -0
  7. package/dist/esm/clients/channels-client.js +209 -0
  8. package/dist/esm/clients/comments-client.js +177 -0
  9. package/dist/esm/clients/conversation-messages-client.js +167 -0
  10. package/dist/esm/clients/conversations-client.js +281 -0
  11. package/dist/esm/clients/groups-client.js +170 -0
  12. package/dist/esm/clients/hooks-client.js +50 -0
  13. package/dist/esm/clients/inbox-client.js +186 -0
  14. package/dist/esm/clients/notify-audience.js +43 -0
  15. package/dist/esm/clients/reactions-client.js +96 -0
  16. package/dist/esm/clients/search-client.js +140 -0
  17. package/dist/esm/clients/threads-client.js +363 -0
  18. package/dist/esm/clients/users-client.js +368 -0
  19. package/dist/esm/clients/workspace-users-client.js +299 -0
  20. package/dist/esm/clients/workspaces-client.js +177 -0
  21. package/dist/esm/comms-api.js +67 -0
  22. package/dist/esm/consts/endpoints.js +31 -0
  23. package/dist/esm/index.js +20 -0
  24. package/dist/esm/migration.js +92 -0
  25. package/dist/esm/testUtils/msw-handlers.js +45 -0
  26. package/dist/esm/testUtils/msw-setup.js +32 -0
  27. package/dist/esm/testUtils/obsidian-fetch-adapter.js +50 -0
  28. package/dist/esm/testUtils/test-defaults.js +103 -0
  29. package/dist/esm/transport/fetch-with-retry.js +240 -0
  30. package/dist/esm/transport/http-client.js +53 -0
  31. package/dist/esm/transport/http-dispatcher.js +149 -0
  32. package/dist/esm/types/api-version.js +5 -0
  33. package/dist/esm/types/entities.js +515 -0
  34. package/dist/esm/types/enums.js +34 -0
  35. package/dist/esm/types/errors.js +82 -0
  36. package/dist/esm/types/http.js +1 -0
  37. package/dist/esm/types/index.js +6 -0
  38. package/dist/esm/types/requests.js +184 -0
  39. package/dist/esm/utils/case-conversion.js +47 -0
  40. package/dist/esm/utils/conversation-title.js +110 -0
  41. package/dist/esm/utils/headers.js +29 -0
  42. package/dist/esm/utils/index.js +5 -0
  43. package/dist/esm/utils/multipart-upload.js +198 -0
  44. package/dist/esm/utils/reply-recipients.js +111 -0
  45. package/dist/esm/utils/timestamp-conversion.js +54 -0
  46. package/dist/esm/utils/url-helpers.js +202 -0
  47. package/dist/esm/utils/uuidv7.js +170 -0
  48. package/dist/types/authentication.d.ts +183 -0
  49. package/dist/types/clients/add-comment-helper.d.ts +32 -0
  50. package/dist/types/clients/attachments-client.d.ts +55 -0
  51. package/dist/types/clients/base-client.d.ts +37 -0
  52. package/dist/types/clients/channels-client.d.ts +211 -0
  53. package/dist/types/clients/comments-client.d.ts +228 -0
  54. package/dist/types/clients/conversation-messages-client.d.ts +201 -0
  55. package/dist/types/clients/conversations-client.d.ts +366 -0
  56. package/dist/types/clients/groups-client.d.ts +148 -0
  57. package/dist/types/clients/hooks-client.d.ts +29 -0
  58. package/dist/types/clients/inbox-client.d.ts +478 -0
  59. package/dist/types/clients/notify-audience.d.ts +22 -0
  60. package/dist/types/clients/reactions-client.d.ts +57 -0
  61. package/dist/types/clients/search-client.d.ts +71 -0
  62. package/dist/types/clients/threads-client.d.ts +547 -0
  63. package/dist/types/clients/users-client.d.ts +280 -0
  64. package/dist/types/clients/workspace-users-client.d.ts +172 -0
  65. package/dist/types/clients/workspaces-client.d.ts +154 -0
  66. package/dist/types/comms-api.d.ts +73 -0
  67. package/dist/types/consts/endpoints.d.ts +27 -0
  68. package/dist/types/index.d.ts +21 -0
  69. package/dist/types/migration.d.ts +78 -0
  70. package/dist/types/testUtils/msw-handlers.d.ts +28 -0
  71. package/dist/types/testUtils/msw-setup.d.ts +1 -0
  72. package/dist/types/testUtils/obsidian-fetch-adapter.d.ts +29 -0
  73. package/dist/types/testUtils/test-defaults.d.ts +17 -0
  74. package/dist/types/transport/fetch-with-retry.d.ts +4 -0
  75. package/dist/types/transport/http-client.d.ts +14 -0
  76. package/dist/types/transport/http-dispatcher.d.ts +46 -0
  77. package/dist/types/types/api-version.d.ts +6 -0
  78. package/dist/types/types/entities.d.ts +3081 -0
  79. package/dist/types/types/enums.d.ts +55 -0
  80. package/dist/types/types/errors.d.ts +57 -0
  81. package/dist/types/types/http.d.ts +60 -0
  82. package/dist/types/types/index.d.ts +6 -0
  83. package/dist/types/types/requests.d.ts +604 -0
  84. package/dist/types/utils/case-conversion.d.ts +8 -0
  85. package/dist/types/utils/conversation-title.d.ts +84 -0
  86. package/dist/types/utils/headers.d.ts +13 -0
  87. package/dist/types/utils/index.d.ts +6 -0
  88. package/dist/types/utils/multipart-upload.d.ts +59 -0
  89. package/dist/types/utils/reply-recipients.d.ts +60 -0
  90. package/dist/types/utils/timestamp-conversion.d.ts +13 -0
  91. package/dist/types/utils/url-helpers.d.ts +129 -0
  92. package/dist/types/utils/uuidv7.d.ts +42 -0
  93. package/package.json +80 -8
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Doist
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,188 @@
1
- # @todoist/comms-sdk
1
+ # Comms SDK TypeScript
2
+
3
+ The official TypeScript SDK for the Comms REST API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @todoist/comms-sdk
9
+ ```
10
+
11
+ Versions up to 4.x were published as `@doist/comms-sdk`.
12
+
13
+ ## Usage
2
14
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
15
+ ```typescript
16
+ import { CommsApi } from '@todoist/comms-sdk'
17
+
18
+ const api = new CommsApi('YOUR_API_TOKEN')
19
+
20
+ api.users
21
+ .getSessionUser()
22
+ .then((user) => console.log(user))
23
+ .catch((error) => console.log(error))
24
+ ```
25
+
26
+ By default the SDK targets production at `https://comms.todoist.com`.
27
+ Pass a `baseUrl` option to point at a different deployment — staging
28
+ lives at `https://comms.staging.todoist.com`:
29
+
30
+ ```typescript
31
+ const api = new CommsApi('YOUR_API_TOKEN', {
32
+ baseUrl: 'https://comms.staging.todoist.com',
33
+ })
34
+ ```
4
35
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
36
+ ### Creating entities
6
37
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
38
+ Channel / thread / comment / conversation / message / group IDs are
39
+ opaque base58-encoded UUIDv7 strings; `workspaceId` and `userId` are
40
+ numeric.
41
+
42
+ Creation endpoints (`createChannel`, `createThread`, `createComment`,
43
+ `getOrCreateConversation`, `createMessage`, `createGroup`) accept an
44
+ optional `id`. **A caller-supplied `id` must be a base58-encoded
45
+ UUIDv7** — anything else fails fast with a `UuidV7Error` before the
46
+ request leaves the SDK. Either mint your own with `generateId()` (handy
47
+ for optimistic UI — the ID survives the round-trip unchanged) or omit
48
+ `id` and let the SDK mint one:
49
+
50
+ ```typescript
51
+ import { CommsApi, generateId } from '@todoist/comms-sdk'
8
52
 
9
- ## Purpose
53
+ const api = new CommsApi('YOUR_API_TOKEN')
10
54
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@todoist/comms-sdk`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
55
+ // Option 1: let the SDK mint an ID
56
+ const channel = await api.channels.createChannel({
57
+ workspaceId: 1,
58
+ name: 'Engineering',
59
+ })
60
+
61
+ // Option 2: mint the ID yourself (must be a base58 UUIDv7 from generateId)
62
+ const id = generateId()
63
+ const sameChannel = await api.channels.createChannel({
64
+ workspaceId: 1,
65
+ name: 'Engineering',
66
+ id,
67
+ })
68
+ ```
69
+
70
+ ### Broadcast group markers
71
+
72
+ Use the string constants `EVERYONE` / `EVERYONE_IN_THREAD` when
73
+ populating `groups[]` / `directGroupMentions[]` directly, or pass
74
+ `notifyAudience` to `createComment` / `closeThread` / `reopenThread`
75
+ and let the SDK encode it for you:
76
+
77
+ ```typescript
78
+ await api.comments.createComment({
79
+ threadId,
80
+ content: 'Heads up everyone',
81
+ notifyAudience: 'channel', // encoded as EVERYONE
82
+ })
83
+ ```
84
+
85
+ ### OAuth 2.0
86
+
87
+ ```typescript
88
+ import { getAuthorizationUrl, getAuthToken, CommsApi } from '@todoist/comms-sdk'
89
+
90
+ const authUrl = getAuthorizationUrl(
91
+ 'your-client-id',
92
+ ['user:read', 'channels:read'],
93
+ 'state-parameter',
94
+ 'https://yourapp.com/callback',
95
+ )
96
+
97
+ const tokenResponse = await getAuthToken({
98
+ clientId: 'your-client-id',
99
+ clientSecret: 'your-client-secret',
100
+ code: 'authorization-code',
101
+ redirectUri: 'https://yourapp.com/callback',
102
+ })
103
+
104
+ const api = new CommsApi(tokenResponse.accessToken)
105
+ const user = await api.users.getSessionUser()
106
+ ```
107
+
108
+ Access tokens expire (see `tokenResponse.expiresIn`). When they do, use the
109
+ `refreshToken` from the original exchange to obtain a new one without sending
110
+ the user back through the authorization flow:
111
+
112
+ ```typescript
113
+ import { refreshAuthToken } from '@todoist/comms-sdk'
114
+
115
+ const refreshed = await refreshAuthToken({
116
+ clientId: 'your-client-id',
117
+ clientSecret: 'your-client-secret',
118
+ refreshToken: tokenResponse.refreshToken,
119
+ })
120
+
121
+ // The server may rotate the refresh token — persist refreshed.refreshToken
122
+ // when present, otherwise keep using the previous one.
123
+ const api = new CommsApi(refreshed.accessToken)
124
+ ```
125
+
126
+ ### REST hooks
127
+
128
+ REST hooks require a Todoist OAuth access token with Todoist Comms audience. Subscribe
129
+ with an HTTPS target URL up to 150 characters and one of the exported
130
+ `HOOK_EVENTS`; the backend will POST webhook payloads to that URL when
131
+ matching events happen:
132
+
133
+ ```typescript
134
+ import { CommsApi, HOOK_EVENTS } from '@todoist/comms-sdk'
135
+
136
+ const api = new CommsApi('TODOIST_OAUTH_ACCESS_TOKEN')
137
+
138
+ const subscription = await api.hooks.subscribe({
139
+ targetUrl: 'https://example.com/comms-hook',
140
+ event: 'thread_added',
141
+ workspaceId: 1,
142
+ })
143
+
144
+ console.log(subscription.id, HOOK_EVENTS)
145
+
146
+ await api.hooks.unsubscribe({
147
+ targetUrl: 'https://example.com/comms-hook',
148
+ })
149
+ ```
150
+
151
+ ### Short-lived processes (CLIs, scripts)
152
+
153
+ On Node, the SDK keeps a connection pool alive across requests so HTTP/2
154
+ multiplexing and TLS reuse actually work. Long-running processes don't
155
+ need to think about it. **Short-lived processes should `await api.close()`
156
+ before exit**, otherwise Node's event loop waits ~4 seconds for idle
157
+ sockets to time out:
158
+
159
+ ```typescript
160
+ const api = new CommsApi('YOUR_API_TOKEN')
161
+ try {
162
+ await api.users.getSessionUser()
163
+ } finally {
164
+ await api.close()
165
+ }
166
+ ```
167
+
168
+ `api.close()` drains the process-global pool, so it also covers code
169
+ paths that only use the standalone OAuth helpers (`getAuthToken`,
170
+ `refreshAuthToken`, `revokeAuthToken`, `registerClient`). Those flows can also import
171
+ `closeDefaultDispatcher` directly.
172
+
173
+ ## Development
174
+
175
+ - `npm install`
176
+ - `npm test` — Vitest
177
+ - `npm run type-check` — TypeScript
178
+ - `npm run check` — oxlint + oxfmt
179
+ - `npm run build` — emit CJS + ESM + d.ts
180
+
181
+ ## Releases
15
182
 
16
- ## What is OIDC Trusted Publishing?
17
-
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
19
-
20
- ## Setup Instructions
21
-
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
183
+ The package follows semantic versioning; releases publish to npm via the
184
+ GitHub workflow.
185
+
186
+ ## Feedback
187
+
188
+ Open issues at https://github.com/todoist/comms-sdk-typescript.
@@ -0,0 +1,247 @@
1
+ import { v4 as uuid } from 'uuid';
2
+ import { isSuccess, request } from './transport/http-client.js';
3
+ import { CommsRequestError } from './types/errors.js';
4
+ /**
5
+ * Default origin of the Comms authorization server.
6
+ *
7
+ * The authorization server for Comms is Todoist (`todoist.com`), not the
8
+ * resource server (`comms.todoist.com`). Tokens are issued by Todoist and
9
+ * accepted by the Comms API. Paths match Todoist's published
10
+ * `/.well-known/oauth-authorization-server` metadata.
11
+ */
12
+ const DEFAULT_AUTH_BASE_URL = 'https://todoist.com';
13
+ function getAuthBaseUrl(baseUrl) {
14
+ const base = baseUrl ?? DEFAULT_AUTH_BASE_URL;
15
+ return base.endsWith('/') ? base.slice(0, -1) : base;
16
+ }
17
+ /**
18
+ * OAuth scopes for the Comms API.
19
+ *
20
+ * @remarks
21
+ * Request only the scopes your application needs:
22
+ *
23
+ * **User Scopes:**
24
+ * - `user:read` - Access user's personal settings
25
+ * - `user:write` - Access and update user's personal settings
26
+ *
27
+ * **Workspace Scopes:**
28
+ * - `workspaces:read` - Access teams the user is part of
29
+ * - `workspaces:write` - Access and update teams the user is part of
30
+ *
31
+ * **Channel Scopes:**
32
+ * - `channels:read` - Access channels
33
+ * - `channels:write` - Access and update channels
34
+ * - `channels:remove` - Access, update, and delete channels
35
+ *
36
+ * **Thread Scopes:**
37
+ * - `threads:read` - Access threads
38
+ * - `threads:write` - Access and update threads
39
+ * - `threads:remove` - Access, update, and delete threads
40
+ *
41
+ * **Comment Scopes:**
42
+ * - `comments:read` - Access comments
43
+ * - `comments:write` - Access and update comments
44
+ * - `comments:remove` - Access, update, and delete comments
45
+ *
46
+ * **Group Scopes:**
47
+ * - `groups:read` - Access groups
48
+ * - `groups:write` - Access and update groups
49
+ * - `groups:remove` - Access, update, and delete groups
50
+ *
51
+ * **Message Scopes:**
52
+ * - `messages:read` - Access messages
53
+ * - `messages:write` - Access and update messages
54
+ * - `messages:remove` - Access, update, and delete messages
55
+ *
56
+ * **Reaction Scopes:**
57
+ * - `reactions:read` - Access reactions
58
+ * - `reactions:write` - Access and update reactions
59
+ * - `reactions:remove` - Access, update, and delete reactions
60
+ *
61
+ * **Search Scopes:**
62
+ * - `search:read` - Search
63
+ *
64
+ * **Attachment Scopes:**
65
+ * - `attachments:read` - Access attachments
66
+ * - `attachments:write` - Access and update attachments
67
+ *
68
+ * **Notification Scopes:**
69
+ * - `notifications:read` - Read user's notifications settings
70
+ * - `notifications:write` - Read and update user's notifications settings
71
+ */
72
+ export const COMMS_SCOPES = [
73
+ 'user:read',
74
+ 'user:write',
75
+ 'workspaces:read',
76
+ 'workspaces:write',
77
+ 'channels:read',
78
+ 'channels:write',
79
+ 'channels:remove',
80
+ 'threads:read',
81
+ 'threads:write',
82
+ 'threads:remove',
83
+ 'comments:read',
84
+ 'comments:write',
85
+ 'comments:remove',
86
+ 'groups:read',
87
+ 'groups:write',
88
+ 'groups:remove',
89
+ 'messages:read',
90
+ 'messages:write',
91
+ 'messages:remove',
92
+ 'reactions:read',
93
+ 'reactions:write',
94
+ 'reactions:remove',
95
+ 'search:read',
96
+ 'attachments:read',
97
+ 'attachments:write',
98
+ 'notifications:read',
99
+ 'notifications:write',
100
+ ];
101
+ /** Supported token endpoint authentication methods for dynamic client registration. */
102
+ export const TOKEN_ENDPOINT_AUTH_METHODS = [
103
+ 'client_secret_post',
104
+ 'client_secret_basic',
105
+ 'none',
106
+ ];
107
+ export function getAuthStateParameter() {
108
+ return uuid();
109
+ }
110
+ /**
111
+ * Generates the authorization URL for the OAuth2 flow.
112
+ *
113
+ * The `clientId` can be either a traditional client ID string (e.g. from
114
+ * {@link registerClient}) or an HTTPS URL pointing to a client metadata document,
115
+ * as defined in {@link https://drafts.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/ RFC draft-ietf-oauth-client-id-metadata-document}.
116
+ */
117
+ export function getAuthorizationUrl(clientId, scopes, state, redirectUri, baseUrl) {
118
+ if (!scopes?.length) {
119
+ throw new Error('At least one scope value is required.');
120
+ }
121
+ const authBaseUrl = `${getAuthBaseUrl(baseUrl)}/oauth`;
122
+ const scope = scopes.join(' ');
123
+ const params = new URLSearchParams({
124
+ client_id: clientId,
125
+ response_type: 'code',
126
+ scope,
127
+ state,
128
+ });
129
+ if (redirectUri) {
130
+ params.append('redirect_uri', redirectUri);
131
+ }
132
+ return `${authBaseUrl}/authorize?${params.toString()}`;
133
+ }
134
+ export async function getAuthToken(args, options) {
135
+ const tokenUrl = `${getAuthBaseUrl(options?.baseUrl)}/oauth/access_token`;
136
+ const payload = {
137
+ clientId: args.clientId,
138
+ clientSecret: args.clientSecret,
139
+ code: args.code,
140
+ grantType: 'authorization_code',
141
+ ...(args.redirectUri && { redirectUri: args.redirectUri }),
142
+ };
143
+ const response = await request({
144
+ httpMethod: 'POST',
145
+ baseUri: tokenUrl,
146
+ relativePath: '',
147
+ payload,
148
+ customFetch: options?.customFetch,
149
+ });
150
+ if (!isSuccess(response) || !response.data?.accessToken) {
151
+ throw new CommsRequestError('Authentication token exchange failed.', response.status, response.data);
152
+ }
153
+ return response.data;
154
+ }
155
+ /**
156
+ * Exchanges a refresh token for a new access token using the OAuth2
157
+ * `refresh_token` grant.
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const { accessToken, refreshToken } = await refreshAuthToken({
162
+ * clientId: 'client-id',
163
+ * clientSecret: 'client-secret',
164
+ * refreshToken: storedRefreshToken,
165
+ * })
166
+ * ```
167
+ *
168
+ * @returns The refreshed token. The response may include a new `refreshToken`
169
+ * (rotated by the server); persist it in place of the previous one when present.
170
+ * @throws {@link CommsRequestError} If the refresh fails
171
+ */
172
+ export async function refreshAuthToken(args, options) {
173
+ const tokenUrl = `${getAuthBaseUrl(options?.baseUrl)}/oauth/access_token`;
174
+ const payload = {
175
+ clientId: args.clientId,
176
+ clientSecret: args.clientSecret,
177
+ refreshToken: args.refreshToken,
178
+ grantType: 'refresh_token',
179
+ };
180
+ const response = await request({
181
+ httpMethod: 'POST',
182
+ baseUri: tokenUrl,
183
+ relativePath: '',
184
+ payload,
185
+ customFetch: options?.customFetch,
186
+ });
187
+ if (!isSuccess(response) || !response.data?.accessToken) {
188
+ throw new CommsRequestError('Authentication token refresh failed.', response.status, response.data);
189
+ }
190
+ return response.data;
191
+ }
192
+ export async function revokeAuthToken(args, options) {
193
+ const revokeUrl = `${getAuthBaseUrl(options?.baseUrl)}/api/v1/revoke`;
194
+ const response = await request({
195
+ httpMethod: 'POST',
196
+ baseUri: revokeUrl,
197
+ relativePath: '',
198
+ payload: {
199
+ clientId: args.clientId,
200
+ clientSecret: args.clientSecret,
201
+ token: args.accessToken,
202
+ },
203
+ customFetch: options?.customFetch,
204
+ });
205
+ return isSuccess(response);
206
+ }
207
+ /**
208
+ * Registers a new OAuth client via Dynamic Client Registration (RFC 7591).
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * const client = await registerClient({
213
+ * redirectUris: ['https://example.com/callback'],
214
+ * clientName: 'My App',
215
+ * scope: ['user:read', 'channels:read'],
216
+ * })
217
+ * // Use client.clientId and client.clientSecret for OAuth flows
218
+ * ```
219
+ *
220
+ * @returns The registered client details
221
+ * @throws {@link CommsRequestError} If the registration fails
222
+ * @see {@link https://datatracker.ietf.org/doc/html/rfc7591 RFC 7591}
223
+ */
224
+ export async function registerClient(args, options) {
225
+ const registerUrl = `${getAuthBaseUrl(options?.baseUrl)}/oauth/register`;
226
+ const response = await request({
227
+ httpMethod: 'POST',
228
+ baseUri: registerUrl,
229
+ relativePath: '',
230
+ payload: { ...args, scope: args.scope?.join(' ') },
231
+ customFetch: options?.customFetch,
232
+ });
233
+ if (!isSuccess(response) || !response.data?.clientId) {
234
+ throw new CommsRequestError('Dynamic client registration failed.', response.status, response.data);
235
+ }
236
+ const { clientIdIssuedAt, clientSecretExpiresAt, scope, ...rest } = response.data;
237
+ return {
238
+ ...rest,
239
+ scope: scope ? scope.split(' ') : undefined,
240
+ clientIdIssuedAt: clientIdIssuedAt !== undefined ? new Date(clientIdIssuedAt * 1000) : undefined,
241
+ clientSecretExpiresAt: clientSecretExpiresAt === undefined
242
+ ? undefined
243
+ : clientSecretExpiresAt === 0
244
+ ? null
245
+ : new Date(clientSecretExpiresAt * 1000),
246
+ };
247
+ }
@@ -0,0 +1,41 @@
1
+ import { ENDPOINT_COMMENTS } from '../consts/endpoints.js';
2
+ import { request } from '../transport/http-client.js';
3
+ import { resolveCreateId, resolveReferenceId } from '../utils/uuidv7.js';
4
+ import { applyNotifyAudience } from './notify-audience.js';
5
+ /**
6
+ * Internal helper that powers `comments.createComment`,
7
+ * `threads.closeThread`, and `threads.reopenThread`.
8
+ *
9
+ * Normalizes the `notifyAudience` flag into a sentinel `groups` entry,
10
+ * rejects sentinel IDs passed via `groups` / `directGroupMentions`, mints a
11
+ * UUIDv7 `id` when the caller omits one, and posts to `/comments/add`. When
12
+ * `threadAction` is set (`'close'` / `'reopen'`), it is forwarded on the
13
+ * wire so the same request both adds the comment and transitions the
14
+ * parent thread.
15
+ *
16
+ * @param context - Per-call client context (base URI, API token, optional `customFetch`).
17
+ * @param params - The comment payload (`{@link CreateCommentArgs}`).
18
+ * @param options - Optional configuration.
19
+ * @param options.threadAction - When set, also transitions the parent thread (`'close'` or `'reopen'`).
20
+ * @returns The parsed {@link Comment} returned by the API.
21
+ */
22
+ export function addCommentRequest(context, params, options) {
23
+ const normalized = applyNotifyAudience(params);
24
+ const withId = {
25
+ ...normalized,
26
+ id: resolveCreateId(normalized.id),
27
+ threadId: resolveReferenceId(normalized.threadId, 'threadId'),
28
+ };
29
+ const payload = options?.threadAction
30
+ ? { ...withId, threadAction: options.threadAction }
31
+ : withId;
32
+ return request({
33
+ httpMethod: 'POST',
34
+ baseUri: context.baseUri,
35
+ relativePath: `${ENDPOINT_COMMENTS}/add`,
36
+ apiToken: context.apiToken,
37
+ payload,
38
+ headers: context.headers,
39
+ customFetch: context.customFetch,
40
+ }).then((response) => context.schema.parse(response.data));
41
+ }
@@ -0,0 +1,99 @@
1
+ import { z } from 'zod';
2
+ import { ENDPOINT_ATTACHMENTS, ENDPOINT_FILES } from '../consts/endpoints.js';
3
+ import { request } from '../transport/http-client.js';
4
+ import { AttachmentSchema } from '../types/entities.js';
5
+ import { uploadMultipartFile } from '../utils/multipart-upload.js';
6
+ import { isValidUuidV7Base58, resolveCreateId, resolveReferenceId, UuidV7Error, } from '../utils/uuidv7.js';
7
+ import { BaseClient } from './base-client.js';
8
+ /**
9
+ * Resolve the `attachment_id`: validate a caller-supplied value (throwing an
10
+ * {@link UuidV7Error} that names `attachmentId` rather than the generic `id`) or
11
+ * mint a fresh one. Wraps {@link resolveCreateId} so the error contract matches the
12
+ * client's actual parameter.
13
+ */
14
+ function resolveAttachmentId(attachmentId) {
15
+ if (attachmentId !== undefined && !isValidUuidV7Base58(attachmentId)) {
16
+ throw new UuidV7Error(`invalid attachmentId ${JSON.stringify(attachmentId)} — use generateId() or omit \`attachmentId\` and let the SDK mint one.`);
17
+ }
18
+ return resolveCreateId(attachmentId);
19
+ }
20
+ export const IMAGE_READ_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
21
+ const IMAGE_READ_MAX_BYTES = 5 * 1024 * 1024;
22
+ export const ImageReadResultSchema = z.object({
23
+ mimeType: z.enum(IMAGE_READ_MIME_TYPES),
24
+ // The API allows 5 MiB of image bytes. Base64 encodes each three-byte group
25
+ // as four characters, including padding for the last group.
26
+ dataBase64: z
27
+ .string()
28
+ .min(1)
29
+ .max(4 * Math.ceil(IMAGE_READ_MAX_BYTES / 3))
30
+ .base64(),
31
+ byteLength: z.number().int().positive().max(IMAGE_READ_MAX_BYTES),
32
+ });
33
+ /**
34
+ * Client for uploading attachments and reading thread images.
35
+ *
36
+ * Attachments are uploaded independently, then referenced by passing the returned
37
+ * {@link Attachment} into the `attachments` array of `comments.createComment`,
38
+ * `conversationMessages.createMessage`, and similar calls.
39
+ */
40
+ export class AttachmentsClient extends BaseClient {
41
+ /** Read one thread image under the caller's content scope. */
42
+ async readImage(uploadId, threadId) {
43
+ const id = resolveReferenceId(uploadId, 'uploadId');
44
+ const checkedThreadId = resolveReferenceId(threadId, 'threadId');
45
+ const response = await request({
46
+ httpMethod: 'GET',
47
+ baseUri: this.getBaseUri(),
48
+ relativePath: `${ENDPOINT_FILES}/image/${checkedThreadId}/${id}`,
49
+ apiToken: this.apiToken,
50
+ headers: this.headers,
51
+ customFetch: this.customFetch,
52
+ });
53
+ return ImageReadResultSchema.parse(response.data);
54
+ }
55
+ /**
56
+ * Uploads a file and returns the created {@link Attachment}.
57
+ *
58
+ * Mirrors the canonical multipart upload: `POST /attachments/upload` with the `file`
59
+ * binary plus `workspace_id`, `file_name`, `file_size`, `attachment_id`, and
60
+ * `underlying_type` form fields.
61
+ *
62
+ * @param args - The file to upload and optional metadata.
63
+ * @returns The created attachment, ready to attach to a comment or message.
64
+ *
65
+ * @example
66
+ * ```typescript
67
+ * import { readFile } from 'node:fs/promises'
68
+ *
69
+ * const attachment = await api.attachments.upload({
70
+ * workspaceId: 12345,
71
+ * file: await readFile('./diagram.png'),
72
+ * fileName: 'diagram.png',
73
+ * })
74
+ *
75
+ * await api.comments.createComment({
76
+ * threadId: '7YpL3oZ4kZ9vP7Q1tR2sX3z',
77
+ * content: 'See attached',
78
+ * attachments: [attachment],
79
+ * })
80
+ * ```
81
+ */
82
+ async upload(args) {
83
+ const data = await uploadMultipartFile({
84
+ baseUrl: this.getBaseUri(),
85
+ authToken: this.apiToken,
86
+ endpoint: `${ENDPOINT_ATTACHMENTS}/upload`,
87
+ file: args.file,
88
+ fileName: args.fileName,
89
+ contentType: args.contentType,
90
+ additionalFields: {
91
+ workspace_id: args.workspaceId,
92
+ attachment_id: resolveAttachmentId(args.attachmentId),
93
+ },
94
+ headers: this.headers,
95
+ customFetch: this.customFetch,
96
+ });
97
+ return AttachmentSchema.parse(data);
98
+ }
99
+ }
@@ -0,0 +1,30 @@
1
+ import { getCommsBaseUri } from '../consts/endpoints.js';
2
+ import { DEFAULT_API_VERSION } from '../types/api-version.js';
3
+ /**
4
+ * Base class for every Comms API client. Centralizes URL handling and
5
+ * config so individual clients stay focused on their endpoints.
6
+ */
7
+ export class BaseClient {
8
+ constructor(config) {
9
+ this.apiToken = config.apiToken;
10
+ this.baseUrl = config.baseUrl;
11
+ this.defaultVersion = config.version || DEFAULT_API_VERSION;
12
+ this.customFetch = config.customFetch;
13
+ this.headers = config.headers;
14
+ }
15
+ /**
16
+ * Returns the base URI for an API request, with a guaranteed trailing
17
+ * slash so relative paths resolve cleanly through `URL`.
18
+ */
19
+ getBaseUri() {
20
+ return getCommsBaseUri(this.defaultVersion, this.baseUrl);
21
+ }
22
+ /**
23
+ * Base URL for entity web links, or `undefined` to use getFullCommsURL's
24
+ * default web app. Trailing-slash normalization happens in
25
+ * `getFullCommsURL`, so the configured value is returned verbatim.
26
+ */
27
+ getLinkBaseUrl() {
28
+ return this.baseUrl;
29
+ }
30
+ }