@forumviriumhelsinki/podio-mcp 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +491 -0
  3. package/build/__tests__/integration/setup.integration.d.ts +104 -0
  4. package/build/__tests__/integration/setup.integration.d.ts.map +1 -0
  5. package/build/__tests__/integration/setup.integration.js +233 -0
  6. package/build/__tests__/integration/setup.integration.js.map +1 -0
  7. package/build/__tests__/mock-data/items-mock-data.d.ts +168 -0
  8. package/build/__tests__/mock-data/items-mock-data.d.ts.map +1 -0
  9. package/build/__tests__/mock-data/items-mock-data.js +370 -0
  10. package/build/__tests__/mock-data/items-mock-data.js.map +1 -0
  11. package/build/__tests__/mock-data/notification-mock-data.d.ts +55 -0
  12. package/build/__tests__/mock-data/notification-mock-data.d.ts.map +1 -0
  13. package/build/__tests__/mock-data/notification-mock-data.js +190 -0
  14. package/build/__tests__/mock-data/notification-mock-data.js.map +1 -0
  15. package/build/__tests__/mock-data/project-epic-mock-data.d.ts +45 -0
  16. package/build/__tests__/mock-data/project-epic-mock-data.d.ts.map +1 -0
  17. package/build/__tests__/mock-data/project-epic-mock-data.js +85 -0
  18. package/build/__tests__/mock-data/project-epic-mock-data.js.map +1 -0
  19. package/build/__tests__/mock-data/tasks-mock-data.d.ts +27 -0
  20. package/build/__tests__/mock-data/tasks-mock-data.d.ts.map +1 -0
  21. package/build/__tests__/mock-data/tasks-mock-data.js +104 -0
  22. package/build/__tests__/mock-data/tasks-mock-data.js.map +1 -0
  23. package/build/__tests__/mock-data/utility-mock-data.d.ts +19 -0
  24. package/build/__tests__/mock-data/utility-mock-data.d.ts.map +1 -0
  25. package/build/__tests__/mock-data/utility-mock-data.js +165 -0
  26. package/build/__tests__/mock-data/utility-mock-data.js.map +1 -0
  27. package/build/__tests__/setup.d.ts +8 -0
  28. package/build/__tests__/setup.d.ts.map +1 -0
  29. package/build/__tests__/setup.js +31 -0
  30. package/build/__tests__/setup.js.map +1 -0
  31. package/build/__tests__/utils/test-helpers.d.ts +110 -0
  32. package/build/__tests__/utils/test-helpers.d.ts.map +1 -0
  33. package/build/__tests__/utils/test-helpers.js +222 -0
  34. package/build/__tests__/utils/test-helpers.js.map +1 -0
  35. package/build/api/podio-api-client.d.ts +364 -0
  36. package/build/api/podio-api-client.d.ts.map +1 -0
  37. package/build/api/podio-api-client.js +696 -0
  38. package/build/api/podio-api-client.js.map +1 -0
  39. package/build/cache/app-cache.d.ts +77 -0
  40. package/build/cache/app-cache.d.ts.map +1 -0
  41. package/build/cache/app-cache.js +230 -0
  42. package/build/cache/app-cache.js.map +1 -0
  43. package/build/cache/base-cache-manager.d.ts +149 -0
  44. package/build/cache/base-cache-manager.d.ts.map +1 -0
  45. package/build/cache/base-cache-manager.js +312 -0
  46. package/build/cache/base-cache-manager.js.map +1 -0
  47. package/build/cache/cache-manager.d.ts +230 -0
  48. package/build/cache/cache-manager.d.ts.map +1 -0
  49. package/build/cache/cache-manager.js +362 -0
  50. package/build/cache/cache-manager.js.map +1 -0
  51. package/build/cache/cache-test.d.ts +9 -0
  52. package/build/cache/cache-test.d.ts.map +1 -0
  53. package/build/cache/cache-test.js +169 -0
  54. package/build/cache/cache-test.js.map +1 -0
  55. package/build/cache/index.d.ts +18 -0
  56. package/build/cache/index.d.ts.map +1 -0
  57. package/build/cache/index.js +20 -0
  58. package/build/cache/index.js.map +1 -0
  59. package/build/cache/migration-helper.d.ts +44 -0
  60. package/build/cache/migration-helper.d.ts.map +1 -0
  61. package/build/cache/migration-helper.js +235 -0
  62. package/build/cache/migration-helper.js.map +1 -0
  63. package/build/cache/project-epic-cache.d.ts +108 -0
  64. package/build/cache/project-epic-cache.d.ts.map +1 -0
  65. package/build/cache/project-epic-cache.js +278 -0
  66. package/build/cache/project-epic-cache.js.map +1 -0
  67. package/build/cache/space-members-cache.d.ts +99 -0
  68. package/build/cache/space-members-cache.d.ts.map +1 -0
  69. package/build/cache/space-members-cache.js +305 -0
  70. package/build/cache/space-members-cache.js.map +1 -0
  71. package/build/cache/storage-adapters.d.ts +100 -0
  72. package/build/cache/storage-adapters.d.ts.map +1 -0
  73. package/build/cache/storage-adapters.js +297 -0
  74. package/build/cache/storage-adapters.js.map +1 -0
  75. package/build/errors/api-errors.d.ts +52 -0
  76. package/build/errors/api-errors.d.ts.map +1 -0
  77. package/build/errors/api-errors.js +86 -0
  78. package/build/errors/api-errors.js.map +1 -0
  79. package/build/errors/auth-errors.d.ts +67 -0
  80. package/build/errors/auth-errors.d.ts.map +1 -0
  81. package/build/errors/auth-errors.js +114 -0
  82. package/build/errors/auth-errors.js.map +1 -0
  83. package/build/errors/base.d.ts +102 -0
  84. package/build/errors/base.d.ts.map +1 -0
  85. package/build/errors/base.js +131 -0
  86. package/build/errors/base.js.map +1 -0
  87. package/build/errors/cache-errors.d.ts +53 -0
  88. package/build/errors/cache-errors.d.ts.map +1 -0
  89. package/build/errors/cache-errors.js +83 -0
  90. package/build/errors/cache-errors.js.map +1 -0
  91. package/build/errors/config-errors.d.ts +58 -0
  92. package/build/errors/config-errors.d.ts.map +1 -0
  93. package/build/errors/config-errors.js +96 -0
  94. package/build/errors/config-errors.js.map +1 -0
  95. package/build/errors/index.d.ts +101 -0
  96. package/build/errors/index.d.ts.map +1 -0
  97. package/build/errors/index.js +135 -0
  98. package/build/errors/index.js.map +1 -0
  99. package/build/errors/structure-errors.d.ts +89 -0
  100. package/build/errors/structure-errors.d.ts.map +1 -0
  101. package/build/errors/structure-errors.js +182 -0
  102. package/build/errors/structure-errors.js.map +1 -0
  103. package/build/errors/validation-errors.d.ts +81 -0
  104. package/build/errors/validation-errors.d.ts.map +1 -0
  105. package/build/errors/validation-errors.js +169 -0
  106. package/build/errors/validation-errors.js.map +1 -0
  107. package/build/fields/field-mapper.d.ts +245 -0
  108. package/build/fields/field-mapper.d.ts.map +1 -0
  109. package/build/fields/field-mapper.js +404 -0
  110. package/build/fields/field-mapper.js.map +1 -0
  111. package/build/index.d.ts +550 -0
  112. package/build/index.d.ts.map +1 -0
  113. package/build/index.js +1527 -0
  114. package/build/index.js.map +1 -0
  115. package/build/oauth-helper.d.ts +189 -0
  116. package/build/oauth-helper.d.ts.map +1 -0
  117. package/build/oauth-helper.js +422 -0
  118. package/build/oauth-helper.js.map +1 -0
  119. package/build/services/app-structure-service.d.ts +49 -0
  120. package/build/services/app-structure-service.d.ts.map +1 -0
  121. package/build/services/app-structure-service.js +122 -0
  122. package/build/services/app-structure-service.js.map +1 -0
  123. package/build/services/code-execution-service.d.ts +88 -0
  124. package/build/services/code-execution-service.d.ts.map +1 -0
  125. package/build/services/code-execution-service.js +342 -0
  126. package/build/services/code-execution-service.js.map +1 -0
  127. package/build/services/comment-service.d.ts +66 -0
  128. package/build/services/comment-service.d.ts.map +1 -0
  129. package/build/services/comment-service.js +139 -0
  130. package/build/services/comment-service.js.map +1 -0
  131. package/build/services/index.d.ts +16 -0
  132. package/build/services/index.d.ts.map +1 -0
  133. package/build/services/index.js +15 -0
  134. package/build/services/index.js.map +1 -0
  135. package/build/services/item-service.d.ts +104 -0
  136. package/build/services/item-service.d.ts.map +1 -0
  137. package/build/services/item-service.js +368 -0
  138. package/build/services/item-service.js.map +1 -0
  139. package/build/services/notification-service.d.ts +125 -0
  140. package/build/services/notification-service.d.ts.map +1 -0
  141. package/build/services/notification-service.js +321 -0
  142. package/build/services/notification-service.js.map +1 -0
  143. package/build/services/project-epic-service.d.ts +73 -0
  144. package/build/services/project-epic-service.d.ts.map +1 -0
  145. package/build/services/project-epic-service.js +248 -0
  146. package/build/services/project-epic-service.js.map +1 -0
  147. package/build/services/response-formatter.d.ts +190 -0
  148. package/build/services/response-formatter.d.ts.map +1 -0
  149. package/build/services/response-formatter.js +1221 -0
  150. package/build/services/response-formatter.js.map +1 -0
  151. package/build/services/search-service.d.ts +103 -0
  152. package/build/services/search-service.d.ts.map +1 -0
  153. package/build/services/search-service.js +273 -0
  154. package/build/services/search-service.js.map +1 -0
  155. package/build/services/task-service.d.ts +70 -0
  156. package/build/services/task-service.d.ts.map +1 -0
  157. package/build/services/task-service.js +156 -0
  158. package/build/services/task-service.js.map +1 -0
  159. package/build/tools/index.d.ts +8 -0
  160. package/build/tools/index.d.ts.map +1 -0
  161. package/build/tools/index.js +8 -0
  162. package/build/tools/index.js.map +1 -0
  163. package/build/tools/tool-definitions.d.ts +89 -0
  164. package/build/tools/tool-definitions.d.ts.map +1 -0
  165. package/build/tools/tool-definitions.js +1167 -0
  166. package/build/tools/tool-definitions.js.map +1 -0
  167. package/build/types/api-types.d.ts +106 -0
  168. package/build/types/api-types.d.ts.map +1 -0
  169. package/build/types/api-types.js +11 -0
  170. package/build/types/api-types.js.map +1 -0
  171. package/build/types/cache-types.d.ts +52 -0
  172. package/build/types/cache-types.d.ts.map +1 -0
  173. package/build/types/cache-types.js +12 -0
  174. package/build/types/cache-types.js.map +1 -0
  175. package/build/types/index.d.ts +31 -0
  176. package/build/types/index.d.ts.map +1 -0
  177. package/build/types/index.js +25 -0
  178. package/build/types/index.js.map +1 -0
  179. package/build/types/notification-types.d.ts +154 -0
  180. package/build/types/notification-types.d.ts.map +1 -0
  181. package/build/types/notification-types.js +7 -0
  182. package/build/types/notification-types.js.map +1 -0
  183. package/build/types/podio-types.d.ts +250 -0
  184. package/build/types/podio-types.d.ts.map +1 -0
  185. package/build/types/podio-types.js +11 -0
  186. package/build/types/podio-types.js.map +1 -0
  187. package/build/types/search-types.d.ts +188 -0
  188. package/build/types/search-types.d.ts.map +1 -0
  189. package/build/types/search-types.js +43 -0
  190. package/build/types/search-types.js.map +1 -0
  191. package/build/utils/debug.d.ts +58 -0
  192. package/build/utils/debug.d.ts.map +1 -0
  193. package/build/utils/debug.js +147 -0
  194. package/build/utils/debug.js.map +1 -0
  195. package/examples/claude-config-example.json +13 -0
  196. package/package.json +87 -0
  197. package/scripts/generate-claude-config.js +107 -0
@@ -0,0 +1,422 @@
1
+ /**
2
+ * @fileoverview OAuth2 authentication helper for Podio API integration.
3
+ *
4
+ * This module handles the complete OAuth2 flow for Podio authentication,
5
+ * including browser-based authorization, token storage, and automatic refresh.
6
+ * It provides a seamless authentication experience for the MCP server.
7
+ *
8
+ * @version 0.1.0
9
+ * @author Podio MCP Team
10
+ */
11
+ import http from 'http';
12
+ import { URL } from 'url';
13
+ import { spawn } from 'child_process';
14
+ import fs from 'fs/promises';
15
+ import path from 'path';
16
+ import os from 'os';
17
+ /**
18
+ * OAuth2 authentication helper for Podio API.
19
+ *
20
+ * Manages the complete OAuth2 authentication flow including:
21
+ * - Browser-based authorization with automatic browser launching
22
+ * - Local HTTP server for handling OAuth callbacks
23
+ * - Secure token storage in user's config directory
24
+ * - Automatic token refresh when nearing expiration
25
+ * - Cross-platform browser opening support
26
+ *
27
+ * The helper automatically handles token lifecycle management,
28
+ * ensuring the application always has valid credentials for API access.
29
+ *
30
+ * @class PodioOAuthHelper
31
+ * @example
32
+ * ```typescript
33
+ * const oauth = new PodioOAuthHelper(
34
+ * 'your-client-id',
35
+ * 'your-client-secret',
36
+ * 'http://localhost:8080/callback'
37
+ * );
38
+ *
39
+ * const token = await oauth.getValidToken();
40
+ * // Use token for API requests
41
+ * ```
42
+ */
43
+ export class PodioOAuthHelper {
44
+ /** Podio OAuth2 client ID */
45
+ clientId;
46
+ /** Podio OAuth2 client secret */
47
+ clientSecret;
48
+ /** OAuth2 redirect URI for callback handling */
49
+ redirectUri;
50
+ /** File system path where tokens are stored */
51
+ tokenPath;
52
+ /**
53
+ * Initialize the OAuth helper with Podio app credentials.
54
+ *
55
+ * Sets up the OAuth configuration and determines the token storage location
56
+ * in the user's config directory (~/.config/podio-mcp/token.json).
57
+ *
58
+ * @param clientId - Your Podio app's client ID from the Podio Developer portal
59
+ * @param clientSecret - Your Podio app's client secret
60
+ * @param redirectUri - OAuth redirect URI (must match your app configuration)
61
+ * @constructor
62
+ */
63
+ constructor(clientId, clientSecret, redirectUri) {
64
+ this.clientId = clientId;
65
+ this.clientSecret = clientSecret;
66
+ this.redirectUri = redirectUri;
67
+ // Set up token storage path
68
+ const configDir = path.join(os.homedir(), '.config', 'podio-mcp');
69
+ this.tokenPath = path.join(configDir, 'token.json');
70
+ }
71
+ /**
72
+ * Ensure the configuration directory exists for token storage.
73
+ *
74
+ * Creates the ~/.config/podio-mcp directory if it doesn't exist.
75
+ * Uses recursive creation to handle missing parent directories.
76
+ *
77
+ * @private
78
+ * @returns Promise that resolves when directory is ensured to exist
79
+ */
80
+ async ensureConfigDir() {
81
+ const configDir = path.dirname(this.tokenPath);
82
+ try {
83
+ await fs.mkdir(configDir, { recursive: true });
84
+ }
85
+ catch (error) {
86
+ // Directory might already exist, ignore error
87
+ }
88
+ }
89
+ /**
90
+ * Load a previously stored OAuth token from disk.
91
+ *
92
+ * Reads the token file and validates expiration. If the token is expired,
93
+ * the file is automatically cleaned up.
94
+ *
95
+ * @private
96
+ * @returns Promise resolving to stored token data or null if not found/expired
97
+ */
98
+ async loadStoredToken() {
99
+ try {
100
+ const tokenData = await fs.readFile(this.tokenPath, 'utf8');
101
+ const stored = JSON.parse(tokenData);
102
+ // Check if token is expired
103
+ const now = Math.floor(Date.now() / 1000);
104
+ if (now >= stored.expires_at) {
105
+ // Token is expired, remove the file
106
+ await fs.unlink(this.tokenPath);
107
+ return null;
108
+ }
109
+ return stored;
110
+ }
111
+ catch (error) {
112
+ // File doesn't exist or is corrupted
113
+ return null;
114
+ }
115
+ }
116
+ /**
117
+ * Store OAuth tokens securely to disk.
118
+ *
119
+ * Converts the API response to our storage format and calculates
120
+ * the absolute expiration timestamp. Ensures the config directory exists.
121
+ *
122
+ * @private
123
+ * @param tokenResponse - Raw OAuth token response from Podio API
124
+ * @returns Promise that resolves when token is stored
125
+ */
126
+ async storeToken(tokenResponse) {
127
+ await this.ensureConfigDir();
128
+ const now = Math.floor(Date.now() / 1000);
129
+ const stored = {
130
+ access_token: tokenResponse.access_token,
131
+ refresh_token: tokenResponse.refresh_token,
132
+ expires_at: now + tokenResponse.expires_in,
133
+ };
134
+ await fs.writeFile(this.tokenPath, JSON.stringify(stored, null, 2));
135
+ }
136
+ /**
137
+ * Refresh an expired OAuth token using the refresh token.
138
+ *
139
+ * Makes a token refresh request to Podio and stores the new tokens.
140
+ * This extends the authentication session without user interaction.
141
+ *
142
+ * @private
143
+ * @param refreshToken - The refresh token from the original authorization
144
+ * @returns Promise resolving to the new token response
145
+ * @throws Error if the refresh request fails
146
+ */
147
+ async refreshToken(refreshToken) {
148
+ const params = new URLSearchParams({
149
+ grant_type: 'refresh_token',
150
+ client_id: this.clientId,
151
+ client_secret: this.clientSecret,
152
+ refresh_token: refreshToken,
153
+ });
154
+ const response = await fetch('https://api.podio.com/oauth/token', {
155
+ method: 'POST',
156
+ headers: {
157
+ 'Content-Type': 'application/x-www-form-urlencoded',
158
+ },
159
+ body: params,
160
+ });
161
+ if (!response.ok) {
162
+ throw new Error(`Failed to refresh token: ${response.statusText}`);
163
+ }
164
+ const tokenResponse = await response.json();
165
+ await this.storeToken(tokenResponse);
166
+ return tokenResponse;
167
+ }
168
+ /**
169
+ * Get a valid OAuth token, handling all authentication scenarios.
170
+ *
171
+ * This is the main entry point for obtaining tokens. It:
172
+ * 1. Checks for existing valid tokens
173
+ * 2. Refreshes tokens that are near expiration (< 10 minutes)
174
+ * 3. Falls back to full OAuth flow if needed
175
+ * 4. Handles refresh failures gracefully
176
+ *
177
+ * @public
178
+ * @returns Promise resolving to a valid access token
179
+ * @throws Error if authentication fails completely
180
+ */
181
+ async getValidToken() {
182
+ // Try to load stored token
183
+ const stored = await this.loadStoredToken();
184
+ if (stored) {
185
+ const now = Math.floor(Date.now() / 1000);
186
+ // If token expires in less than 10 minutes, refresh it
187
+ if (stored.expires_at - now < 600) {
188
+ try {
189
+ const refreshed = await this.refreshToken(stored.refresh_token);
190
+ return refreshed.access_token;
191
+ }
192
+ catch (error) {
193
+ // Refresh failed, need to re-authenticate
194
+ return await this.performOAuthFlow();
195
+ }
196
+ }
197
+ else {
198
+ return stored.access_token;
199
+ }
200
+ }
201
+ // No valid token, perform OAuth flow
202
+ return await this.performOAuthFlow();
203
+ }
204
+ /**
205
+ * Try to start a server on the given port with fallback options.
206
+ *
207
+ * Attempts to start an HTTP server on the specified port. If that fails,
208
+ * tries alternative ports in sequence.
209
+ *
210
+ * @private
211
+ * @param server - The HTTP server to start
212
+ * @param host - The hostname to bind to
213
+ * @param preferredPort - The preferred port to use
214
+ * @param fallbackPorts - Alternative ports to try if preferred fails
215
+ * @returns Promise resolving to the actual port used
216
+ * @throws Error if no ports are available
217
+ */
218
+ async tryStartServer(server, host, preferredPort, fallbackPorts = [8090, 8100, 8888, 9090]) {
219
+ const portsToTry = [preferredPort, ...fallbackPorts];
220
+ for (let i = 0; i < portsToTry.length; i++) {
221
+ const port = portsToTry[i];
222
+ try {
223
+ await new Promise((resolve, reject) => {
224
+ server.once('error', reject);
225
+ server.listen(port, host, () => {
226
+ server.removeListener('error', reject);
227
+ resolve();
228
+ });
229
+ });
230
+ console.error(`OAuth callback server started successfully on port ${port}`);
231
+ return port;
232
+ }
233
+ catch (err) {
234
+ // Clean up server event listeners on error
235
+ server.removeAllListeners('error');
236
+ // If this is the last port to try, throw a detailed error
237
+ if (i === portsToTry.length - 1) {
238
+ const triedPorts = portsToTry.join(', ');
239
+ throw new Error(`Unable to start OAuth callback server. All ports are in use (${triedPorts}). ` +
240
+ `SOLUTION: Please either (1) stop the service using one of these ports, or ` +
241
+ `(2) configure a custom redirect URI with a different port in your Podio app settings ` +
242
+ `and update your PODIO_REDIRECT_URI environment variable accordingly.`);
243
+ }
244
+ // Port is in use, try the next one
245
+ if (err.code === 'EADDRINUSE') {
246
+ console.error(`Port ${port} is already in use, trying next port...`);
247
+ }
248
+ }
249
+ }
250
+ // This should never be reached due to the throw above, but TypeScript needs it
251
+ throw new Error('Failed to start server on any available port');
252
+ }
253
+ /**
254
+ * Perform the complete OAuth2 authorization flow.
255
+ *
256
+ * Creates a local HTTP server to handle the OAuth callback,
257
+ * opens the user's browser to the Podio authorization page,
258
+ * and waits for the authorization code to complete the flow.
259
+ *
260
+ * Includes timeout handling, cross-platform browser support,
261
+ * and automatic port fallback if the preferred port is in use.
262
+ *
263
+ * @private
264
+ * @returns Promise resolving to the access token
265
+ * @throws Error if the OAuth flow fails or times out
266
+ */
267
+ async performOAuthFlow() {
268
+ return new Promise(async (resolve, reject) => {
269
+ const url = new URL(this.redirectUri);
270
+ const preferredPort = parseInt(url.port) || 8080;
271
+ const host = url.hostname || 'localhost';
272
+ const pathname = url.pathname || '/callback';
273
+ // Declare actualPort in outer scope so it's available to server callback
274
+ let actualPort;
275
+ // Declare timeout ID so it can be cleared on success
276
+ let timeoutId;
277
+ // Create HTTP server to handle callback
278
+ const server = http.createServer(async (req, res) => {
279
+ if (req.url?.startsWith(pathname)) {
280
+ const callbackUrl = new URL(req.url, `http://${host}:${actualPort}`);
281
+ const code = callbackUrl.searchParams.get('code');
282
+ const error = callbackUrl.searchParams.get('error');
283
+ if (error) {
284
+ res.writeHead(400, { 'Content-Type': 'text/html' });
285
+ res.end(`<h1>Error</h1><p>Authentication failed: ${error}</p>`);
286
+ clearTimeout(timeoutId);
287
+ server.close();
288
+ reject(new Error(`Authentication failed: ${error}`));
289
+ return;
290
+ }
291
+ if (code) {
292
+ try {
293
+ const tokenResponse = await this.exchangeCodeForToken(code);
294
+ await this.storeToken(tokenResponse);
295
+ res.writeHead(200, { 'Content-Type': 'text/html' });
296
+ res.end('<h1>Success!</h1><p>Authentication successful. You can close this tab.</p>');
297
+ clearTimeout(timeoutId);
298
+ server.close();
299
+ resolve(tokenResponse.access_token);
300
+ }
301
+ catch (exchangeError) {
302
+ res.writeHead(500, { 'Content-Type': 'text/html' });
303
+ res.end(`<h1>Error</h1><p>Failed to exchange code for token: ${exchangeError}</p>`);
304
+ clearTimeout(timeoutId);
305
+ server.close();
306
+ reject(exchangeError);
307
+ }
308
+ }
309
+ else {
310
+ res.writeHead(400, { 'Content-Type': 'text/html' });
311
+ res.end('<h1>Error</h1><p>No authorization code received</p>');
312
+ clearTimeout(timeoutId);
313
+ server.close();
314
+ reject(new Error('No authorization code received'));
315
+ }
316
+ }
317
+ else {
318
+ res.writeHead(404, { 'Content-Type': 'text/html' });
319
+ res.end('<h1>404 Not Found</h1>');
320
+ }
321
+ });
322
+ // Try to start the server with fallback ports
323
+ try {
324
+ actualPort = await this.tryStartServer(server, host, preferredPort);
325
+ // Update the redirect URI with the actual port if it's different
326
+ const actualRedirectUri = preferredPort !== actualPort
327
+ ? this.redirectUri.replace(`:${preferredPort}`, `:${actualPort}`)
328
+ : this.redirectUri;
329
+ // Note: If using a different port, the user needs to update their Podio app settings
330
+ if (preferredPort !== actualPort) {
331
+ console.error(`\n⚠️ IMPORTANT: OAuth callback server is running on port ${actualPort} instead of ${preferredPort}.`);
332
+ console.error(` You may need to update your Podio app's redirect URI to: ${actualRedirectUri}`);
333
+ console.error(` Or stop the service using port ${preferredPort} and restart.\n`);
334
+ }
335
+ const authUrl = `https://podio.com/oauth/authorize?client_id=${this.clientId}&redirect_uri=${encodeURIComponent(actualRedirectUri)}&scope=read&response_type=code`;
336
+ console.error(`Starting OAuth flow...`);
337
+ console.error(`Opening browser to: ${authUrl}`);
338
+ // Try to open the browser
339
+ this.openBrowser(authUrl);
340
+ // Set a timeout for the OAuth flow
341
+ timeoutId = setTimeout(() => {
342
+ server.close();
343
+ reject(new Error('OAuth flow timed out after 3 minutes'));
344
+ }, 180000); // 3 minutes
345
+ }
346
+ catch (err) {
347
+ reject(err);
348
+ }
349
+ });
350
+ }
351
+ /**
352
+ * Exchange an authorization code for OAuth tokens.
353
+ *
354
+ * Makes the final OAuth request to convert the authorization code
355
+ * into access and refresh tokens.
356
+ *
357
+ * @private
358
+ * @param code - Authorization code received from the OAuth callback
359
+ * @returns Promise resolving to the token response from Podio
360
+ * @throws Error if the token exchange fails
361
+ */
362
+ async exchangeCodeForToken(code) {
363
+ const params = new URLSearchParams({
364
+ grant_type: 'authorization_code',
365
+ client_id: this.clientId,
366
+ redirect_uri: this.redirectUri,
367
+ client_secret: this.clientSecret,
368
+ code: code,
369
+ });
370
+ const response = await fetch('https://api.podio.com/oauth/token', {
371
+ method: 'POST',
372
+ headers: {
373
+ 'Content-Type': 'application/x-www-form-urlencoded',
374
+ },
375
+ body: params,
376
+ });
377
+ if (!response.ok) {
378
+ const errorText = await response.text();
379
+ throw new Error(`Failed to exchange code for token: ${response.status} ${errorText}`);
380
+ }
381
+ return await response.json();
382
+ }
383
+ /**
384
+ * Open a URL in the user's default browser across different platforms.
385
+ *
386
+ * Handles cross-platform browser launching using platform-specific commands:
387
+ * - macOS: `open`
388
+ * - Windows: `cmd /c start`
389
+ * - Linux/Others: `xdg-open`
390
+ *
391
+ * The child process is detached and unreferenced to avoid blocking
392
+ * the main application.
393
+ *
394
+ * @private
395
+ * @param url - The URL to open in the browser
396
+ */
397
+ openBrowser(url) {
398
+ const platform = process.platform;
399
+ let command;
400
+ let args;
401
+ switch (platform) {
402
+ case 'darwin': // macOS
403
+ command = 'open';
404
+ args = [url];
405
+ break;
406
+ case 'win32': // Windows
407
+ command = 'cmd';
408
+ args = ['/c', 'start', url];
409
+ break;
410
+ default: // Linux and others
411
+ command = 'xdg-open';
412
+ args = [url];
413
+ break;
414
+ }
415
+ const child = spawn(command, args, {
416
+ detached: true,
417
+ stdio: 'ignore',
418
+ });
419
+ child.unref();
420
+ }
421
+ }
422
+ //# sourceMappingURL=oauth-helper.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauth-helper.js","sourceRoot":"","sources":["../src/oauth-helper.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,MAAM,aAAa,CAAC;AAC7B,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,MAAM,IA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,KAAK,CAAC;gBAChB,IAAI,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,CAAC,CAAC;gBAC5B,MAAM;YACR,SAAS,mBAAmB;gBAC1B,OAAO,GAAG,UAAU,CAAC;gBACrB,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;gBACb,MAAM;QACV,CAAC;QAED,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,EAAE,IAAI,EAAE;YACjC,QAAQ,EAAE,IAAI;YACd,KAAK,EAAE,QAAQ;SAChB,CAAC,CAAC;QAEH,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;CACF"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * @fileoverview App Structure Service
3
+ *
4
+ * This service handles all app structure related operations including
5
+ * loading, caching, and coordinate resolution.
6
+ */
7
+ import type { PodioApiClient } from '../api/podio-api-client.js';
8
+ import type { CacheManager } from '../cache/cache-manager.js';
9
+ import { FieldMapper } from '../fields/field-mapper.js';
10
+ import type { AppStructure, AppCoordinates } from '../types/index.js';
11
+ /**
12
+ * Service class for handling app structure operations.
13
+ *
14
+ * This class encapsulates all app structure related business logic
15
+ * and coordinates between the API client, cache manager, and field mapper.
16
+ */
17
+ export declare class AppStructureService {
18
+ private readonly apiClient;
19
+ private readonly cacheManager;
20
+ constructor(apiClient: PodioApiClient, cacheManager: CacheManager);
21
+ /**
22
+ * Load app structure with caching
23
+ */
24
+ loadAppStructure(coordinates: AppCoordinates, forceRefresh?: boolean): Promise<{
25
+ structure: AppStructure;
26
+ fieldMapper: FieldMapper;
27
+ }>;
28
+ /**
29
+ * Resolve app coordinates from arguments only (no environment variable fallbacks)
30
+ */
31
+ resolveAppCoordinates(args: any): AppCoordinates | null;
32
+ /**
33
+ * Cache app structure by coordinates
34
+ */
35
+ cacheAppStructure(coordinates: AppCoordinates): Promise<void>;
36
+ /**
37
+ * Get all cached apps
38
+ */
39
+ getAllCachedApps(): Promise<import("../types/cache-types.js").CachedApp[]>;
40
+ /**
41
+ * Refresh app cache
42
+ */
43
+ refreshAppCache(appId?: number): Promise<void>;
44
+ /**
45
+ * Clear app cache
46
+ */
47
+ clearAppCache(appId?: number): Promise<void>;
48
+ }
49
+ //# sourceMappingURL=app-structure-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app-structure-service.d.ts","sourceRoot":"","sources":["../../src/services/app-structure-service.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAGtE;;;;;GAKG;AACH,qBAAa,mBAAmB;IAE5B,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,YAAY;gBADZ,SAAS,EAAE,cAAc,EACzB,YAAY,EAAE,YAAY;IAG7C;;OAEG;IACG,gBAAgB,CACpB,WAAW,EAAE,cAAc,EAC3B,YAAY,UAAQ,GACnB,OAAO,CAAC;QAAE,SAAS,EAAE,YAAY,CAAC;QAAC,WAAW,EAAE,WAAW,CAAA;KAAE,CAAC;IAqDjE;;OAEG;IACH,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,cAAc,GAAG,IAAI;IA4BvD;;OAEG;IACG,iBAAiB,CAAC,WAAW,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAInE;;OAEG;IACG,gBAAgB;IAItB;;OAEG;IACG,eAAe,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAQpD;;OAEG;IACG,aAAa,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAOnD"}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @fileoverview App Structure Service
3
+ *
4
+ * This service handles all app structure related operations including
5
+ * loading, caching, and coordinate resolution.
6
+ */
7
+ import { FieldMapper } from '../fields/field-mapper.js';
8
+ import { isPodioApiError } from '../errors/index.js';
9
+ /**
10
+ * Service class for handling app structure operations.
11
+ *
12
+ * This class encapsulates all app structure related business logic
13
+ * and coordinates between the API client, cache manager, and field mapper.
14
+ */
15
+ export class AppStructureService {
16
+ apiClient;
17
+ cacheManager;
18
+ constructor(apiClient, cacheManager) {
19
+ this.apiClient = apiClient;
20
+ this.cacheManager = cacheManager;
21
+ }
22
+ /**
23
+ * Load app structure with caching
24
+ */
25
+ async loadAppStructure(coordinates, forceRefresh = false) {
26
+ try {
27
+ // Check cache first (unless forcing refresh)
28
+ if (!forceRefresh) {
29
+ const cachedApp = await this.cacheManager.getAppByCoordinates(coordinates);
30
+ if (cachedApp) {
31
+ // Convert AppField[] to PodioField[] for FieldMapper
32
+ const podioFields = cachedApp.structure.fields.map((field) => ({
33
+ ...field,
34
+ values: [], // AppField doesn't have values, but PodioField needs it
35
+ }));
36
+ const fieldMapper = new FieldMapper(podioFields);
37
+ console.error(`✅ Loaded app structure from cache: ${cachedApp.name}`);
38
+ return { structure: cachedApp.structure, fieldMapper };
39
+ }
40
+ }
41
+ console.error('Cache miss or forced refresh - fetching from API...');
42
+ // Fetch from API using the API client
43
+ const appStructure = await this.apiClient.get(`/app/org/${coordinates.org_label}/space/${coordinates.space_label}/${coordinates.app_label}`);
44
+ // Create field mapper
45
+ const podioFields = appStructure.data.fields.map((field) => ({
46
+ ...field,
47
+ values: [], // AppField doesn't have values, but PodioField needs it
48
+ }));
49
+ const fieldMapper = new FieldMapper(podioFields);
50
+ // Cache the structure
51
+ const appName = appStructure.data.config?.name || appStructure.data.name || coordinates.app_label;
52
+ await this.cacheManager.cacheApp(coordinates, appStructure.data, appName);
53
+ console.error(`✅ Loaded and cached app structure: ${appName}`);
54
+ return { structure: appStructure.data, fieldMapper };
55
+ }
56
+ catch (error) {
57
+ if (isPodioApiError(error)) {
58
+ // Handle cache refresh for structure mismatches
59
+ await this.cacheManager.handleApiErrorWithCacheRefresh(error, coordinates, 'load app structure');
60
+ }
61
+ throw error;
62
+ }
63
+ }
64
+ /**
65
+ * Resolve app coordinates from arguments only (no environment variable fallbacks)
66
+ */
67
+ resolveAppCoordinates(args) {
68
+ // Helper to check for placeholder values
69
+ const isPlaceholder = (value) => value &&
70
+ (value.includes('your_') ||
71
+ value.includes('_label') ||
72
+ value === 'organization' ||
73
+ value === 'space' ||
74
+ value === 'app');
75
+ const org_label = args.org_label && !isPlaceholder(args.org_label) ? args.org_label : null;
76
+ const space_label = args.space_label && !isPlaceholder(args.space_label) ? args.space_label : null;
77
+ const app_label = args.app_label && !isPlaceholder(args.app_label) ? args.app_label : null;
78
+ if (!org_label || !space_label || !app_label) {
79
+ console.error('App coordinates must be provided explicitly:', {
80
+ provided: { org_label, space_label, app_label },
81
+ required: 'All three coordinates (org_label, space_label, app_label) are required',
82
+ });
83
+ return null;
84
+ }
85
+ return { org_label, space_label, app_label };
86
+ }
87
+ /**
88
+ * Cache app structure by coordinates
89
+ */
90
+ async cacheAppStructure(coordinates) {
91
+ await this.loadAppStructure(coordinates, true);
92
+ }
93
+ /**
94
+ * Get all cached apps
95
+ */
96
+ async getAllCachedApps() {
97
+ return await this.cacheManager.getAllCachedApps();
98
+ }
99
+ /**
100
+ * Refresh app cache
101
+ */
102
+ async refreshAppCache(appId) {
103
+ if (appId) {
104
+ await this.cacheManager.removeAppById(appId);
105
+ }
106
+ else {
107
+ await this.cacheManager.refreshAppCache();
108
+ }
109
+ }
110
+ /**
111
+ * Clear app cache
112
+ */
113
+ async clearAppCache(appId) {
114
+ if (appId) {
115
+ await this.cacheManager.removeAppById(appId);
116
+ }
117
+ else {
118
+ await this.cacheManager.clearAppCache();
119
+ }
120
+ }
121
+ }
122
+ //# sourceMappingURL=app-structure-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app-structure-service.js","source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